diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 00000000..7b94908b --- /dev/null +++ b/.clang-format-ignore @@ -0,0 +1,2 @@ +*/DDS.h +*/d3dx12.h diff --git a/.github/linters/.clang-format b/.github/linters/.clang-format new file mode 100644 index 00000000..842e0331 --- /dev/null +++ b/.github/linters/.clang-format @@ -0,0 +1,87 @@ +Language: Cpp +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: false +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignConsecutiveShortCaseStatements: + Enabled: true + AcrossEmptyLines: true + AcrossComments: true + AlignCaseColons: false +AlignTrailingComments: + Kind: Always + OverEmptyLines: 2 +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +BinPackArguments: false +BinPackParameters: false +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: true + SplitEmptyFunction: false + SplitEmptyRecord: false +#requires clang-format 22 +#BreakAfterOpenBracketFunction: true +#BreakBeforeCloseBracketFunction: true +BreakBeforeBinaryOperators: All +BreakBeforeTernaryOperators: false +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakTemplateDeclarations: Yes +ColumnLimit: 140 +ConstructorInitializerAllOnOneLineOrOnePerLine: true +Cpp11BracedListStyle: false +FixNamespaceComments: true +IndentCaseLabels: false +IndentExternBlock: Indent +IndentPPDirectives: None +IndentWidth: 4 +InsertNewlineAtEOF: true +LineEnding: CRLF +NamespaceIndentation: All +PackConstructorInitializers: Never +PointerAlignment: Left +ReflowComments: true +SortIncludes: false +SpaceAfterCStyleCast: false +#requires clang format 21 +#SpaceAfterOperatorKeyword: true +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInContainerLiterals: false +SpacesInParentheses: false +Standard: c++17 +TabWidth: 4 +UseTab: Never diff --git a/.github/linters/.editorconfig-checker.json b/.github/linters/.editorconfig-checker.json index 8bd824ba..db710dd7 100644 --- a/.github/linters/.editorconfig-checker.json +++ b/.github/linters/.editorconfig-checker.json @@ -5,5 +5,8 @@ "LICENSE", "Tests", "Src/d3dx12.h" - ] + ], + "Disable": { + "IndentSize": true + } } diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 8b1a1b48..0dcf6951 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -26,18 +26,19 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Lint Code Base - uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 + uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 env: DEFAULT_BRANCH: origin/main GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} IGNORE_GITIGNORED_FILES: true VALIDATE_ALL_CODEBASE: true VALIDATE_CHECKOV: true + VALIDATE_CLANG_FORMAT: true VALIDATE_EDITORCONFIG: true VALIDATE_GITHUB_ACTIONS: true VALIDATE_JSON: true diff --git a/.github/workflows/mingw.yml b/.github/workflows/mingw.yml index 3c3db899..d41cf08e 100644 --- a/.github/workflows/mingw.yml +++ b/.github/workflows/mingw.yml @@ -50,10 +50,10 @@ jobs: runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Clone test repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: walbourn/directxtk12test path: Tests @@ -104,6 +104,7 @@ jobs: -DCMAKE_TOOLCHAIN_FILE="${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake" -DVCPKG_MANIFEST_DIR="${{ github.workspace }}/build" -DVCPKG_TARGET_TRIPLET="${env:VCPKG_DEFAULT_TRIPLET}" + -DBUILD_BINPLACE=OFF - name: 'Build' working-directory: ${{ github.workspace }} diff --git a/Audio/AudioEngine.cpp b/Audio/AudioEngine.cpp index dea0b819..8ec3dd43 100644 --- a/Audio/AudioEngine.cpp +++ b/Audio/AudioEngine.cpp @@ -17,7 +17,7 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; -//#define VERBOSE_TRACE +// #define VERBOSE_TRACE #ifdef VERBOSE_TRACE #pragma message("NOTE: Verbose tracing enabled") @@ -36,22 +36,22 @@ namespace } } - EngineCallback(EngineCallback&&) = default; - EngineCallback& operator= (EngineCallback&&) = default; + EngineCallback(EngineCallback&&) = default; + EngineCallback& operator=(EngineCallback&&) = default; - EngineCallback(EngineCallback const&) = delete; - EngineCallback& operator= (EngineCallback const&) = delete; + EngineCallback(EngineCallback const&) = delete; + EngineCallback& operator=(EngineCallback const&) = delete; virtual ~EngineCallback() = default; - STDMETHOD_(void, OnProcessingPassStart) () override {} + STDMETHOD_(void, OnProcessingPassStart)() override {} STDMETHOD_(void, OnProcessingPassEnd)() override {} - STDMETHOD_(void, OnCriticalError) (THIS_ HRESULT error) + STDMETHOD_(void, OnCriticalError)(THIS_ HRESULT error) { - #ifndef _DEBUG +#ifndef _DEBUG UNREFERENCED_PARAMETER(error); - #endif +#endif DebugTrace("ERROR: AudioEngine encountered critical error (%08X)\n", static_cast(error)); SetEvent(mCriticalError.get()); } @@ -70,16 +70,15 @@ namespace } } - VoiceCallback(VoiceCallback&&) = default; + VoiceCallback(VoiceCallback&&) = default; VoiceCallback& operator=(VoiceCallback&&) = default; - VoiceCallback(const VoiceCallback&) = delete; + VoiceCallback(const VoiceCallback&) = delete; VoiceCallback& operator=(const VoiceCallback&) = delete; - virtual ~VoiceCallback() - {} + virtual ~VoiceCallback() {} - STDMETHOD_(void, OnVoiceProcessingPassStart) (UINT32) override {} + STDMETHOD_(void, OnVoiceProcessingPassStart)(UINT32) override {} STDMETHOD_(void, OnVoiceProcessingPassEnd)() override {} STDMETHOD_(void, OnStreamEnd)() override {} STDMETHOD_(void, OnBufferStart)(void*) override {} @@ -100,39 +99,38 @@ namespace ScopedHandle mBufferEnd; }; - static const XAUDIO2FX_REVERB_I3DL2_PARAMETERS gReverbPresets[] = - { - XAUDIO2FX_I3DL2_PRESET_DEFAULT, // Reverb_Off - XAUDIO2FX_I3DL2_PRESET_DEFAULT, // Reverb_Default - XAUDIO2FX_I3DL2_PRESET_GENERIC, // Reverb_Generic - XAUDIO2FX_I3DL2_PRESET_FOREST, // Reverb_Forest - XAUDIO2FX_I3DL2_PRESET_PADDEDCELL, // Reverb_PaddedCell - XAUDIO2FX_I3DL2_PRESET_ROOM, // Reverb_Room - XAUDIO2FX_I3DL2_PRESET_BATHROOM, // Reverb_Bathroom - XAUDIO2FX_I3DL2_PRESET_LIVINGROOM, // Reverb_LivingRoom - XAUDIO2FX_I3DL2_PRESET_STONEROOM, // Reverb_StoneRoom - XAUDIO2FX_I3DL2_PRESET_AUDITORIUM, // Reverb_Auditorium - XAUDIO2FX_I3DL2_PRESET_CONCERTHALL, // Reverb_ConcertHall - XAUDIO2FX_I3DL2_PRESET_CAVE, // Reverb_Cave - XAUDIO2FX_I3DL2_PRESET_ARENA, // Reverb_Arena - XAUDIO2FX_I3DL2_PRESET_HANGAR, // Reverb_Hangar - XAUDIO2FX_I3DL2_PRESET_CARPETEDHALLWAY, // Reverb_CarpetedHallway - XAUDIO2FX_I3DL2_PRESET_HALLWAY, // Reverb_Hallway - XAUDIO2FX_I3DL2_PRESET_STONECORRIDOR, // Reverb_StoneCorridor - XAUDIO2FX_I3DL2_PRESET_ALLEY, // Reverb_Alley - XAUDIO2FX_I3DL2_PRESET_CITY, // Reverb_City - XAUDIO2FX_I3DL2_PRESET_MOUNTAINS, // Reverb_Mountains - XAUDIO2FX_I3DL2_PRESET_QUARRY, // Reverb_Quarry - XAUDIO2FX_I3DL2_PRESET_PLAIN, // Reverb_Plain - XAUDIO2FX_I3DL2_PRESET_PARKINGLOT, // Reverb_ParkingLot - XAUDIO2FX_I3DL2_PRESET_SEWERPIPE, // Reverb_SewerPipe - XAUDIO2FX_I3DL2_PRESET_UNDERWATER, // Reverb_Underwater - XAUDIO2FX_I3DL2_PRESET_SMALLROOM, // Reverb_SmallRoom - XAUDIO2FX_I3DL2_PRESET_MEDIUMROOM, // Reverb_MediumRoom - XAUDIO2FX_I3DL2_PRESET_LARGEROOM, // Reverb_LargeRoom - XAUDIO2FX_I3DL2_PRESET_MEDIUMHALL, // Reverb_MediumHall - XAUDIO2FX_I3DL2_PRESET_LARGEHALL, // Reverb_LargeHall - XAUDIO2FX_I3DL2_PRESET_PLATE, // Reverb_Plate + static const XAUDIO2FX_REVERB_I3DL2_PARAMETERS gReverbPresets[] = { + XAUDIO2FX_I3DL2_PRESET_DEFAULT, // Reverb_Off + XAUDIO2FX_I3DL2_PRESET_DEFAULT, // Reverb_Default + XAUDIO2FX_I3DL2_PRESET_GENERIC, // Reverb_Generic + XAUDIO2FX_I3DL2_PRESET_FOREST, // Reverb_Forest + XAUDIO2FX_I3DL2_PRESET_PADDEDCELL, // Reverb_PaddedCell + XAUDIO2FX_I3DL2_PRESET_ROOM, // Reverb_Room + XAUDIO2FX_I3DL2_PRESET_BATHROOM, // Reverb_Bathroom + XAUDIO2FX_I3DL2_PRESET_LIVINGROOM, // Reverb_LivingRoom + XAUDIO2FX_I3DL2_PRESET_STONEROOM, // Reverb_StoneRoom + XAUDIO2FX_I3DL2_PRESET_AUDITORIUM, // Reverb_Auditorium + XAUDIO2FX_I3DL2_PRESET_CONCERTHALL, // Reverb_ConcertHall + XAUDIO2FX_I3DL2_PRESET_CAVE, // Reverb_Cave + XAUDIO2FX_I3DL2_PRESET_ARENA, // Reverb_Arena + XAUDIO2FX_I3DL2_PRESET_HANGAR, // Reverb_Hangar + XAUDIO2FX_I3DL2_PRESET_CARPETEDHALLWAY, // Reverb_CarpetedHallway + XAUDIO2FX_I3DL2_PRESET_HALLWAY, // Reverb_Hallway + XAUDIO2FX_I3DL2_PRESET_STONECORRIDOR, // Reverb_StoneCorridor + XAUDIO2FX_I3DL2_PRESET_ALLEY, // Reverb_Alley + XAUDIO2FX_I3DL2_PRESET_CITY, // Reverb_City + XAUDIO2FX_I3DL2_PRESET_MOUNTAINS, // Reverb_Mountains + XAUDIO2FX_I3DL2_PRESET_QUARRY, // Reverb_Quarry + XAUDIO2FX_I3DL2_PRESET_PLAIN, // Reverb_Plain + XAUDIO2FX_I3DL2_PRESET_PARKINGLOT, // Reverb_ParkingLot + XAUDIO2FX_I3DL2_PRESET_SEWERPIPE, // Reverb_SewerPipe + XAUDIO2FX_I3DL2_PRESET_UNDERWATER, // Reverb_Underwater + XAUDIO2FX_I3DL2_PRESET_SMALLROOM, // Reverb_SmallRoom + XAUDIO2FX_I3DL2_PRESET_MEDIUMROOM, // Reverb_MediumRoom + XAUDIO2FX_I3DL2_PRESET_LARGEROOM, // Reverb_LargeRoom + XAUDIO2FX_I3DL2_PRESET_MEDIUMHALL, // Reverb_MediumHall + XAUDIO2FX_I3DL2_PRESET_LARGEHALL, // Reverb_LargeHall + XAUDIO2FX_I3DL2_PRESET_PLATE, // Reverb_Plate }; constexpr uint32_t c_XAudio3DCalculateDefault = X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_LPF_DIRECT; @@ -164,14 +162,14 @@ namespace unsigned int samplesPerBlock : 16; } adpcm; - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 struct { unsigned int tag : 9; unsigned int channels : 7; unsigned int encoderVersion : 8; } xma; - #endif +#endif unsigned int key; } result; @@ -196,8 +194,8 @@ namespace { case WAVE_FORMAT_PCM: static_assert(WAVE_FORMAT_PCM < 0x1ff, "KeyGen tag is too small"); - result.pcm.tag = WAVE_FORMAT_PCM; - result.pcm.channels = wfx->nChannels; + result.pcm.tag = WAVE_FORMAT_PCM; + result.pcm.channels = wfx->nChannels; result.pcm.bitsPerSample = wfx->wBitsPerSample; break; @@ -207,58 +205,60 @@ namespace if (wfx->wBitsPerSample != 32) return 0; - result.pcm.tag = WAVE_FORMAT_IEEE_FLOAT; - result.pcm.channels = wfx->nChannels; + result.pcm.tag = WAVE_FORMAT_IEEE_FLOAT; + result.pcm.channels = wfx->nChannels; result.pcm.bitsPerSample = 32; break; case WAVE_FORMAT_ADPCM: static_assert(WAVE_FORMAT_ADPCM < 0x1ff, "KeyGen tag is too small"); - result.adpcm.tag = WAVE_FORMAT_ADPCM; + result.adpcm.tag = WAVE_FORMAT_ADPCM; result.adpcm.channels = wfx->nChannels; { - auto wfadpcm = reinterpret_cast(wfx); + auto wfadpcm = reinterpret_cast(wfx); result.adpcm.samplesPerBlock = wfadpcm->wSamplesPerBlock; } break; - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 case WAVE_FORMAT_XMA2: static_assert(WAVE_FORMAT_XMA2 < 0x1ff, "KeyGen tag is too small"); - result.xma.tag = WAVE_FORMAT_XMA2; + result.xma.tag = WAVE_FORMAT_XMA2; result.xma.channels = wfx->nChannels; { auto xmaFmt = reinterpret_cast(wfx); - if ((xmaFmt->LoopBegin > 0) - || (xmaFmt->PlayBegin > 0)) + if ((xmaFmt->LoopBegin > 0) || (xmaFmt->PlayBegin > 0)) return 0; result.xma.encoderVersion = xmaFmt->EncoderVersion; } break; - #endif +#endif - default: - return 0; + default: return 0; } return result.key; } void GetDeviceOutputFormat(const wchar_t* deviceId, WAVEFORMATEX& wfx); -} +} // namespace static_assert(static_cast(std::size(gReverbPresets)) == Reverb_MAX, "AUDIO_ENGINE_REVERB enum mismatch"); - //====================================================================================== // AudioEngine //====================================================================================== -#define SAFE_DESTROY_VOICE(voice) if ( voice ) { voice->DestroyVoice(); voice = nullptr; } +#define SAFE_DESTROY_VOICE(voice) \ + if (voice) \ + { \ + voice->DestroyVoice(); \ + voice = nullptr; \ + } #ifdef __clang__ #pragma clang diagnostic ignored "-Wextra-semi-stmt" @@ -268,38 +268,38 @@ static_assert(static_cast(std::size(gReverbPresets)) == Reverb_MAX class AudioEngine::Impl { public: - Impl() noexcept : - mMasterVoice(nullptr), - mReverbVoice(nullptr), - masterChannelMask(0), - masterChannels(0), - masterRate(0), - defaultRate(44100), - maxVoiceOneshots(SIZE_MAX), - maxVoiceInstances(SIZE_MAX), - mMasterVolume(1.f), - mX3DAudio{}, - mX3DCalcFlags(c_XAudio3DCalculateDefault), - mCriticalError(false), - mReverbEnabled(false), - mEngineFlags(AudioEngine_Default), - mOutputFormat{}, - mCategory(AudioCategory_GameEffects), - mVoiceInstances(0) + Impl() noexcept + : mMasterVoice(nullptr), + mReverbVoice(nullptr), + masterChannelMask(0), + masterChannels(0), + masterRate(0), + defaultRate(44100), + maxVoiceOneshots(SIZE_MAX), + maxVoiceInstances(SIZE_MAX), + mMasterVolume(1.f), + mX3DAudio{}, + mX3DCalcFlags(c_XAudio3DCalculateDefault), + mCriticalError(false), + mReverbEnabled(false), + mEngineFlags(AudioEngine_Default), + mOutputFormat{}, + mCategory(AudioCategory_GameEffects), + mVoiceInstances(0) {} ~Impl() = default; - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; HRESULT Initialize(AUDIO_ENGINE_FLAGS flags, - _In_opt_ const WAVEFORMATEX* wfx, - _In_opt_z_ const wchar_t* deviceId, - AUDIO_STREAM_CATEGORY category); + _In_opt_ const WAVEFORMATEX* wfx, + _In_opt_z_ const wchar_t* deviceId, + AUDIO_STREAM_CATEGORY category); HRESULT Reset(_In_opt_ const WAVEFORMATEX* wfx, _In_opt_z_ const wchar_t* deviceId); @@ -317,70 +317,66 @@ class AudioEngine::Impl void TrimVoicePool(); - void AllocateVoice(_In_ const WAVEFORMATEX* wfx, - SOUND_EFFECT_INSTANCE_FLAGS flags, bool oneshot, + void AllocateVoice(_In_ const WAVEFORMATEX* wfx, + SOUND_EFFECT_INSTANCE_FLAGS flags, + bool oneshot, _Outptr_result_maybenull_ IXAudio2SourceVoice** voice); void DestroyVoice(_In_ IXAudio2SourceVoice* voice) noexcept; void RegisterNotify(_In_ IVoiceNotify* notify, bool usesUpdate); void UnregisterNotify(_In_ IVoiceNotify* notify, bool oneshots, bool usesUpdate); - ComPtr xaudio2; - IXAudio2MasteringVoice* mMasterVoice; - IXAudio2SubmixVoice* mReverbVoice; + ComPtr xaudio2; + IXAudio2MasteringVoice* mMasterVoice; + IXAudio2SubmixVoice* mReverbVoice; - uint32_t masterChannelMask; - uint32_t masterChannels; - uint32_t masterRate; + uint32_t masterChannelMask; + uint32_t masterChannels; + uint32_t masterRate; - int defaultRate; - size_t maxVoiceOneshots; - size_t maxVoiceInstances; - float mMasterVolume; + int defaultRate; + size_t maxVoiceOneshots; + size_t maxVoiceInstances; + float mMasterVolume; - X3DAUDIO_HANDLE mX3DAudio; - uint32_t mX3DCalcFlags; + X3DAUDIO_HANDLE mX3DAudio; + uint32_t mX3DCalcFlags; - bool mCriticalError; - bool mReverbEnabled; + bool mCriticalError; + bool mReverbEnabled; - AUDIO_ENGINE_FLAGS mEngineFlags; - WAVEFORMATEX mOutputFormat; + AUDIO_ENGINE_FLAGS mEngineFlags; + WAVEFORMATEX mOutputFormat; private: - using notifylist_t = std::set; + using notifylist_t = std::set; using oneshotlist_t = std::list>; - using voicepool_t = std::unordered_multimap; - - AUDIO_STREAM_CATEGORY mCategory; - ComPtr mReverbEffect; - ComPtr mVolumeLimiter; - oneshotlist_t mOneShots; - voicepool_t mVoicePool; - notifylist_t mNotifyObjects; - notifylist_t mNotifyUpdates; - size_t mVoiceInstances; - VoiceCallback mVoiceCallback; - EngineCallback mEngineCallback; + using voicepool_t = std::unordered_multimap; + + AUDIO_STREAM_CATEGORY mCategory; + ComPtr mReverbEffect; + ComPtr mVolumeLimiter; + oneshotlist_t mOneShots; + voicepool_t mVoicePool; + notifylist_t mNotifyObjects; + notifylist_t mNotifyUpdates; + size_t mVoiceInstances; + VoiceCallback mVoiceCallback; + EngineCallback mEngineCallback; }; - -_Use_decl_annotations_ -HRESULT AudioEngine::Impl::Initialize( - AUDIO_ENGINE_FLAGS flags, - const WAVEFORMATEX* wfx, - const wchar_t* deviceId, - AUDIO_STREAM_CATEGORY category) +_Use_decl_annotations_ HRESULT AudioEngine::Impl::Initialize(AUDIO_ENGINE_FLAGS flags, + const WAVEFORMATEX* wfx, + const wchar_t* deviceId, + AUDIO_STREAM_CATEGORY category) { mEngineFlags = flags; - mCategory = category; + mCategory = category; return Reset(wfx, deviceId); } - -_Use_decl_annotations_ -HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) +_Use_decl_annotations_ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) { if (wfx) { @@ -401,7 +397,7 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI assert(mReverbVoice == nullptr); masterChannelMask = masterChannels = masterRate = 0; - mOutputFormat = {}; + mOutputFormat = {}; memset(&mX3DAudio, 0, X3DAUDIO_HANDLE_BYTESIZE); mX3DCalcFlags = c_XAudio3DCalculateDefault; @@ -419,19 +415,19 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI if (mEngineFlags & AudioEngine_Debug) { XAUDIO2_DEBUG_CONFIGURATION debug = {}; - debug.TraceMask = XAUDIO2_LOG_ERRORS | XAUDIO2_LOG_WARNINGS; - debug.BreakMask = XAUDIO2_LOG_ERRORS; + debug.TraceMask = XAUDIO2_LOG_ERRORS | XAUDIO2_LOG_WARNINGS; + debug.BreakMask = XAUDIO2_LOG_ERRORS; xaudio2->SetDebugConfiguration(&debug, nullptr); - #ifdef USING_XAUDIO2_9 +#ifdef USING_XAUDIO2_9 DebugTrace("INFO: XAudio 2.9 debugging enabled\n"); - #else // USING_XAUDIO2_8 - // To see the trace output, you need to view ETW logs for this application: - // Go to Control Panel, Administrative Tools, Event Viewer. - // View->Show Analytic and Debug Logs. - // Applications and Services Logs / Microsoft / Windows / XAudio2. - // Right click on Microsoft Windows XAudio2 debug logging, Properties, then Enable Logging, and hit OK +#else // USING_XAUDIO2_8 + // To see the trace output, you need to view ETW logs for this application: + // Go to Control Panel, Administrative Tools, Event Viewer. + // View->Show Analytic and Debug Logs. + // Applications and Services Logs / Microsoft / Windows / XAudio2. + // Right click on Microsoft Windows XAudio2 debug logging, Properties, then Enable Logging, and hit OK DebugTrace("INFO: XAudio 2.8 debugging enabled\n"); - #endif +#endif } if (mEngineFlags & AudioEngine_DisableVoiceReuse) @@ -452,7 +448,10 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI hr = xaudio2->CreateMasteringVoice(&mMasterVoice, (wfx) ? wfx->nChannels : 0u /*XAUDIO2_DEFAULT_CHANNELS */, (wfx) ? wfx->nSamplesPerSec : 0u /* XAUDIO2_DEFAULT_SAMPLERATE */, - 0u, deviceId, nullptr, mCategory); + 0u, + deviceId, + nullptr, + mCategory); if (FAILED(hr)) { xaudio2.Reset(); @@ -472,11 +471,10 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI mMasterVoice->GetVoiceDetails(&details); masterChannelMask = dwChannelMask; - masterChannels = details.InputChannels; - masterRate = details.InputSampleRate; + masterChannels = details.InputChannels; + masterRate = details.InputSampleRate; - DebugTrace("INFO: mastering voice has %u channels, %u sample rate, %08X channel mask\n", - masterChannels, masterRate, masterChannelMask); + DebugTrace("INFO: mastering voice has %u channels, %u sample rate, %08X channel mask\n", masterChannels, masterRate, masterChannelMask); if (mMasterVolume != 1.f) { @@ -489,8 +487,8 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI } } - mOutputFormat.wFormatTag = WAVE_FORMAT_PCM; - mOutputFormat.nChannels = static_cast(details.InputChannels); + mOutputFormat.wFormatTag = WAVE_FORMAT_PCM; + mOutputFormat.nChannels = static_cast(details.InputChannels); mOutputFormat.nSamplesPerSec = details.InputSampleRate; mOutputFormat.wBitsPerSample = 16; GetDeviceOutputFormat(deviceId, mOutputFormat); @@ -501,8 +499,8 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI if (mEngineFlags & AudioEngine_UseMasteringLimiter) { FXMASTERINGLIMITER_PARAMETERS params = {}; - params.Release = FXMASTERINGLIMITER_DEFAULT_RELEASE; - params.Loudness = FXMASTERINGLIMITER_DEFAULT_LOUDNESS; + params.Release = FXMASTERINGLIMITER_DEFAULT_RELEASE; + params.Loudness = FXMASTERINGLIMITER_DEFAULT_LOUDNESS; hr = CreateFX(__uuidof(FXMasteringLimiter), mVolumeLimiter.ReleaseAndGetAddressOf(), ¶ms, sizeof(params)); if (FAILED(hr)) @@ -513,12 +511,12 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI } XAUDIO2_EFFECT_DESCRIPTOR desc = {}; - desc.InitialState = TRUE; - desc.OutputChannels = masterChannels; - desc.pEffect = mVolumeLimiter.Get(); + desc.InitialState = TRUE; + desc.OutputChannels = masterChannels; + desc.pEffect = mVolumeLimiter.Get(); XAUDIO2_EFFECT_CHAIN chain = { 1, &desc }; - hr = mMasterVoice->SetEffectChain(&chain); + hr = mMasterVoice->SetEffectChain(&chain); if (FAILED(hr)) { SAFE_DESTROY_VOICE(mMasterVoice); @@ -544,14 +542,18 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI return hr; } - XAUDIO2_EFFECT_DESCRIPTOR effects[] = { { mReverbEffect.Get(), TRUE, 1 } }; - XAUDIO2_EFFECT_CHAIN effectChain = { 1, effects }; + XAUDIO2_EFFECT_DESCRIPTOR effects[] = { { mReverbEffect.Get(), TRUE, 1 } }; + XAUDIO2_EFFECT_CHAIN effectChain = { 1, effects }; mReverbEnabled = true; - hr = xaudio2->CreateSubmixVoice(&mReverbVoice, 1, masterRate, - (mEngineFlags & AudioEngine_ReverbUseFilters) ? XAUDIO2_VOICE_USEFILTER : 0u, 0u, - nullptr, &effectChain); + hr = xaudio2->CreateSubmixVoice(&mReverbVoice, + 1, + masterRate, + (mEngineFlags & AudioEngine_ReverbUseFilters) ? XAUDIO2_VOICE_USEFILTER : 0u, + 0u, + nullptr, + &effectChain); if (FAILED(hr)) { SAFE_DESTROY_VOICE(mMasterVoice); @@ -562,13 +564,13 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI } XAUDIO2FX_REVERB_PARAMETERS native = {}; - ReverbConvertI3DL2ToNative( - &gReverbPresets[Reverb_Default], + ReverbConvertI3DL2ToNative(&gReverbPresets[Reverb_Default], &native #ifdef __MINGW32__ - , FALSE + , + FALSE #endif - ); + ); hr = mReverbVoice->SetEffectParameters(0, &native, sizeof(XAUDIO2FX_REVERB_PARAMETERS)); if (FAILED(hr)) @@ -630,7 +632,6 @@ HRESULT AudioEngine::Impl::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceI return S_OK; } - void AudioEngine::Impl::SetSilentMode() { for (auto it : mNotifyObjects) @@ -663,7 +664,6 @@ void AudioEngine::Impl::SetSilentMode() xaudio2.Reset(); } - void AudioEngine::Impl::Shutdown() noexcept { for (auto it : mNotifyObjects) @@ -702,7 +702,7 @@ void AudioEngine::Impl::Shutdown() noexcept xaudio2.Reset(); masterChannelMask = masterChannels = masterRate = 0; - mOutputFormat = {}; + mOutputFormat = {}; mCriticalError = false; mReverbEnabled = false; @@ -711,7 +711,6 @@ void AudioEngine::Impl::Shutdown() noexcept } } - bool AudioEngine::Impl::Update() { if (!xaudio2) @@ -721,10 +720,9 @@ bool AudioEngine::Impl::Update() switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { default: - case WAIT_TIMEOUT: - break; + case WAIT_TIMEOUT: break; - case WAIT_OBJECT_0: // OnCritialError + case WAIT_OBJECT_0: // OnCritialError mCriticalError = true; SetSilentMode(); @@ -732,7 +730,7 @@ bool AudioEngine::Impl::Update() case WAIT_OBJECT_0 + 1: // OnBufferEnd // Scan for completed one-shot voices - for (auto it = mOneShots.begin(); it != mOneShots.end(); ) + for (auto it = mOneShots.begin(); it != mOneShots.end();) { assert(it->second != nullptr); @@ -745,18 +743,18 @@ bool AudioEngine::Impl::Update() if (it->first) { // Put voice back into voice pool for reuse since it has a non-zero voiceKey - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO: One-shot voice being saved for reuse (%08X)\n", it->first); - #endif +#endif voicepool_t::value_type v(it->first, it->second); mVoicePool.emplace(v); } else { // Voice is to be destroyed rather than reused - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO: Destroying one-shot voice\n"); - #endif +#endif it->second->DestroyVoice(); } it = mOneShots.erase(it); @@ -782,9 +780,7 @@ bool AudioEngine::Impl::Update() return true; } - -_Use_decl_annotations_ -void AudioEngine::Impl::SetReverb(const XAUDIO2FX_REVERB_PARAMETERS* native) noexcept +_Use_decl_annotations_ void AudioEngine::Impl::SetReverb(const XAUDIO2FX_REVERB_PARAMETERS* native) noexcept { if (!mReverbVoice) return; @@ -794,7 +790,7 @@ void AudioEngine::Impl::SetReverb(const XAUDIO2FX_REVERB_PARAMETERS* native) noe if (!mReverbEnabled) { mReverbEnabled = true; - std::ignore = mReverbVoice->EnableEffect(0); + std::ignore = mReverbVoice->EnableEffect(0); } std::ignore = mReverbVoice->SetEffectParameters(0, native, sizeof(XAUDIO2FX_REVERB_PARAMETERS)); @@ -802,11 +798,10 @@ void AudioEngine::Impl::SetReverb(const XAUDIO2FX_REVERB_PARAMETERS* native) noe else if (mReverbEnabled) { mReverbEnabled = false; - std::ignore = mReverbVoice->DisableEffect(0); + std::ignore = mReverbVoice->DisableEffect(0); } } - void AudioEngine::Impl::SetMasteringLimit(int release, int loudness) { if (!mVolumeLimiter || !mMasterVoice) @@ -819,20 +814,19 @@ void AudioEngine::Impl::SetMasteringLimit(int release, int loudness) throw std::out_of_range("AudioEngine::SetMasteringLimit"); FXMASTERINGLIMITER_PARAMETERS params = {}; - params.Release = static_cast(release); - params.Loudness = static_cast(loudness); + params.Release = static_cast(release); + params.Loudness = static_cast(loudness); HRESULT hr = mMasterVoice->SetEffectParameters(0, ¶ms, sizeof(params)); ThrowIfFailed(hr); } - AudioStatistics AudioEngine::Impl::GetStatistics() const { AudioStatistics stats = {}; stats.allocatedVoices = stats.allocatedVoicesOneShot = mOneShots.size() + mVoicePool.size(); - stats.allocatedVoicesIdle = mVoicePool.size(); + stats.allocatedVoicesIdle = mVoicePool.size(); for (const auto it : mNotifyObjects) { @@ -845,7 +839,6 @@ AudioStatistics AudioEngine::Impl::GetStatistics() const return stats; } - void AudioEngine::Impl::TrimVoicePool() { for (auto it : mNotifyObjects) @@ -862,13 +855,8 @@ void AudioEngine::Impl::TrimVoicePool() mVoicePool.clear(); } - -_Use_decl_annotations_ -void AudioEngine::Impl::AllocateVoice( - const WAVEFORMATEX* wfx, - SOUND_EFFECT_INSTANCE_FLAGS flags, - bool oneshot, - IXAudio2SourceVoice** voice) +_Use_decl_annotations_ void +AudioEngine::Impl::AllocateVoice(const WAVEFORMATEX* wfx, SOUND_EFFECT_INSTANCE_FLAGS flags, bool oneshot, IXAudio2SourceVoice** voice) { if (!wfx) throw std::invalid_argument("Wave format is required\n"); @@ -893,24 +881,31 @@ void AudioEngine::Impl::AllocateVoice( { if (flags & (SoundEffectInstance_Use3D | SoundEffectInstance_ReverbUseFilters | SoundEffectInstance_NoSetPitch)) { - DebugTrace((flags & SoundEffectInstance_NoSetPitch) - ? "ERROR: One-shot voices must support pitch-shifting for voice reuse\n" - : "ERROR: One-use voices cannot use 3D positional audio\n"); + DebugTrace((flags & SoundEffectInstance_NoSetPitch) ? "ERROR: One-shot voices must support pitch-shifting for voice reuse\n" : + "ERROR: One-use voices cannot use 3D positional audio\n"); throw std::invalid_argument("Invalid flags for one-shot voice"); } - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE if (wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { DebugTrace("INFO: Requesting one-shot: Format Tag EXTENSIBLE %u, %u channels, %u-bit, %u blkalign, %u Hz\n", - GetFormatTag(wfx), wfx->nChannels, wfx->wBitsPerSample, wfx->nBlockAlign, wfx->nSamplesPerSec); + GetFormatTag(wfx), + wfx->nChannels, + wfx->wBitsPerSample, + wfx->nBlockAlign, + wfx->nSamplesPerSec); } else { DebugTrace("INFO: Requesting one-shot: Format Tag %u, %u channels, %u-bit, %u blkalign, %u Hz\n", - wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nBlockAlign, wfx->nSamplesPerSec); + wfx->wFormatTag, + wfx->nChannels, + wfx->wBitsPerSample, + wfx->nBlockAlign, + wfx->nSamplesPerSec); } - #endif +#endif if (!(mEngineFlags & AudioEngine_DisableVoiceReuse)) { @@ -945,7 +940,9 @@ void AudioEngine::Impl::AllocateVoice( else if ((mVoicePool.size() + mOneShots.size() + 1) >= maxVoiceOneshots) { DebugTrace("WARNING: Too many one-shot voices in use (%zu + %zu >= %zu); one-shot not played\n", - mVoicePool.size(), mOneShots.size() + 1, maxVoiceOneshots); + mVoicePool.size(), + mOneShots.size() + 1, + maxVoiceOneshots); return; } else @@ -953,40 +950,36 @@ void AudioEngine::Impl::AllocateVoice( // makeVoiceKey already constrained the supported wfx formats to those supported for reuse char buff[64] = {}; - auto wfmt = reinterpret_cast(buff); + auto wfmt = reinterpret_cast(buff); const uint32_t tag = GetFormatTag(wfx); switch (tag) { - case WAVE_FORMAT_PCM: - CreateIntegerPCM(wfmt, defaultRate, wfx->nChannels, wfx->wBitsPerSample); - break; - - case WAVE_FORMAT_IEEE_FLOAT: - CreateFloatPCM(wfmt, defaultRate, wfx->nChannels); - break; - - case WAVE_FORMAT_ADPCM: - { - auto wfadpcm = reinterpret_cast(wfx); - CreateADPCM(wfmt, sizeof(buff), defaultRate, wfx->nChannels, wfadpcm->wSamplesPerBlock); - } - break; - - #ifdef DIRECTX_ENABLE_XMA2 - case WAVE_FORMAT_XMA2: - CreateXMA2(wfmt, sizeof(buff), defaultRate, wfx->nChannels, 65536, 2, 0); - break; - #endif - - default: - throw std::invalid_argument("Unsupported wave format"); + case WAVE_FORMAT_PCM: CreateIntegerPCM(wfmt, defaultRate, wfx->nChannels, wfx->wBitsPerSample); break; + + case WAVE_FORMAT_IEEE_FLOAT: CreateFloatPCM(wfmt, defaultRate, wfx->nChannels); break; + + case WAVE_FORMAT_ADPCM: { + auto wfadpcm = reinterpret_cast(wfx); + CreateADPCM(wfmt, sizeof(buff), defaultRate, wfx->nChannels, wfadpcm->wSamplesPerBlock); } + break; - #ifdef VERBOSE_TRACE +#ifdef DIRECTX_ENABLE_XMA2 + case WAVE_FORMAT_XMA2: CreateXMA2(wfmt, sizeof(buff), defaultRate, wfx->nChannels, 65536, 2, 0); break; +#endif + + default: throw std::invalid_argument("Unsupported wave format"); + } + +#ifdef VERBOSE_TRACE DebugTrace("INFO: Allocate reuse voice: Format Tag %u, %u channels, %u-bit, %u blkalign, %u Hz\n", - wfmt->wFormatTag, wfmt->nChannels, wfmt->wBitsPerSample, wfmt->nBlockAlign, wfmt->nSamplesPerSec); - #endif + wfmt->wFormatTag, + wfmt->nChannels, + wfmt->wBitsPerSample, + wfmt->nBlockAlign, + wfmt->nSamplesPerSec); +#endif assert(voiceKey == makeVoiceKey(wfmt)); @@ -1016,14 +1009,15 @@ void AudioEngine::Impl::AllocateVoice( if ((mVoicePool.size() + mOneShots.size() + 1) >= maxVoiceOneshots) { DebugTrace("WARNING: Too many one-shot voices in use (%zu + %zu >= %zu); one-shot not played; see TrimVoicePool\n", - mVoicePool.size(), mOneShots.size() + 1, maxVoiceOneshots); + mVoicePool.size(), + mOneShots.size() + 1, + maxVoiceOneshots); return; } } else if ((mVoiceInstances + 1) >= maxVoiceInstances) { - DebugTrace("ERROR: Too many instance voices (%zu >= %zu); see TrimVoicePool\n", - mVoiceInstances + 1, maxVoiceInstances); + DebugTrace("ERROR: Too many instance voices (%zu >= %zu); see TrimVoicePool\n", mVoiceInstances + 1, maxVoiceInstances); throw std::runtime_error("Too many instance voices"); } @@ -1033,25 +1027,33 @@ void AudioEngine::Impl::AllocateVoice( if (flags & SoundEffectInstance_Use3D) { XAUDIO2_SEND_DESCRIPTOR sendDescriptors[2] = {}; - sendDescriptors[0].Flags = sendDescriptors[1].Flags = (flags & SoundEffectInstance_ReverbUseFilters) - ? XAUDIO2_SEND_USEFILTER : 0u; - sendDescriptors[0].pOutputVoice = mMasterVoice; - sendDescriptors[1].pOutputVoice = mReverbVoice; + sendDescriptors[0].Flags = sendDescriptors[1].Flags + = (flags & SoundEffectInstance_ReverbUseFilters) ? XAUDIO2_SEND_USEFILTER : 0u; + sendDescriptors[0].pOutputVoice = mMasterVoice; + sendDescriptors[1].pOutputVoice = mReverbVoice; const XAUDIO2_VOICE_SENDS sendList = { mReverbVoice ? 2U : 1U, sendDescriptors }; - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO: Allocate voice 3D: Format Tag %u, %u channels, %u-bit, %u blkalign, %u Hz\n", - wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nBlockAlign, wfx->nSamplesPerSec); - #endif + wfx->wFormatTag, + wfx->nChannels, + wfx->wBitsPerSample, + wfx->nBlockAlign, + wfx->nSamplesPerSec); +#endif hr = xaudio2->CreateSourceVoice(voice, wfx, vflags, XAUDIO2_DEFAULT_FREQ_RATIO, &mVoiceCallback, &sendList, nullptr); } else { - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO: Allocate voice: Format Tag %u, %u channels, %u-bit, %u blkalign, %u Hz\n", - wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nBlockAlign, wfx->nSamplesPerSec); - #endif + wfx->wFormatTag, + wfx->nChannels, + wfx->wBitsPerSample, + wfx->nBlockAlign, + wfx->nSamplesPerSec); +#endif hr = xaudio2->CreateSourceVoice(voice, wfx, vflags, XAUDIO2_DEFAULT_FREQ_RATIO, &mVoiceCallback, nullptr, nullptr); } @@ -1074,7 +1076,6 @@ void AudioEngine::Impl::AllocateVoice( } } - void AudioEngine::Impl::DestroyVoice(_In_ IXAudio2SourceVoice* voice) noexcept { if (!voice) @@ -1105,7 +1106,6 @@ void AudioEngine::Impl::DestroyVoice(_In_ IXAudio2SourceVoice* voice) noexcept voice->DestroyVoice(); } - void AudioEngine::Impl::RegisterNotify(_In_ IVoiceNotify* notify, bool usesUpdate) { assert(notify != nullptr); @@ -1117,7 +1117,6 @@ void AudioEngine::Impl::RegisterNotify(_In_ IVoiceNotify* notify, bool usesUpdat } } - void AudioEngine::Impl::UnregisterNotify(_In_ IVoiceNotify* notify, bool usesOneShots, bool usesUpdate) { assert(notify != nullptr); @@ -1139,7 +1138,7 @@ void AudioEngine::Impl::UnregisterNotify(_In_ IVoiceNotify* notify, bool usesOne { std::ignore = it.second->Stop(0); std::ignore = it.second->FlushSourceBuffers(); - setevent = true; + setevent = true; } } @@ -1156,18 +1155,15 @@ void AudioEngine::Impl::UnregisterNotify(_In_ IVoiceNotify* notify, bool usesOne } } - //-------------------------------------------------------------------------------------- // AudioEngine //-------------------------------------------------------------------------------------- // Public constructor. -_Use_decl_annotations_ -AudioEngine::AudioEngine( - AUDIO_ENGINE_FLAGS flags, - const WAVEFORMATEX* wfx, - const wchar_t* deviceId, - AUDIO_STREAM_CATEGORY category) noexcept(false) +_Use_decl_annotations_ AudioEngine::AudioEngine(AUDIO_ENGINE_FLAGS flags, + const WAVEFORMATEX* wfx, + const wchar_t* deviceId, + AUDIO_STREAM_CATEGORY category) noexcept(false) : pImpl(std::make_unique()) { HRESULT hr = pImpl->Initialize(flags, wfx, deviceId, category); @@ -1200,18 +1196,15 @@ AudioEngine::AudioEngine( } else { - DebugTrace("ERROR: AudioEngine failed (%08X) to initialize using device [%ls]\n", - static_cast(hr), deviceName); + DebugTrace("ERROR: AudioEngine failed (%08X) to initialize using device [%ls]\n", static_cast(hr), deviceName); throw std::runtime_error("AudioEngine"); } } } - // Move ctor/operator. -AudioEngine::AudioEngine(AudioEngine&&) noexcept = default; -AudioEngine& AudioEngine::operator= (AudioEngine&&) noexcept = default; - +AudioEngine::AudioEngine(AudioEngine&&) noexcept = default; +AudioEngine& AudioEngine::operator=(AudioEngine&&) noexcept = default; // Public destructor. AudioEngine::~AudioEngine() @@ -1222,16 +1215,13 @@ AudioEngine::~AudioEngine() } } - // Public methods. bool AudioEngine::Update() { return pImpl->Update(); } - -_Use_decl_annotations_ -bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) +_Use_decl_annotations_ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) { if (pImpl->xaudio2) { @@ -1271,8 +1261,7 @@ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) } else { - DebugTrace("ERROR: AudioEngine failed (%08X) to Reset using device [%ls]\n", - static_cast(hr), deviceName); + DebugTrace("ERROR: AudioEngine failed (%08X) to Reset using device [%ls]\n", static_cast(hr), deviceName); throw std::runtime_error("AudioEngine::Reset"); } } @@ -1282,7 +1271,6 @@ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) return true; } - void AudioEngine::Suspend() noexcept { if (!pImpl->xaudio2) @@ -1291,7 +1279,6 @@ void AudioEngine::Suspend() noexcept pImpl->xaudio2->StopEngine(); } - void AudioEngine::Resume() { if (!pImpl->xaudio2) @@ -1305,13 +1292,11 @@ void AudioEngine::Resume() } } - float AudioEngine::GetMasterVolume() const noexcept { return pImpl->mMasterVolume; } - void AudioEngine::SetMasterVolume(float volume) { assert(volume >= -XAUDIO2_MAX_VOLUME_LEVEL && volume <= XAUDIO2_MAX_VOLUME_LEVEL); @@ -1325,7 +1310,6 @@ void AudioEngine::SetMasterVolume(float volume) } } - void AudioEngine::SetReverb(AUDIO_ENGINE_REVERB reverb) { if (reverb >= Reverb_MAX) @@ -1338,38 +1322,33 @@ void AudioEngine::SetReverb(AUDIO_ENGINE_REVERB reverb) else { XAUDIO2FX_REVERB_PARAMETERS native = {}; - ReverbConvertI3DL2ToNative( - &gReverbPresets[reverb], + ReverbConvertI3DL2ToNative(&gReverbPresets[reverb], &native #ifdef __MINGW32__ - , FALSE + , + FALSE #endif - ); + ); pImpl->SetReverb(&native); } } - -_Use_decl_annotations_ -void AudioEngine::SetReverb(const XAUDIO2FX_REVERB_PARAMETERS* native) +_Use_decl_annotations_ void AudioEngine::SetReverb(const XAUDIO2FX_REVERB_PARAMETERS* native) { pImpl->SetReverb(native); } - void AudioEngine::SetMasteringLimit(int release, int loudness) { pImpl->SetMasteringLimit(release, loudness); } - // Public accessors. AudioStatistics AudioEngine::GetStatistics() const { return pImpl->GetStatistics(); } - WAVEFORMATEXTENSIBLE AudioEngine::GetOutputFormat() const noexcept { WAVEFORMATEXTENSIBLE wfx = {}; @@ -1377,14 +1356,14 @@ WAVEFORMATEXTENSIBLE AudioEngine::GetOutputFormat() const noexcept if (!pImpl->xaudio2) return wfx; - wfx.Format = pImpl->mOutputFormat; - wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); + wfx.Format = pImpl->mOutputFormat; + wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; wfx.Samples.wValidBitsPerSample = wfx.Format.wBitsPerSample; - wfx.dwChannelMask = pImpl->masterChannelMask; + wfx.dwChannelMask = pImpl->masterChannelMask; - wfx.Format.nBlockAlign = static_cast(wfx.Format.nChannels * wfx.Format.wBitsPerSample / 8); + wfx.Format.nBlockAlign = static_cast(wfx.Format.nChannels * wfx.Format.wBitsPerSample / 8); wfx.Format.nAvgBytesPerSec = wfx.Format.nSamplesPerSec * wfx.Format.nBlockAlign; static const GUID s_wfexBase = { 0x00000000, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 } }; @@ -1394,37 +1373,31 @@ WAVEFORMATEXTENSIBLE AudioEngine::GetOutputFormat() const noexcept return wfx; } - uint32_t AudioEngine::GetChannelMask() const noexcept { return pImpl->masterChannelMask; } - int AudioEngine::GetOutputSampleRate() const noexcept { return static_cast(pImpl->masterRate); } - unsigned int AudioEngine::GetOutputChannels() const noexcept { return pImpl->masterChannels; } - bool AudioEngine::IsAudioDevicePresent() const noexcept { return pImpl->xaudio2 && !pImpl->mCriticalError; } - bool AudioEngine::IsCriticalError() const noexcept { return pImpl->mCriticalError; } - // Voice management. void AudioEngine::SetDefaultSampleRate(int sampleRate) { @@ -1434,7 +1407,6 @@ void AudioEngine::SetDefaultSampleRate(int sampleRate) pImpl->defaultRate = sampleRate; } - void AudioEngine::SetMaxVoicePool(size_t maxOneShots, size_t maxInstances) { if (maxOneShots > 0) @@ -1444,66 +1416,52 @@ void AudioEngine::SetMaxVoicePool(size_t maxOneShots, size_t maxInstances) pImpl->maxVoiceInstances = maxInstances; } - void AudioEngine::TrimVoicePool() { pImpl->TrimVoicePool(); } - -_Use_decl_annotations_ -void AudioEngine::AllocateVoice( - const WAVEFORMATEX* wfx, - SOUND_EFFECT_INSTANCE_FLAGS flags, - bool oneshot, - IXAudio2SourceVoice** voice) +_Use_decl_annotations_ void +AudioEngine::AllocateVoice(const WAVEFORMATEX* wfx, SOUND_EFFECT_INSTANCE_FLAGS flags, bool oneshot, IXAudio2SourceVoice** voice) { pImpl->AllocateVoice(wfx, flags, oneshot, voice); } - void AudioEngine::DestroyVoice(_In_ IXAudio2SourceVoice* voice) noexcept { pImpl->DestroyVoice(voice); } - void AudioEngine::RegisterNotify(_In_ IVoiceNotify* notify, bool usesUpdate) { pImpl->RegisterNotify(notify, usesUpdate); } - void AudioEngine::UnregisterNotify(_In_ IVoiceNotify* notify, bool oneshots, bool usesUpdate) { pImpl->UnregisterNotify(notify, oneshots, usesUpdate); } - IXAudio2* AudioEngine::GetInterface() const noexcept { return pImpl->xaudio2.Get(); } - IXAudio2MasteringVoice* AudioEngine::GetMasterVoice() const noexcept { return pImpl->mMasterVoice; } - IXAudio2SubmixVoice* AudioEngine::GetReverbVoice() const noexcept { return pImpl->mReverbVoice; } - X3DAUDIO_HANDLE& AudioEngine::Get3DHandle() const noexcept { return pImpl->mX3DAudio; } - uint32_t AudioEngine::Get3DCalculateFlags() const noexcept { return pImpl->mX3DCalcFlags; @@ -1520,9 +1478,9 @@ uint32_t AudioEngine::Get3DCalculateFlags() const noexcept // -or- use XAudio2Redist -or- use XAudio 2.8. #ifdef _MSC_VER -#pragma comment(lib,"runtimeobject.lib") +#pragma comment(lib, "runtimeobject.lib") #pragma warning(push) -#pragma warning(disable: 4471 5204 5256 6553) +#pragma warning(disable : 4471 5204 5256 6553) #endif #ifdef __clang__ #pragma clang diagnostic ignored "-Wnonportable-system-include-path" @@ -1545,16 +1503,18 @@ namespace class PropertyIterator : public Microsoft::WRL::RuntimeClass> { - #if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) - InspectableClass(L"AudioEngine.PropertyIterator", FullTrust) - #else - InspectableClass(L"AudioEngine.PropertyIterator", BaseTrust) - #endif +#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) + InspectableClass(L"AudioEngine.PropertyIterator", FullTrust) +#else + InspectableClass(L"AudioEngine.PropertyIterator", BaseTrust) +#endif - public: - PropertyIterator() : mFirst(true), mString(c_PKEY_AudioEngine_DeviceFormat) {} + public : PropertyIterator() + : mFirst(true), + mString(c_PKEY_AudioEngine_DeviceFormat) + {} - HRESULT STDMETHODCALLTYPE get_Current(HSTRING *current) override + HRESULT STDMETHODCALLTYPE get_Current(HSTRING* current) override { if (!current) return E_INVALIDARG; @@ -1567,7 +1527,7 @@ namespace return S_OK; } - HRESULT STDMETHODCALLTYPE get_HasCurrent(boolean *hasCurrent) override + HRESULT STDMETHODCALLTYPE get_HasCurrent(boolean* hasCurrent) override { if (!hasCurrent) return E_INVALIDARG; @@ -1576,18 +1536,18 @@ namespace return S_OK; } - HRESULT STDMETHODCALLTYPE MoveNext(boolean *hasCurrent) override + HRESULT STDMETHODCALLTYPE MoveNext(boolean* hasCurrent) override { if (!hasCurrent) return E_INVALIDARG; *hasCurrent = FALSE; - mFirst = false; + mFirst = false; return S_OK; } private: - bool mFirst; + bool mFirst; Microsoft::WRL::Wrappers::HStringReference mString; ~PropertyIterator() override = default; @@ -1595,20 +1555,19 @@ namespace class PropertyList : public Microsoft::WRL::RuntimeClass> { - #if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) - InspectableClass(L"AudioEngine.PropertyList", FullTrust) - #else - InspectableClass(L"AudioEngine.PropertyList", BaseTrust) - #endif - - public: - HRESULT STDMETHODCALLTYPE First(ABI::Windows::Foundation::Collections::IIterator **first) override +#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) + InspectableClass(L"AudioEngine.PropertyList", FullTrust) +#else + InspectableClass(L"AudioEngine.PropertyList", BaseTrust) +#endif + + public : HRESULT STDMETHODCALLTYPE First(ABI::Windows::Foundation::Collections::IIterator** first) override { if (!first) return E_INVALIDARG; ComPtr p = Microsoft::WRL::Make(); - *first = p.Detach(); + *first = p.Detach(); return S_OK; } @@ -1624,10 +1583,10 @@ namespace using namespace ABI::Windows::Foundation::Collections; using namespace ABI::Windows::Devices::Enumeration; - #if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) +#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); ThrowIfFailed(initialize); - #endif +#endif ComPtr diFactory; HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Devices_Enumeration_DeviceInformation).Get(), &diFactory); @@ -1651,7 +1610,7 @@ namespace } ComPtr> operation; - ComPtr> props = Make(); + ComPtr> props = Make(); hr = diFactory->CreateFromIdAsyncAdditionalProperties(id.Get(), props.Get(), operation.GetAddressOf()); if (FAILED(hr)) @@ -1698,7 +1657,7 @@ namespace if (ptype == PropertyType_UInt8Array) { UINT32 length = 0; - BYTE* ptr; + BYTE* ptr; ThrowIfFailed(pvalue->GetUInt8Array(&length, &ptr)); if (length >= sizeof(WAVEFORMATEX)) @@ -1711,7 +1670,7 @@ namespace } } } -} +} // namespace std::vector AudioEngine::GetRendererDetails() { @@ -1761,7 +1720,7 @@ std::vector AudioEngine::GetRendererDetails() ThrowIfFailed(hr); unsigned int count = 0; - hr = devices->get_Size(&count); + hr = devices->get_Size(&count); ThrowIfFailed(hr); if (!count) @@ -1794,7 +1753,6 @@ std::vector AudioEngine::GetRendererDetails() return list; } - #elif defined(_XBOX_ONE) //--- Use legacy Xbox One XDK device enumeration --- @@ -1808,7 +1766,7 @@ namespace wfx.nSamplesPerSec = 48000; wfx.wBitsPerSample = 24; } -} +} // namespace std::vector AudioEngine::GetRendererDetails() { @@ -1828,14 +1786,13 @@ std::vector AudioEngine::GetRendererDetails() ThrowIfFailed(hr); RendererDetail device; - device.deviceId = id.GetRawBuffer(nullptr); + device.deviceId = id.GetRawBuffer(nullptr); device.description = L"Default"; list.emplace_back(device); return list; } - #elif defined(USING_XAUDIO2_9) || defined(USING_XAUDIO2_REDIST) || defined(_GAMING_DESKTOP) #include //--- Use WASAPI device enumeration --- @@ -1861,7 +1818,8 @@ namespace } // Value matches Windows SDK header um\mmdeviceapi.h - constexpr static PROPERTYKEY s_PKEY_AudioEngine_DeviceFormat = { { 0xf19f064d, 0x82c, 0x4e27, { 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c } }, 0 }; + constexpr static PROPERTYKEY s_PKEY_AudioEngine_DeviceFormat + = { { 0xf19f064d, 0x82c, 0x4e27, { 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c } }, 0 }; ComPtr props; if (SUCCEEDED(endpoint->OpenPropertyStore(STGM_READ, props.GetAddressOf()))) @@ -1881,14 +1839,15 @@ namespace } } } -} +} // namespace std::vector AudioEngine::GetRendererDetails() { std::vector list; // Value matches Windows SDK header shared\devpkey.h - constexpr static PROPERTYKEY s_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 }; + constexpr static PROPERTYKEY s_PKEY_Device_FriendlyName + = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 }; ComPtr devEnum; HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(devEnum.GetAddressOf())); @@ -1939,27 +1898,22 @@ std::vector AudioEngine::GetRendererDetails() return list; } - #else #error DirectX Tool Kit for Audio not supported on this platform #endif - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -_Use_decl_annotations_ -AudioEngine::AudioEngine( - AUDIO_ENGINE_FLAGS flags, - const WAVEFORMATEX* wfx, - const __wchar_t* deviceId, - AUDIO_STREAM_CATEGORY category) noexcept(false) : - AudioEngine(flags, wfx, reinterpret_cast(deviceId), category) +_Use_decl_annotations_ AudioEngine::AudioEngine(AUDIO_ENGINE_FLAGS flags, + const WAVEFORMATEX* wfx, + const __wchar_t* deviceId, + AUDIO_STREAM_CATEGORY category) noexcept(false) + : AudioEngine(flags, wfx, reinterpret_cast(deviceId), category) {} -_Use_decl_annotations_ -bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const __wchar_t* deviceId) +_Use_decl_annotations_ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const __wchar_t* deviceId) { return Reset(wfx, reinterpret_cast(deviceId)); } diff --git a/Audio/DynamicSoundEffectInstance.cpp b/Audio/DynamicSoundEffectInstance.cpp index a8bd4c6a..e696cbbb 100644 --- a/Audio/DynamicSoundEffectInstance.cpp +++ b/Audio/DynamicSoundEffectInstance.cpp @@ -13,7 +13,6 @@ using namespace DirectX; - //====================================================================================== // DynamicSoundEffectInstance //====================================================================================== @@ -22,22 +21,25 @@ using namespace DirectX; class DynamicSoundEffectInstance::Impl : public IVoiceNotify { public: - Impl(_In_ AudioEngine* engine, - _In_ DynamicSoundEffectInstance* object, + Impl(_In_ AudioEngine* engine, + _In_ DynamicSoundEffectInstance* object, std::function& bufferNeeded, - int sampleRate, int channels, int sampleBits, - SOUND_EFFECT_INSTANCE_FLAGS flags) : - mBase(), - mBufferNeeded(nullptr), - mObject(object) + int sampleRate, + int channels, + int sampleBits, + SOUND_EFFECT_INSTANCE_FLAGS flags) + : mBase(), + mBufferNeeded(nullptr), + mObject(object) { if (!engine) throw std::invalid_argument("AudioEngine is required"); - if ((sampleRate < XAUDIO2_MIN_SAMPLE_RATE) - || (sampleRate > XAUDIO2_MAX_SAMPLE_RATE)) + if ((sampleRate < XAUDIO2_MIN_SAMPLE_RATE) || (sampleRate > XAUDIO2_MAX_SAMPLE_RATE)) { - DebugTrace("DynamicSoundEffectInstance sampleRate must be in range %u...%u\n", XAUDIO2_MIN_SAMPLE_RATE, XAUDIO2_MAX_SAMPLE_RATE); + DebugTrace("DynamicSoundEffectInstance sampleRate must be in range %u...%u\n", + XAUDIO2_MIN_SAMPLE_RATE, + XAUDIO2_MAX_SAMPLE_RATE); throw std::out_of_range("DynamicSoundEffectInstance"); } @@ -50,8 +52,7 @@ class DynamicSoundEffectInstance::Impl : public IVoiceNotify switch (sampleBits) { case 8: - case 16: - break; + case 16: break; default: DebugTrace("DynamicSoundEffectInstance sampleBits must be 8-bit or 16-bit\n"); @@ -79,11 +80,11 @@ class DynamicSoundEffectInstance::Impl : public IVoiceNotify mBufferNeeded = bufferNeeded; } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() override { @@ -105,51 +106,31 @@ class DynamicSoundEffectInstance::Impl : public IVoiceNotify const WAVEFORMATEX* GetFormat() const noexcept { return &mWaveFormat; } // IVoiceNotify - void __cdecl OnBufferEnd() override - { - SetEvent(mBufferEvent.get()); - } + void __cdecl OnBufferEnd() override { SetEvent(mBufferEvent.get()); } - void __cdecl OnCriticalError() override - { - mBase.OnCriticalError(); - } + void __cdecl OnCriticalError() override { mBase.OnCriticalError(); } - void __cdecl OnReset() override - { - mBase.OnReset(); - } + void __cdecl OnReset() override { mBase.OnReset(); } void __cdecl OnUpdate() override; - void __cdecl OnDestroyEngine() noexcept override - { - mBase.OnDestroy(); - } + void __cdecl OnDestroyEngine() noexcept override { mBase.OnDestroy(); } - void __cdecl OnTrim() override - { - mBase.OnTrim(); - } + void __cdecl OnTrim() override { mBase.OnTrim(); } - void __cdecl GatherStatistics(AudioStatistics& stats) const noexcept override - { - mBase.GatherStatistics(stats); - } + void __cdecl GatherStatistics(AudioStatistics& stats) const noexcept override { mBase.GatherStatistics(stats); } - void __cdecl OnDestroyParent() noexcept override - {} + void __cdecl OnDestroyParent() noexcept override {} - SoundEffectInstanceBase mBase; + SoundEffectInstanceBase mBase; private: - ScopedHandle mBufferEvent; - std::function mBufferNeeded; - DynamicSoundEffectInstance* mObject; - WAVEFORMATEX mWaveFormat; + ScopedHandle mBufferEvent; + std::function mBufferNeeded; + DynamicSoundEffectInstance* mObject; + WAVEFORMATEX mWaveFormat; }; - void DynamicSoundEffectInstance::Impl::Play() { if (!mBase.voice) @@ -165,7 +146,6 @@ void DynamicSoundEffectInstance::Impl::Play() } } - void DynamicSoundEffectInstance::Impl::Resume() { if (mBase.voice && (mBase.state == PAUSED)) @@ -179,9 +159,7 @@ void DynamicSoundEffectInstance::Impl::Resume() } } - -_Use_decl_annotations_ -void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, uint32_t offset, size_t audioBytes) +_Use_decl_annotations_ void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, uint32_t offset, size_t audioBytes) { if (!pAudioData || !audioBytes) throw std::invalid_argument("Invalid audio data buffer"); @@ -190,13 +168,13 @@ void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, u throw std::out_of_range("SubmitBuffer"); XAUDIO2_BUFFER buffer = {}; - buffer.AudioBytes = static_cast(audioBytes); - buffer.pAudioData = pAudioData; + buffer.AudioBytes = static_cast(audioBytes); + buffer.pAudioData = pAudioData; if (offset) { assert(mWaveFormat.wFormatTag == WAVE_FORMAT_PCM); - buffer.PlayBegin = offset / mWaveFormat.nBlockAlign; + buffer.PlayBegin = offset / mWaveFormat.nBlockAlign; buffer.PlayLength = static_cast((audioBytes - offset) / mWaveFormat.nBlockAlign); } @@ -205,25 +183,28 @@ void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, u HRESULT hr = mBase.voice->SubmitSourceBuffer(&buffer, nullptr); if (FAILED(hr)) { - #ifdef _DEBUG +#ifdef _DEBUG DebugTrace("ERROR: DynamicSoundEffectInstance failed (%08X) when submitting buffer:\n", static_cast(hr)); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %zu bytes [%u offset)\n", - mWaveFormat.wFormatTag, mWaveFormat.nChannels, mWaveFormat.wBitsPerSample, mWaveFormat.nSamplesPerSec, audioBytes, offset); - #endif + mWaveFormat.wFormatTag, + mWaveFormat.nChannels, + mWaveFormat.wBitsPerSample, + mWaveFormat.nSamplesPerSec, + audioBytes, + offset); +#endif throw std::runtime_error("SubmitSourceBuffer"); } } - void DynamicSoundEffectInstance::Impl::OnUpdate() { const DWORD result = WaitForSingleObjectEx(mBufferEvent.get(), 0, FALSE); switch (result) { default: - case WAIT_TIMEOUT: - break; + case WAIT_TIMEOUT: break; case WAIT_OBJECT_0: if (mBufferNeeded) @@ -238,33 +219,27 @@ void DynamicSoundEffectInstance::Impl::OnUpdate() } } - - //-------------------------------------------------------------------------------------- // DynamicSoundEffectInstance //-------------------------------------------------------------------------------------- #ifdef _MSC_VER -#pragma warning( disable : 4355 ) +#pragma warning(disable : 4355) #endif // Public constructors -_Use_decl_annotations_ -DynamicSoundEffectInstance::DynamicSoundEffectInstance( - AudioEngine* engine, - std::function bufferNeeded, - int sampleRate, - int channels, - int sampleBits, - SOUND_EFFECT_INSTANCE_FLAGS flags) : - pImpl(std::make_unique(engine, this, bufferNeeded, sampleRate, channels, sampleBits, flags)) +_Use_decl_annotations_ DynamicSoundEffectInstance::DynamicSoundEffectInstance(AudioEngine* engine, + std::function bufferNeeded, + int sampleRate, + int channels, + int sampleBits, + SOUND_EFFECT_INSTANCE_FLAGS flags) + : pImpl(std::make_unique(engine, this, bufferNeeded, sampleRate, channels, sampleBits, flags)) {} - -DynamicSoundEffectInstance::DynamicSoundEffectInstance(DynamicSoundEffectInstance&&) noexcept = default; -DynamicSoundEffectInstance& DynamicSoundEffectInstance::operator= (DynamicSoundEffectInstance&&) noexcept = default; -DynamicSoundEffectInstance::~DynamicSoundEffectInstance() = default; - +DynamicSoundEffectInstance::DynamicSoundEffectInstance(DynamicSoundEffectInstance&&) noexcept = default; +DynamicSoundEffectInstance& DynamicSoundEffectInstance::operator=(DynamicSoundEffectInstance&&) noexcept = default; +DynamicSoundEffectInstance::~DynamicSoundEffectInstance() = default; // Public methods. void DynamicSoundEffectInstance::Play() @@ -272,82 +247,67 @@ void DynamicSoundEffectInstance::Play() pImpl->Play(); } - void DynamicSoundEffectInstance::Stop(bool immediate) noexcept { bool looped = false; pImpl->mBase.Stop(immediate, looped); } - void DynamicSoundEffectInstance::Pause() noexcept { pImpl->mBase.Pause(); } - void DynamicSoundEffectInstance::Resume() { pImpl->Resume(); } - void DynamicSoundEffectInstance::SetVolume(float volume) { pImpl->mBase.SetVolume(volume); } - void DynamicSoundEffectInstance::SetPitch(float pitch) { pImpl->mBase.SetPitch(pitch); } - void DynamicSoundEffectInstance::SetPan(float pan) { pImpl->mBase.SetPan(pan); } - void DynamicSoundEffectInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } - -_Use_decl_annotations_ -void DynamicSoundEffectInstance::SubmitBuffer(const uint8_t* pAudioData, size_t audioBytes) +_Use_decl_annotations_ void DynamicSoundEffectInstance::SubmitBuffer(const uint8_t* pAudioData, size_t audioBytes) { pImpl->SubmitBuffer(pAudioData, 0, audioBytes); } - -_Use_decl_annotations_ -void DynamicSoundEffectInstance::SubmitBuffer(const uint8_t* pAudioData, uint32_t offset, size_t audioBytes) +_Use_decl_annotations_ void DynamicSoundEffectInstance::SubmitBuffer(const uint8_t* pAudioData, uint32_t offset, size_t audioBytes) { pImpl->SubmitBuffer(pAudioData, offset, audioBytes); } - // Public accessors. SoundState DynamicSoundEffectInstance::GetState() noexcept { return pImpl->mBase.GetState(false); } - size_t DynamicSoundEffectInstance::GetSampleDuration(size_t bytes) const noexcept { auto wfx = pImpl->GetFormat(); if (!wfx || !wfx->wBitsPerSample || !wfx->nChannels) return 0; - return static_cast((uint64_t(bytes) * 8) - / (uint64_t(wfx->wBitsPerSample) * uint64_t(wfx->nChannels))); + return static_cast((uint64_t(bytes) * 8) / (uint64_t(wfx->wBitsPerSample) * uint64_t(wfx->nChannels))); } - size_t DynamicSoundEffectInstance::GetSampleDurationMS(size_t bytes) const noexcept { auto wfx = pImpl->GetFormat(); @@ -357,7 +317,6 @@ size_t DynamicSoundEffectInstance::GetSampleDurationMS(size_t bytes) const noexc return static_cast((uint64_t(bytes) * 1000) / wfx->nAvgBytesPerSec); } - size_t DynamicSoundEffectInstance::GetSampleSizeInBytes(uint64_t duration) const noexcept { auto wfx = pImpl->GetFormat(); @@ -367,19 +326,16 @@ size_t DynamicSoundEffectInstance::GetSampleSizeInBytes(uint64_t duration) const return static_cast(((duration * wfx->nSamplesPerSec) / 1000) * wfx->nBlockAlign); } - int DynamicSoundEffectInstance::GetPendingBufferCount() const noexcept { return pImpl->mBase.GetPendingBufferCount(); } - unsigned int DynamicSoundEffectInstance::GetChannelCount() const noexcept { return pImpl->mBase.GetChannelCount(); } - const WAVEFORMATEX* DynamicSoundEffectInstance::GetFormat() const noexcept { return pImpl->GetFormat(); diff --git a/Audio/SoundCommon.cpp b/Audio/SoundCommon.cpp index 6538d2d9..f3dbf85a 100644 --- a/Audio/SoundCommon.cpp +++ b/Audio/SoundCommon.cpp @@ -13,13 +13,17 @@ using namespace DirectX; - namespace { - template WORD ChannelsSpecifiedInMask(T x) noexcept + template + WORD ChannelsSpecifiedInMask(T x) noexcept { WORD bitCount = 0; - while (x) { ++bitCount; x &= (x - 1); } + while (x) + { + ++bitCount; + x &= (x - 1); + } return bitCount; } @@ -27,13 +31,12 @@ namespace constexpr uint16_t MSADPCM_FORMAT_EXTRA_BYTES = 32; - constexpr uint16_t MSADPCM_BITS_PER_SAMPLE = 4; + constexpr uint16_t MSADPCM_BITS_PER_SAMPLE = 4; constexpr uint16_t MSADPCM_NUM_COEFFICIENTS = 7; constexpr uint16_t MSADPCM_MIN_SAMPLES_PER_BLOCK = 4; constexpr uint16_t MSADPCM_MAX_SAMPLES_PER_BLOCK = 64000; -} - +} // namespace //====================================================================================== // Wave format utilities @@ -62,11 +65,12 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept return false; } - if ((wfx->nSamplesPerSec < XAUDIO2_MIN_SAMPLE_RATE) - || (wfx->nSamplesPerSec > XAUDIO2_MAX_SAMPLE_RATE)) + if ((wfx->nSamplesPerSec < XAUDIO2_MIN_SAMPLE_RATE) || (wfx->nSamplesPerSec > XAUDIO2_MAX_SAMPLE_RATE)) { DebugTrace("ERROR: Wave format channel count must be in range %u..%u (%u)\n", - XAUDIO2_MIN_SAMPLE_RATE, XAUDIO2_MAX_SAMPLE_RATE, wfx->nSamplesPerSec); + XAUDIO2_MIN_SAMPLE_RATE, + XAUDIO2_MAX_SAMPLE_RATE, + wfx->nSamplesPerSec); return false; } @@ -79,8 +83,7 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept case 8: case 16: case 24: - case 32: - break; + case 32: break; default: DebugTrace("ERROR: Wave format integer PCM must have 8, 16, 24, or 32 bits per sample (%u)\n", wfx->wBitsPerSample); @@ -90,14 +93,18 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { DebugTrace("ERROR: Wave format integer PCM - nBlockAlign (%u) != nChannels (%u) * wBitsPerSample (%u) / 8\n", - wfx->nBlockAlign, wfx->nChannels, wfx->wBitsPerSample); + wfx->nBlockAlign, + wfx->nChannels, + wfx->wBitsPerSample); return false; } if (wfx->nAvgBytesPerSec != (wfx->nSamplesPerSec * wfx->nBlockAlign)) { DebugTrace("ERROR: Wave format integer PCM - nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\n", - wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); + wfx->nAvgBytesPerSec, + wfx->nSamplesPerSec, + wfx->nBlockAlign); return false; } @@ -114,14 +121,18 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { DebugTrace("ERROR: Wave format float PCM - nBlockAlign (%u) != nChannels (%u) * wBitsPerSample (%u) / 8\n", - wfx->nBlockAlign, wfx->nChannels, wfx->wBitsPerSample); + wfx->nBlockAlign, + wfx->nChannels, + wfx->wBitsPerSample); return false; } if (wfx->nAvgBytesPerSec != (wfx->nSamplesPerSec * wfx->nBlockAlign)) { DebugTrace("ERROR: Wave format float PCM - nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\n", - wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); + wfx->nAvgBytesPerSec, + wfx->nSamplesPerSec, + wfx->nBlockAlign); return false; } @@ -160,11 +171,10 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept for (size_t j = 0; j < MSADPCM_NUM_COEFFICIENTS; ++j) { // Microsoft ADPCM standard encoding coefficients - static const short g_pAdpcmCoefficients1[] = { 256, 512, 0, 192, 240, 460, 392 }; - static const short g_pAdpcmCoefficients2[] = { 0, -256, 0, 64, 0, -208, -232 }; + static const short g_pAdpcmCoefficients1[] = { 256, 512, 0, 192, 240, 460, 392 }; + static const short g_pAdpcmCoefficients2[] = { 0, -256, 0, 64, 0, -208, -232 }; - if (wfadpcm->aCoef[j].iCoef1 != g_pAdpcmCoefficients1[j] - || wfadpcm->aCoef[j].iCoef2 != g_pAdpcmCoefficients2[j]) + if (wfadpcm->aCoef[j].iCoef1 != g_pAdpcmCoefficients1[j] || wfadpcm->aCoef[j].iCoef2 != g_pAdpcmCoefficients2[j]) { valid = false; } @@ -176,8 +186,7 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept return false; } - if ((wfadpcm->wSamplesPerBlock < MSADPCM_MIN_SAMPLES_PER_BLOCK) - || (wfadpcm->wSamplesPerBlock > MSADPCM_MAX_SAMPLES_PER_BLOCK)) + if ((wfadpcm->wSamplesPerBlock < MSADPCM_MIN_SAMPLES_PER_BLOCK) || (wfadpcm->wSamplesPerBlock > MSADPCM_MAX_SAMPLES_PER_BLOCK)) { DebugTrace("ERROR: Wave format ADPCM wSamplesPerBlock must be 4..64000 (%u)\n", wfadpcm->wSamplesPerBlock); return false; @@ -189,14 +198,17 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept return false; } - const int nHeaderBytes = MSADPCM_HEADER_LENGTH * wfx->nChannels; - const int nBitsPerFrame = MSADPCM_BITS_PER_SAMPLE * wfx->nChannels; + const int nHeaderBytes = MSADPCM_HEADER_LENGTH * wfx->nChannels; + const int nBitsPerFrame = MSADPCM_BITS_PER_SAMPLE * wfx->nChannels; const int nPcmFramesPerBlock = (wfx->nBlockAlign - nHeaderBytes) * 8 / nBitsPerFrame + 2; if (wfadpcm->wSamplesPerBlock != nPcmFramesPerBlock) { DebugTrace("ERROR: Wave format ADPCM %u-channel with nBlockAlign = %u must have wSamplesPerBlock = %d (%u)\n", - wfx->nChannels, wfx->nBlockAlign, nPcmFramesPerBlock, wfadpcm->wSamplesPerBlock); + wfx->nChannels, + wfx->nBlockAlign, + nPcmFramesPerBlock, + wfadpcm->wSamplesPerBlock); return false; } } @@ -205,7 +217,7 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept case WAVE_FORMAT_WMAUDIO2: case WAVE_FORMAT_WMAUDIO3: - #ifdef DIRECTX_ENABLE_XWMA +#ifdef DIRECTX_ENABLE_XWMA if (wfx->wBitsPerSample != 16) { @@ -227,20 +239,23 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept return true; - #else +#else DebugTrace("ERROR: Wave format xWMA not supported by this version of DirectXTK for Audio\n"); return false; - #endif +#endif case 0x166 /* WAVE_FORMAT_XMA2 */: - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 static_assert(WAVE_FORMAT_XMA2 == 0x166, "Unrecognized XMA2 tag"); if (wfx->nBlockAlign != wfx->nChannels * XMA_OUTPUT_SAMPLE_BYTES) { - DebugTrace("ERROR: Wave format XMA2 - nBlockAlign (%u) != nChannels(%u) * %u\n", wfx->nBlockAlign, wfx->nChannels, XMA_OUTPUT_SAMPLE_BYTES); + DebugTrace("ERROR: Wave format XMA2 - nBlockAlign (%u) != nChannels(%u) * %u\n", + wfx->nBlockAlign, + wfx->nChannels, + XMA_OUTPUT_SAMPLE_BYTES); return false; } @@ -252,7 +267,9 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept if (wfx->cbSize != (sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX))) { - DebugTrace("ERROR: Wave format XMA2 - cbSize must be %zu (%u)\n", (sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX)), wfx->cbSize); + DebugTrace("ERROR: Wave format XMA2 - cbSize must be %zu (%u)\n", + (sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX)), + wfx->cbSize); return false; } else @@ -283,44 +300,50 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept if (channelBits != wfx->nChannels) { DebugTrace("ERROR: Wave format XMA2 - nChannels=%u but ChannelMask (%08X) has %u bits set\n", - xmaFmt->ChannelMask, wfx->nChannels, channelBits); + xmaFmt->ChannelMask, + wfx->nChannels, + channelBits); return false; } } if (xmaFmt->NumStreams != ((wfx->nChannels + 1) / 2)) { - DebugTrace("ERROR: Wave format XMA2 - NumStreams (%u) != ( nChannels(%u) + 1 ) / 2\n", - xmaFmt->NumStreams, wfx->nChannels); + DebugTrace("ERROR: Wave format XMA2 - NumStreams (%u) != ( nChannels(%u) + 1 ) / 2\n", xmaFmt->NumStreams, wfx->nChannels); return false; } if ((xmaFmt->PlayBegin + xmaFmt->PlayLength) > xmaFmt->SamplesEncoded) { DebugTrace("ERROR: Wave format XMA2 play region too large (%u + %u > %u)\n", - xmaFmt->PlayBegin, xmaFmt->PlayLength, xmaFmt->SamplesEncoded); + xmaFmt->PlayBegin, + xmaFmt->PlayLength, + xmaFmt->SamplesEncoded); return false; } if ((xmaFmt->LoopBegin + xmaFmt->LoopLength) > xmaFmt->SamplesEncoded) { DebugTrace("ERROR: Wave format XMA2 loop region too large (%u + %u > %u)\n", - xmaFmt->LoopBegin, xmaFmt->LoopLength, xmaFmt->SamplesEncoded); + xmaFmt->LoopBegin, + xmaFmt->LoopLength, + xmaFmt->SamplesEncoded); return false; } } return true; - #else +#else DebugTrace("ERROR: Wave format XMA2 not supported by this version of DirectXTK for Audio\n"); return false; - #endif +#endif case WAVE_FORMAT_EXTENSIBLE: if (wfx->cbSize < (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))) { DebugTrace("ERROR: Wave format WAVE_FORMAT_EXTENSIBLE - cbSize must be %zu (%u)\n", - (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)), wfx->cbSize); + (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)), + wfx->cbSize); return false; } else @@ -330,12 +353,24 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept auto wfex = reinterpret_cast(wfx); if (memcmp(reinterpret_cast(&wfex->SubFormat) + sizeof(DWORD), - reinterpret_cast(&s_wfexBase) + sizeof(DWORD), sizeof(GUID) - sizeof(DWORD)) != 0) + reinterpret_cast(&s_wfexBase) + sizeof(DWORD), + sizeof(GUID) - sizeof(DWORD)) + != 0) { - DebugTrace("ERROR: Wave format WAVEFORMATEXTENSIBLE encountered with unknown GUID ({%8.8lX-%4.4X-%4.4X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X})\n", - wfex->SubFormat.Data1, wfex->SubFormat.Data2, wfex->SubFormat.Data3, - wfex->SubFormat.Data4[0], wfex->SubFormat.Data4[1], wfex->SubFormat.Data4[2], wfex->SubFormat.Data4[3], - wfex->SubFormat.Data4[4], wfex->SubFormat.Data4[5], wfex->SubFormat.Data4[6], wfex->SubFormat.Data4[7]); + DebugTrace( + "ERROR: Wave format WAVEFORMATEXTENSIBLE encountered with unknown GUID " + "({%8.8lX-%4.4X-%4.4X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X})\n", + wfex->SubFormat.Data1, + wfex->SubFormat.Data2, + wfex->SubFormat.Data3, + wfex->SubFormat.Data4[0], + wfex->SubFormat.Data4[1], + wfex->SubFormat.Data4[2], + wfex->SubFormat.Data4[3], + wfex->SubFormat.Data4[4], + wfex->SubFormat.Data4[5], + wfex->SubFormat.Data4[6], + wfex->SubFormat.Data4[7]); return false; } @@ -348,12 +383,10 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept case 8: case 16: case 24: - case 32: - break; + case 32: break; default: - DebugTrace("ERROR: Wave format integer PCM must have 8, 16, 24, or 32 bits per sample (%u)\n", - wfx->wBitsPerSample); + DebugTrace("ERROR: Wave format integer PCM must have 8, 16, 24, or 32 bits per sample (%u)\n", wfx->wBitsPerSample); return false; } @@ -364,8 +397,7 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept case 16: case 20: case 24: - case 32: - break; + case 32: break; default: DebugTrace("ERROR: Wave format integer PCM must have 8, 16, 20, 24, or 32 valid bits per sample (%u)\n", @@ -373,25 +405,29 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept return false; } - if (wfex->Samples.wValidBitsPerSample - && (wfex->Samples.wValidBitsPerSample > wfx->wBitsPerSample)) + if (wfex->Samples.wValidBitsPerSample && (wfex->Samples.wValidBitsPerSample > wfx->wBitsPerSample)) { DebugTrace("ERROR: Wave format ingter PCM wValidBitsPerSample (%u) is greater than wBitsPerSample (%u)\n", - wfex->Samples.wValidBitsPerSample, wfx->wBitsPerSample); + wfex->Samples.wValidBitsPerSample, + wfx->wBitsPerSample); return false; } if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { DebugTrace("ERROR: Wave format integer PCM - nBlockAlign (%u) != nChannels (%u) * wBitsPerSample (%u) / 8\n", - wfx->nBlockAlign, wfx->nChannels, wfx->wBitsPerSample); + wfx->nBlockAlign, + wfx->nChannels, + wfx->wBitsPerSample); return false; } if (wfx->nAvgBytesPerSec != (wfx->nSamplesPerSec * wfx->nBlockAlign)) { DebugTrace("ERROR: Wave format integer PCM - nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\n", - wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); + wfx->nAvgBytesPerSec, + wfx->nSamplesPerSec, + wfx->nBlockAlign); return false; } @@ -408,39 +444,39 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept switch (wfex->Samples.wValidBitsPerSample) { case 0: - case 32: - break; + case 32: break; default: - DebugTrace("ERROR: Wave format float PCM must have 32 valid bits per sample (%u)\n", - wfex->Samples.wValidBitsPerSample); + DebugTrace("ERROR: Wave format float PCM must have 32 valid bits per sample (%u)\n", wfex->Samples.wValidBitsPerSample); return false; } if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { DebugTrace("ERROR: Wave format float PCM - nBlockAlign (%u) != nChannels (%u) * wBitsPerSample (%u) / 8\n", - wfx->nBlockAlign, wfx->nChannels, wfx->wBitsPerSample); + wfx->nBlockAlign, + wfx->nChannels, + wfx->wBitsPerSample); return false; } if (wfx->nAvgBytesPerSec != (wfx->nSamplesPerSec * wfx->nBlockAlign)) { DebugTrace("ERROR: Wave format float PCM - nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\n", - wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); + wfx->nAvgBytesPerSec, + wfx->nSamplesPerSec, + wfx->nBlockAlign); return false; } break; - case WAVE_FORMAT_ADPCM: - DebugTrace("ERROR: Wave format ADPCM is not supported as a WAVEFORMATEXTENSIBLE\n"); - return false; + case WAVE_FORMAT_ADPCM: DebugTrace("ERROR: Wave format ADPCM is not supported as a WAVEFORMATEXTENSIBLE\n"); return false; case WAVE_FORMAT_WMAUDIO2: case WAVE_FORMAT_WMAUDIO3: - #ifdef DIRECTX_ENABLE_XWMA +#ifdef DIRECTX_ENABLE_XWMA if (wfx->wBitsPerSample != 16) { @@ -462,18 +498,16 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept break; - #else +#else DebugTrace("ERROR: Wave format xWMA not supported by this version of DirectXTK for Audio\n"); return false; - #endif +#endif case 0x166 /* WAVE_FORMAT_XMA2 */: DebugTrace("ERROR: Wave format XMA2 is not supported as a WAVEFORMATEXTENSIBLE\n"); return false; - default: - DebugTrace("ERROR: Unknown WAVEFORMATEXTENSIBLE format tag (%u)\n", wfex->SubFormat.Data1); - return false; + default: DebugTrace("ERROR: Unknown WAVEFORMATEXTENSIBLE format tag (%u)\n", wfex->SubFormat.Data1); return false; } if (wfex->dwChannelMask) @@ -481,8 +515,7 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept const auto channelBits = ChannelsSpecifiedInMask(wfex->dwChannelMask); if (channelBits != wfx->nChannels) { - DebugTrace("ERROR: WAVEFORMATEXTENSIBLE: nChannels=%u but ChannelMask has %u bits set\n", - wfx->nChannels, channelBits); + DebugTrace("ERROR: WAVEFORMATEXTENSIBLE: nChannels=%u but ChannelMask has %u bits set\n", wfx->nChannels, channelBits); return false; } } @@ -490,92 +523,71 @@ bool DirectX::IsValid(_In_ const WAVEFORMATEX* wfx) noexcept return true; } - default: - DebugTrace("ERROR: Unknown WAVEFORMATEX format tag (%u)\n", wfx->wFormatTag); - return false; + default: DebugTrace("ERROR: Unknown WAVEFORMATEX format tag (%u)\n", wfx->wFormatTag); return false; } } - uint32_t DirectX::GetDefaultChannelMask(int channels) noexcept { switch (channels) { - case 1: return SPEAKER_MONO; - case 2: return SPEAKER_STEREO; - case 3: return SPEAKER_2POINT1; - case 4: return SPEAKER_QUAD; - case 5: return SPEAKER_4POINT1; - case 6: return SPEAKER_5POINT1; - case 7: return SPEAKER_5POINT1 | SPEAKER_BACK_CENTER; - case 8: return SPEAKER_7POINT1; + case 1: return SPEAKER_MONO; + case 2: return SPEAKER_STEREO; + case 3: return SPEAKER_2POINT1; + case 4: return SPEAKER_QUAD; + case 5: return SPEAKER_4POINT1; + case 6: return SPEAKER_5POINT1; + case 7: return SPEAKER_5POINT1 | SPEAKER_BACK_CENTER; + case 8: return SPEAKER_7POINT1; default: return 0; } } - -_Use_decl_annotations_ -void DirectX::CreateIntegerPCM( - WAVEFORMATEX* wfx, - int sampleRate, - int channels, - int sampleBits) noexcept +_Use_decl_annotations_ void DirectX::CreateIntegerPCM(WAVEFORMATEX* wfx, int sampleRate, int channels, int sampleBits) noexcept { if (!wfx) return; const int blockAlign = channels * sampleBits / 8; - wfx->wFormatTag = WAVE_FORMAT_PCM; - wfx->nChannels = static_cast(channels); - wfx->nSamplesPerSec = static_cast(sampleRate); + wfx->wFormatTag = WAVE_FORMAT_PCM; + wfx->nChannels = static_cast(channels); + wfx->nSamplesPerSec = static_cast(sampleRate); wfx->nAvgBytesPerSec = static_cast(blockAlign * sampleRate); - wfx->nBlockAlign = static_cast(blockAlign); - wfx->wBitsPerSample = static_cast(sampleBits); - wfx->cbSize = 0; + wfx->nBlockAlign = static_cast(blockAlign); + wfx->wBitsPerSample = static_cast(sampleBits); + wfx->cbSize = 0; assert(IsValid(wfx)); } - -_Use_decl_annotations_ -void DirectX::CreateFloatPCM( - WAVEFORMATEX* wfx, - int sampleRate, - int channels) noexcept +_Use_decl_annotations_ void DirectX::CreateFloatPCM(WAVEFORMATEX* wfx, int sampleRate, int channels) noexcept { if (!wfx) return; const int blockAlign = channels * 4; - wfx->wFormatTag = WAVE_FORMAT_IEEE_FLOAT; - wfx->nChannels = static_cast(channels); - wfx->nSamplesPerSec = static_cast(sampleRate); + wfx->wFormatTag = WAVE_FORMAT_IEEE_FLOAT; + wfx->nChannels = static_cast(channels); + wfx->nSamplesPerSec = static_cast(sampleRate); wfx->nAvgBytesPerSec = static_cast(blockAlign * sampleRate); - wfx->nBlockAlign = static_cast(blockAlign); - wfx->wBitsPerSample = 32; - wfx->cbSize = 0; + wfx->nBlockAlign = static_cast(blockAlign); + wfx->wBitsPerSample = 32; + wfx->cbSize = 0; assert(IsValid(wfx)); } - -_Use_decl_annotations_ -void DirectX::CreateADPCM( - WAVEFORMATEX* wfx, - size_t wfxSize, - int sampleRate, - int channels, - int samplesPerBlock) noexcept(false) +_Use_decl_annotations_ void +DirectX::CreateADPCM(WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int samplesPerBlock) noexcept(false) { if (!wfx) return; if (wfxSize < (sizeof(WAVEFORMATEX) + MSADPCM_FORMAT_EXTRA_BYTES)) { - DebugTrace("CreateADPCM needs at least %zu bytes for the result\n", - (sizeof(WAVEFORMATEX) + MSADPCM_FORMAT_EXTRA_BYTES)); + DebugTrace("CreateADPCM needs at least %zu bytes for the result\n", (sizeof(WAVEFORMATEX) + MSADPCM_FORMAT_EXTRA_BYTES)); throw std::invalid_argument("ADPCMWAVEFORMAT"); } @@ -585,64 +597,54 @@ void DirectX::CreateADPCM( throw std::invalid_argument("ADPCMWAVEFORMAT"); } - const int blockAlign = MSADPCM_HEADER_LENGTH * channels - + (samplesPerBlock - 2) * MSADPCM_BITS_PER_SAMPLE * channels / 8; + const int blockAlign = MSADPCM_HEADER_LENGTH * channels + (samplesPerBlock - 2) * MSADPCM_BITS_PER_SAMPLE * channels / 8; - wfx->wFormatTag = WAVE_FORMAT_ADPCM; - wfx->nChannels = static_cast(channels); - wfx->nSamplesPerSec = static_cast(sampleRate); + wfx->wFormatTag = WAVE_FORMAT_ADPCM; + wfx->nChannels = static_cast(channels); + wfx->nSamplesPerSec = static_cast(sampleRate); wfx->nAvgBytesPerSec = static_cast(blockAlign * sampleRate / samplesPerBlock); - wfx->nBlockAlign = static_cast(blockAlign); - wfx->wBitsPerSample = MSADPCM_BITS_PER_SAMPLE; - wfx->cbSize = MSADPCM_FORMAT_EXTRA_BYTES; + wfx->nBlockAlign = static_cast(blockAlign); + wfx->wBitsPerSample = MSADPCM_BITS_PER_SAMPLE; + wfx->cbSize = MSADPCM_FORMAT_EXTRA_BYTES; - auto adpcm = reinterpret_cast(wfx); + auto adpcm = reinterpret_cast(wfx); adpcm->wSamplesPerBlock = static_cast(samplesPerBlock); - adpcm->wNumCoef = MSADPCM_NUM_COEFFICIENTS; + adpcm->wNumCoef = MSADPCM_NUM_COEFFICIENTS; - static ADPCMCOEFSET aCoef[7] = { { 256, 0}, {512, -256}, {0,0}, {192,64}, {240,0}, {460, -208}, {392,-232} }; - memcpy(&adpcm->aCoef, aCoef, sizeof(aCoef)); // CodeQL [SM01947] Code scanner doesn't understand the 0-length MSVC array extension. MSADPCM_FORMAT_EXTRA_BYTES includes this memory. + static ADPCMCOEFSET aCoef[7] = { { 256, 0 }, { 512, -256 }, { 0, 0 }, { 192, 64 }, { 240, 0 }, { 460, -208 }, { 392, -232 } }; + memcpy(&adpcm->aCoef, aCoef, sizeof(aCoef)); // CodeQL [SM01947] Code scanner doesn't understand the 0-length MSVC array extension. + // MSADPCM_FORMAT_EXTRA_BYTES includes this memory. assert(IsValid(wfx)); } - #ifdef DIRECTX_ENABLE_XWMA -_Use_decl_annotations_ -void DirectX::CreateXWMA( - WAVEFORMATEX* wfx, - int sampleRate, - int channels, - int blockAlign, - int avgBytes, - bool wma3) noexcept +_Use_decl_annotations_ void +DirectX::CreateXWMA(WAVEFORMATEX* wfx, int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept { if (!wfx) return; - wfx->wFormatTag = static_cast((wma3) ? WAVE_FORMAT_WMAUDIO3 : WAVE_FORMAT_WMAUDIO2); - wfx->nChannels = static_cast(channels); - wfx->nSamplesPerSec = static_cast(sampleRate); + wfx->wFormatTag = static_cast((wma3) ? WAVE_FORMAT_WMAUDIO3 : WAVE_FORMAT_WMAUDIO2); + wfx->nChannels = static_cast(channels); + wfx->nSamplesPerSec = static_cast(sampleRate); wfx->nAvgBytesPerSec = static_cast(avgBytes); - wfx->nBlockAlign = static_cast(blockAlign); - wfx->wBitsPerSample = 16; - wfx->cbSize = 0; + wfx->nBlockAlign = static_cast(blockAlign); + wfx->wBitsPerSample = 16; + wfx->cbSize = 0; assert(IsValid(wfx)); } #endif - #ifdef DIRECTX_ENABLE_XMA2 -_Use_decl_annotations_ -void DirectX::CreateXMA2( - WAVEFORMATEX* wfx, - size_t wfxSize, - int sampleRate, - int channels, - int bytesPerBlock, - int blockCount, - int samplesEncoded) noexcept(false) +_Use_decl_annotations_ void DirectX::CreateXMA2(WAVEFORMATEX* wfx, + size_t wfxSize, + int sampleRate, + int channels, + int bytesPerBlock, + int blockCount, + int samplesEncoded) noexcept(false) { if (wfxSize < sizeof(XMA2WAVEFORMATEX)) { @@ -658,13 +660,13 @@ void DirectX::CreateXMA2( unsigned int blockAlign = (static_cast(channels) * XMA_OUTPUT_SAMPLE_BITS) / 8u; - wfx->wFormatTag = WAVE_FORMAT_XMA2; - wfx->nChannels = static_cast(channels); - wfx->nSamplesPerSec = static_cast(sampleRate); + wfx->wFormatTag = WAVE_FORMAT_XMA2; + wfx->nChannels = static_cast(channels); + wfx->nSamplesPerSec = static_cast(sampleRate); wfx->nAvgBytesPerSec = static_cast(blockAlign * static_cast(sampleRate)); - wfx->nBlockAlign = static_cast(blockAlign); - wfx->wBitsPerSample = XMA_OUTPUT_SAMPLE_BITS; - wfx->cbSize = sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX); + wfx->nBlockAlign = static_cast(blockAlign); + wfx->wBitsPerSample = XMA_OUTPUT_SAMPLE_BITS; + wfx->cbSize = sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX); auto xmaFmt = reinterpret_cast(wfx); @@ -673,19 +675,16 @@ void DirectX::CreateXMA2( xmaFmt->ChannelMask = GetDefaultChannelMask(channels); xmaFmt->SamplesEncoded = static_cast(samplesEncoded); - xmaFmt->BytesPerBlock = static_cast(bytesPerBlock); - xmaFmt->PlayBegin = xmaFmt->PlayLength = - xmaFmt->LoopBegin = xmaFmt->LoopLength = xmaFmt->LoopCount = 0; - xmaFmt->EncoderVersion = 4 /* XMAENCODER_VERSION_XMA2 */; - xmaFmt->BlockCount = static_cast(blockCount); + xmaFmt->BytesPerBlock = static_cast(bytesPerBlock); + xmaFmt->PlayBegin = xmaFmt->PlayLength = xmaFmt->LoopBegin = xmaFmt->LoopLength = xmaFmt->LoopCount = 0; + xmaFmt->EncoderVersion = 4 /* XMAENCODER_VERSION_XMA2 */; + xmaFmt->BlockCount = static_cast(blockCount); assert(IsValid(wfx)); } #endif // XMA2 - -_Use_decl_annotations_ -bool DirectX::ComputePan(float pan, unsigned int channels, float* matrix) noexcept +_Use_decl_annotations_ bool DirectX::ComputePan(float pan, unsigned int channels, float* matrix) noexcept { memset(matrix, 0, sizeof(float) * 16); @@ -693,12 +692,12 @@ bool DirectX::ComputePan(float pan, unsigned int channels, float* matrix) noexce { // Mono panning float left = 1.f - pan; - left = std::min(1.f, left); - left = std::max(0.f, left); + left = std::min(1.f, left); + left = std::max(0.f, left); float right = pan + 1.f; - right = std::min(1.f, right); - right = std::max(0.f, right); + right = std::min(1.f, right); + right = std::max(0.f, right); matrix[0] = left; matrix[1] = right; @@ -708,17 +707,17 @@ bool DirectX::ComputePan(float pan, unsigned int channels, float* matrix) noexce // Stereo panning if (-1.f <= pan && pan <= 0.f) { - matrix[0] = .5f * pan + 1.f; // .5 when pan is -1, 1 when pan is 0 - matrix[1] = .5f * -pan; // .5 when pan is -1, 0 when pan is 0 - matrix[2] = 0.f; // 0 when pan is -1, 0 when pan is 0 - matrix[3] = pan + 1.f; // 0 when pan is -1, 1 when pan is 0 + matrix[0] = .5f * pan + 1.f; // .5 when pan is -1, 1 when pan is 0 + matrix[1] = .5f * -pan; // .5 when pan is -1, 0 when pan is 0 + matrix[2] = 0.f; // 0 when pan is -1, 0 when pan is 0 + matrix[3] = pan + 1.f; // 0 when pan is -1, 1 when pan is 0 } else { - matrix[0] = -pan + 1.f; // 1 when pan is 0, 0 when pan is 1 - matrix[1] = 0.f; // 0 when pan is 0, 0 when pan is 1 - matrix[2] = .5f * pan; // 0 when pan is 0, .5f when pan is 1 - matrix[3] = .5f * -pan + 1.f; // 1 when pan is 0. .5f when pan is 1 + matrix[0] = -pan + 1.f; // 1 when pan is 0, 0 when pan is 1 + matrix[1] = 0.f; // 0 when pan is 0, 0 when pan is 1 + matrix[2] = .5f * pan; // 0 when pan is 0, .5f when pan is 1 + matrix[3] = .5f * -pan + 1.f; // 1 when pan is 0. .5f when pan is 1 } } else @@ -733,7 +732,6 @@ bool DirectX::ComputePan(float pan, unsigned int channels, float* matrix) noexce return true; } - //====================================================================================== // SoundEffectInstanceBase //====================================================================================== @@ -755,7 +753,6 @@ void SoundEffectInstanceBase::SetPan(float pan) } } - void SoundEffectInstanceBase::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { if (!voice) @@ -770,7 +767,7 @@ void SoundEffectInstanceBase::Apply3D(const X3DAUDIO_LISTENER& listener, const X float matrix[XAUDIO2_MAX_AUDIO_CHANNELS * 8] = {}; assert(mDSPSettings.SrcChannelCount <= XAUDIO2_MAX_AUDIO_CHANNELS); assert(mDSPSettings.DstChannelCount <= 8); - mDSPSettings.DopplerFactor = 1.f; + mDSPSettings.DopplerFactor = 1.f; mDSPSettings.pMatrixCoefficients = matrix; assert(engine != nullptr); @@ -779,16 +776,16 @@ void SoundEffectInstanceBase::Apply3D(const X3DAUDIO_LISTENER& listener, const X X3DAUDIO_EMITTER lhEmitter; memcpy(&lhEmitter, &emitter, sizeof(X3DAUDIO_EMITTER)); lhEmitter.OrientFront.z = -emitter.OrientFront.z; - lhEmitter.OrientTop.z = -emitter.OrientTop.z; - lhEmitter.Position.z = -emitter.Position.z; - lhEmitter.Velocity.z = -emitter.Velocity.z; + lhEmitter.OrientTop.z = -emitter.OrientTop.z; + lhEmitter.Position.z = -emitter.Position.z; + lhEmitter.Velocity.z = -emitter.Velocity.z; X3DAUDIO_LISTENER lhListener; memcpy(&lhListener, &listener, sizeof(X3DAUDIO_LISTENER)); lhListener.OrientFront.z = -listener.OrientFront.z; - lhListener.OrientTop.z = -listener.OrientTop.z; - lhListener.Position.z = -listener.Position.z; - lhListener.Velocity.z = -listener.Velocity.z; + lhListener.OrientTop.z = -listener.OrientTop.z; + lhListener.Position.z = -listener.Position.z; + lhListener.Velocity.z = -listener.Velocity.z; X3DAudioCalculate(engine->Get3DHandle(), &lhListener, &lhEmitter, mX3DCalcFlags, &mDSPSettings); } @@ -817,20 +814,21 @@ void SoundEffectInstanceBase::Apply3D(const X3DAUDIO_LISTENER& listener, const X if (mFlags & SoundEffectInstance_ReverbUseFilters) { - XAUDIO2_FILTER_PARAMETERS filterDirect = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI / 6.0f * mDSPSettings.LPFDirectCoefficient), 1.0f }; + XAUDIO2_FILTER_PARAMETERS filterDirect + = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI / 6.0f * mDSPSettings.LPFDirectCoefficient), 1.0f }; // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here std::ignore = voice->SetOutputFilterParameters(direct, &filterDirect); if (reverb) { - XAUDIO2_FILTER_PARAMETERS filterReverb = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI / 6.0f * mDSPSettings.LPFReverbCoefficient), 1.0f }; + XAUDIO2_FILTER_PARAMETERS filterReverb + = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI / 6.0f * mDSPSettings.LPFReverbCoefficient), 1.0f }; // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here std::ignore = voice->SetOutputFilterParameters(reverb, &filterReverb); } } } - //====================================================================================== // AudioListener/Emitter helpers //====================================================================================== @@ -896,7 +894,7 @@ namespace return true; } -} +} // namespace void AudioListener::SetCone(const X3DAUDIO_CONE& listenerCone) { @@ -904,7 +902,7 @@ void AudioListener::SetCone(const X3DAUDIO_CONE& listenerCone) throw std::invalid_argument("X3DAUDIO_CONE values out of range"); ListenerCone = listenerCone; - pCone = &ListenerCone; + pCone = &ListenerCone; } bool AudioListener::IsValid() const noexcept @@ -952,7 +950,7 @@ void AudioEmitter::SetCone(const X3DAUDIO_CONE& emitterCone) throw std::invalid_argument("X3DAUDIO_CONE values out of range"); EmitterCone = emitterCone; - pCone = &EmitterCone; + pCone = &EmitterCone; } bool AudioEmitter::IsValid() const noexcept @@ -1075,37 +1073,60 @@ namespace // BACK // - constexpr float LEFT_AZIMUTH = 3 * X3DAUDIO_PI / 2; - constexpr float RIGHT_AZIMUTH = X3DAUDIO_PI / 2; - constexpr float FRONT_LEFT_AZIMUTH = 7 * X3DAUDIO_PI / 4; - constexpr float FRONT_RIGHT_AZIMUTH = X3DAUDIO_PI / 4; - constexpr float FRONT_CENTER_AZIMUTH = 0.0f; + constexpr float LEFT_AZIMUTH = 3 * X3DAUDIO_PI / 2; + constexpr float RIGHT_AZIMUTH = X3DAUDIO_PI / 2; + constexpr float FRONT_LEFT_AZIMUTH = 7 * X3DAUDIO_PI / 4; + constexpr float FRONT_RIGHT_AZIMUTH = X3DAUDIO_PI / 4; + constexpr float FRONT_CENTER_AZIMUTH = 0.0f; constexpr float LOW_FREQUENCY_AZIMUTH = X3DAUDIO_2PI; - constexpr float BACK_LEFT_AZIMUTH = 5 * X3DAUDIO_PI / 4; - constexpr float BACK_RIGHT_AZIMUTH = 3 * X3DAUDIO_PI / 4; - constexpr float BACK_CENTER_AZIMUTH = X3DAUDIO_PI; - - constexpr float c_channelAzimuths[9][8] = - { - /* 0 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, - /* 1 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, - /* 2 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + constexpr float BACK_LEFT_AZIMUTH = 5 * X3DAUDIO_PI / 4; + constexpr float BACK_RIGHT_AZIMUTH = 3 * X3DAUDIO_PI / 4; + constexpr float BACK_CENTER_AZIMUTH = X3DAUDIO_PI; + + constexpr float c_channelAzimuths[9][8] = { + /* 0 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 1 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 2 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, /* 2.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, LOW_FREQUENCY_AZIMUTH, 0.f, 0.f, 0.f, 0.f, 0.f }, /* 4.0 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f, 0.f, 0.f }, /* 4.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f, 0.f }, - /* 5.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f }, - /* 6.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, BACK_CENTER_AZIMUTH, 0.f }, - /* 7.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, LEFT_AZIMUTH, RIGHT_AZIMUTH } + /* 5.1 */ + { FRONT_LEFT_AZIMUTH, + FRONT_RIGHT_AZIMUTH, + FRONT_CENTER_AZIMUTH, + LOW_FREQUENCY_AZIMUTH, + BACK_LEFT_AZIMUTH, + BACK_RIGHT_AZIMUTH, + 0.f, + 0.f }, + /* 6.1 */ + { FRONT_LEFT_AZIMUTH, + FRONT_RIGHT_AZIMUTH, + FRONT_CENTER_AZIMUTH, + LOW_FREQUENCY_AZIMUTH, + BACK_LEFT_AZIMUTH, + BACK_RIGHT_AZIMUTH, + BACK_CENTER_AZIMUTH, + 0.f }, + /* 7.1 */ + { FRONT_LEFT_AZIMUTH, + FRONT_RIGHT_AZIMUTH, + FRONT_CENTER_AZIMUTH, + LOW_FREQUENCY_AZIMUTH, + BACK_LEFT_AZIMUTH, + BACK_RIGHT_AZIMUTH, + LEFT_AZIMUTH, + RIGHT_AZIMUTH } }; -} +} // namespace void AudioEmitter::EnableDefaultMultiChannel(unsigned int channels, float radius) { if (channels > XAUDIO2_MAX_AUDIO_CHANNELS) throw std::invalid_argument("Invalid channel count"); - ChannelCount = channels; - ChannelRadius = radius; + ChannelCount = channels; + ChannelRadius = radius; pChannelAzimuths = EmitterAzimuths; if (channels <= 8) @@ -1122,23 +1143,23 @@ namespace { // **Note these match the defaults from xact3d3.h in the legacy DirectX SDK** constexpr X3DAUDIO_DISTANCE_CURVE_POINT c_defaultCurvePoints[2] = { { 0.0f, 1.0f }, { 1.0f, 1.0f } }; - constexpr X3DAUDIO_DISTANCE_CURVE c_defaultCurve = { const_cast(c_defaultCurvePoints), 2 }; + constexpr X3DAUDIO_DISTANCE_CURVE c_defaultCurve = { const_cast(c_defaultCurvePoints), 2 }; // **Note these match X3DAudioDefault_LinearCurvePoints from x3daudio.h** constexpr X3DAUDIO_DISTANCE_CURVE_POINT c_linearCurvePoints[2] = { { 0.0f, 1.0f }, { 1.0f, 0.0f } }; - constexpr X3DAUDIO_DISTANCE_CURVE c_linearCurve = { const_cast(c_linearCurvePoints), 2 }; -} + constexpr X3DAUDIO_DISTANCE_CURVE c_linearCurve = { const_cast(c_linearCurvePoints), 2 }; +} // namespace void AudioEmitter::EnableDefaultCurves() noexcept { - pVolumeCurve = const_cast(&c_defaultCurve); - pLFECurve = const_cast(&c_defaultCurve); + pVolumeCurve = const_cast(&c_defaultCurve); + pLFECurve = const_cast(&c_defaultCurve); pLPFDirectCurve = pLPFReverbCurve = pReverbCurve = nullptr; } void AudioEmitter::EnableLinearCurves() noexcept { - pVolumeCurve = const_cast(&c_linearCurve); - pLFECurve = const_cast(&c_linearCurve); + pVolumeCurve = const_cast(&c_linearCurve); + pLFECurve = const_cast(&c_linearCurve); pLPFDirectCurve = pLPFReverbCurve = pReverbCurve = nullptr; } diff --git a/Audio/SoundCommon.h b/Audio/SoundCommon.h index 9ac3b46b..a6788f9c 100644 --- a/Audio/SoundCommon.h +++ b/Audio/SoundCommon.h @@ -30,13 +30,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -45,7 +45,6 @@ #endif #endif - namespace DirectX { // Helper for getting a format tag from a WAVEFORMATEX @@ -61,7 +60,9 @@ namespace DirectX auto wfex = reinterpret_cast(wfx); if (memcmp(reinterpret_cast(&wfex->SubFormat) + sizeof(DWORD), - reinterpret_cast(&s_wfexBase) + sizeof(DWORD), sizeof(GUID) - sizeof(DWORD)) != 0) + reinterpret_cast(&s_wfexBase) + sizeof(DWORD), + sizeof(GUID) - sizeof(DWORD)) + != 0) { return 0; } @@ -74,29 +75,29 @@ namespace DirectX } } - // Helper for validating wave format structure DIRECTX_TOOLKIT_API bool __cdecl IsValid(_In_ const WAVEFORMATEX* wfx) noexcept; - // Helper for getting a default channel mask from channels DIRECTX_TOOLKIT_API uint32_t __cdecl GetDefaultChannelMask(int channels) noexcept; - // Helpers for creating various wave format structures - void __cdecl CreateIntegerPCM(_Out_ WAVEFORMATEX* wfx, - int sampleRate, int channels, int sampleBits) noexcept; - void __cdecl CreateFloatPCM(_Out_ WAVEFORMATEX* wfx, - int sampleRate, int channels) noexcept; - void __cdecl CreateADPCM(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, - int sampleRate, int channels, int samplesPerBlock) noexcept(false); + void __cdecl CreateIntegerPCM(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels, int sampleBits) noexcept; + void __cdecl CreateFloatPCM(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels) noexcept; + void __cdecl + CreateADPCM(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int samplesPerBlock) noexcept( + false); #ifdef DIRECTX_ENABLE_XWMA - void __cdecl CreateXWMA(_Out_ WAVEFORMATEX* wfx, - int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept; + void __cdecl CreateXWMA(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept; #endif #ifdef DIRECTX_ENABLE_XMA2 - void __cdecl CreateXMA2(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, - int sampleRate, int channels, int bytesPerBlock, int blockCount, int samplesEncoded) noexcept(false); + void __cdecl CreateXMA2(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, + size_t wfxSize, + int sampleRate, + int channels, + int bytesPerBlock, + int blockCount, + int samplesEncoded) noexcept(false); #endif // Helper for computing pan volume matrix @@ -106,31 +107,28 @@ namespace DirectX class SoundEffectInstanceBase { public: - SoundEffectInstanceBase() noexcept : - voice(nullptr), - state(STOPPED), - engine(nullptr), - mVolume(1.f), - mPitch(0.f), - mFreqRatio(1.f), - mPan(0.f), - mFlags(SoundEffectInstance_Default), - mX3DCalcFlags(0), - mDirectVoice(nullptr), - mReverbVoice(nullptr), - mDSPSettings{} + SoundEffectInstanceBase() noexcept + : voice(nullptr), + state(STOPPED), + engine(nullptr), + mVolume(1.f), + mPitch(0.f), + mFreqRatio(1.f), + mPan(0.f), + mFlags(SoundEffectInstance_Default), + mX3DCalcFlags(0), + mDirectVoice(nullptr), + mReverbVoice(nullptr), + mDSPSettings{} {} - SoundEffectInstanceBase(SoundEffectInstanceBase&&) = default; - SoundEffectInstanceBase& operator= (SoundEffectInstanceBase&&) = default; + SoundEffectInstanceBase(SoundEffectInstanceBase&&) = default; + SoundEffectInstanceBase& operator=(SoundEffectInstanceBase&&) = default; - SoundEffectInstanceBase(SoundEffectInstanceBase const&) = delete; - SoundEffectInstanceBase& operator= (SoundEffectInstanceBase const&) = delete; + SoundEffectInstanceBase(SoundEffectInstanceBase const&) = delete; + SoundEffectInstanceBase& operator=(SoundEffectInstanceBase const&) = delete; - ~SoundEffectInstanceBase() - { - assert(voice == nullptr); - } + ~SoundEffectInstanceBase() { assert(voice == nullptr); } void Initialize(_In_ AudioEngine* eng, _In_ const WAVEFORMATEX* wfx, SOUND_EFFECT_INSTANCE_FLAGS flags) noexcept { @@ -218,13 +216,13 @@ namespace DirectX if (immediate) { - state = STOPPED; + state = STOPPED; std::ignore = voice->Stop(0); std::ignore = voice->FlushSourceBuffers(); } else if (looped) { - looped = false; + looped = false; std::ignore = voice->ExitLoop(); } else @@ -302,7 +300,7 @@ namespace DirectX { // Automatic stop if the buffer has finished playing std::ignore = voice->Stop(); - state = STOPPED; + state = STOPPED; } } @@ -319,10 +317,7 @@ namespace DirectX return static_cast(xstate.BuffersQueued); } - unsigned int GetChannelCount() const noexcept - { - return mDSPSettings.SrcChannelCount; - } + unsigned int GetChannelCount() const noexcept { return mDSPSettings.SrcChannelCount; } void OnCriticalError() noexcept { @@ -331,7 +326,7 @@ namespace DirectX voice->DestroyVoice(); voice = nullptr; } - state = STOPPED; + state = STOPPED; mDirectVoice = nullptr; mReverbVoice = nullptr; } @@ -356,8 +351,8 @@ namespace DirectX voice->DestroyVoice(); voice = nullptr; } - state = STOPPED; - engine = nullptr; + state = STOPPED; + engine = nullptr; mDirectVoice = nullptr; mReverbVoice = nullptr; } @@ -386,9 +381,9 @@ namespace DirectX } } - IXAudio2SourceVoice* voice; - SoundState state; - AudioEngine* engine; + IXAudio2SourceVoice* voice; + SoundState state; + AudioEngine* engine; private: float mVolume; @@ -423,4 +418,4 @@ namespace DirectX const uint32_t* seekTable; uint32_t tag; }; -} +} // namespace DirectX diff --git a/Audio/SoundEffect.cpp b/Audio/SoundEffect.cpp index 3904f047..2dec3b21 100644 --- a/Audio/SoundEffect.cpp +++ b/Audio/SoundEffect.cpp @@ -25,7 +25,6 @@ using namespace DirectX; - //====================================================================================== // SoundEffect //====================================================================================== @@ -34,21 +33,23 @@ using namespace DirectX; class SoundEffect::Impl : public IVoiceNotify { public: - explicit Impl(_In_ AudioEngine* engine) : - mWaveFormat(nullptr), - mStartAudio(nullptr), - mAudioBytes(0), - mLoopStart(0), - mLoopLength(0), - mEngine(engine), - mOneShots(0) - #ifdef DIRECTX_ENABLE_SEEK_TABLES - , mSeekCount(0) - , mSeekTable(nullptr) - #endif - #ifdef DIRECTX_ENABLE_XMA2 - , mXMAMemory(nullptr) - #endif + explicit Impl(_In_ AudioEngine* engine) + : mWaveFormat(nullptr), + mStartAudio(nullptr), + mAudioBytes(0), + mLoopStart(0), + mLoopLength(0), + mEngine(engine), + mOneShots(0) +#ifdef DIRECTX_ENABLE_SEEK_TABLES + , + mSeekCount(0), + mSeekTable(nullptr) +#endif +#ifdef DIRECTX_ENABLE_XMA2 + , + mXMAMemory(nullptr) +#endif { if (!engine) throw std::invalid_argument("AudioEngine is required"); @@ -56,11 +57,11 @@ class SoundEffect::Impl : public IVoiceNotify mEngine->RegisterNotify(this, false); } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() override { @@ -88,37 +89,33 @@ class SoundEffect::Impl : public IVoiceNotify mEngine = nullptr; } - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 if (mXMAMemory) { ApuFree(mXMAMemory); mXMAMemory = nullptr; } - #endif +#endif } - HRESULT Initialize( - _In_ const AudioEngine* engine, - _Inout_ std::unique_ptr& wavData, - _In_ const WAVEFORMATEX* wfx, - _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes, - #ifdef DIRECTX_ENABLE_SEEK_TABLES - _In_reads_opt_(seekCount) const uint32_t* seekTable, size_t seekCount, - #endif - uint32_t loopStart, uint32_t loopLength) noexcept; + HRESULT Initialize(_In_ const AudioEngine* engine, + _Inout_ std::unique_ptr& wavData, + _In_ const WAVEFORMATEX* wfx, + _In_reads_bytes_(audioBytes) const uint8_t* startAudio, + size_t audioBytes, +#ifdef DIRECTX_ENABLE_SEEK_TABLES + _In_reads_opt_(seekCount) const uint32_t* seekTable, + size_t seekCount, +#endif + uint32_t loopStart, + uint32_t loopLength) noexcept; void Play(float volume, float pitch, float pan); // IVoiceNotify - void __cdecl OnBufferEnd() override - { - InterlockedDecrement(&mOneShots); - } + void __cdecl OnBufferEnd() override { InterlockedDecrement(&mOneShots); } - void __cdecl OnCriticalError() override - { - mOneShots = 0; - } + void __cdecl OnCriticalError() override { mOneShots = 0; } void __cdecl OnReset() override { @@ -133,7 +130,7 @@ class SoundEffect::Impl : public IVoiceNotify void __cdecl OnDestroyEngine() noexcept override { - mEngine = nullptr; + mEngine = nullptr; mOneShots = 0; } @@ -147,48 +144,47 @@ class SoundEffect::Impl : public IVoiceNotify stats.playingOneShots += mOneShots; stats.audioBytes += mAudioBytes; - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 if (mXMAMemory) stats.xmaAudioBytes += mAudioBytes; - #endif +#endif } - void __cdecl OnDestroyParent() noexcept override - {} + void __cdecl OnDestroyParent() noexcept override {} - const WAVEFORMATEX* mWaveFormat; - const uint8_t* mStartAudio; - uint32_t mAudioBytes; - uint32_t mLoopStart; - uint32_t mLoopLength; - AudioEngine* mEngine; - std::list mInstances; - uint32_t mOneShots; + const WAVEFORMATEX* mWaveFormat; + const uint8_t* mStartAudio; + uint32_t mAudioBytes; + uint32_t mLoopStart; + uint32_t mLoopLength; + AudioEngine* mEngine; + std::list mInstances; + uint32_t mOneShots; #ifdef DIRECTX_ENABLE_SEEK_TABLES - uint32_t mSeekCount; - const uint32_t* mSeekTable; + uint32_t mSeekCount; + const uint32_t* mSeekTable; #endif private: - std::unique_ptr mWavData; + std::unique_ptr mWavData; #ifdef DIRECTX_ENABLE_XMA2 - void* mXMAMemory; + void* mXMAMemory; #endif }; - -_Use_decl_annotations_ -HRESULT SoundEffect::Impl::Initialize( - const AudioEngine* engine, - std::unique_ptr& wavData, - const WAVEFORMATEX* wfx, - const uint8_t* startAudio, size_t audioBytes, +_Use_decl_annotations_ HRESULT SoundEffect::Impl::Initialize(const AudioEngine* engine, + std::unique_ptr& wavData, + const WAVEFORMATEX* wfx, + const uint8_t* startAudio, + size_t audioBytes, #ifdef DIRECTX_ENABLE_SEEK_TABLES - const uint32_t* seekTable, size_t seekCount, + const uint32_t* seekTable, + size_t seekCount, #endif - uint32_t loopStart, uint32_t loopLength) noexcept + uint32_t loopStart, + uint32_t loopLength) noexcept { if (!engine || !IsValid(wfx) || !startAudio || !audioBytes || !wavData) return E_INVALIDARG; @@ -209,7 +205,7 @@ HRESULT SoundEffect::Impl::Initialize( mStartAudio = startAudio; break; - #ifdef DIRECTX_ENABLE_XWMA +#ifdef DIRECTX_ENABLE_XWMA case WAVE_FORMAT_WMAUDIO2: case WAVE_FORMAT_WMAUDIO3: @@ -228,13 +224,13 @@ HRESULT SoundEffect::Impl::Initialize( // WARNING: We assume the wfx, startAudio, and mSeekTable parameters are pointers into the wavData memory buffer mWaveFormat = wfx; mStartAudio = startAudio; - mSeekCount = static_cast(seekCount); - mSeekTable = seekTable; + mSeekCount = static_cast(seekCount); + mSeekTable = seekTable; break; - #endif // xWMA +#endif // xWMA - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 case WAVE_FORMAT_XMA2: if (!seekCount || !seekTable) @@ -247,8 +243,7 @@ HRESULT SoundEffect::Impl::Initialize( return E_INVALIDARG; { - HRESULT hr = ApuAlloc(&mXMAMemory, nullptr, - static_cast(audioBytes), SHAPE_XMA_INPUT_BUFFER_ALIGNMENT); + HRESULT hr = ApuAlloc(&mXMAMemory, nullptr, static_cast(audioBytes), SHAPE_XMA_INPUT_BUFFER_ALIGNMENT); if (FAILED(hr)) { DebugTrace("ERROR: ApuAlloc failed. Did you allocate a large enough heap with ApuCreateHeap for all your XMA wave data?\n"); @@ -281,23 +276,21 @@ HRESULT SoundEffect::Impl::Initialize( wavData.reset(); break; - #endif // XMA2 +#endif // XMA2 - default: - { - DebugTrace("ERROR: SoundEffect encountered an unsupported format tag (%u)\n", wfx->wFormatTag); - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); - } + default: { + DebugTrace("ERROR: SoundEffect encountered an unsupported format tag (%u)\n", wfx->wFormatTag); + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } } mAudioBytes = static_cast(audioBytes); - mLoopStart = loopStart; + mLoopStart = loopStart; mLoopLength = loopLength; return S_OK; } - void SoundEffect::Impl::Play(float volume, float pitch, float pan) { assert(volume >= -XAUDIO2_MAX_VOLUME_LEVEL && volume <= XAUDIO2_MAX_VOLUME_LEVEL); @@ -338,23 +331,23 @@ void SoundEffect::Impl::Play(float volume, float pitch, float pan) ThrowIfFailed(hr); XAUDIO2_BUFFER buffer = {}; - buffer.AudioBytes = mAudioBytes; - buffer.pAudioData = mStartAudio; - buffer.Flags = XAUDIO2_END_OF_STREAM; - buffer.pContext = this; + buffer.AudioBytes = mAudioBytes; + buffer.pAudioData = mStartAudio; + buffer.Flags = XAUDIO2_END_OF_STREAM; + buffer.pContext = this; #ifdef DIRECTX_ENABLE_XWMA const uint32_t tag = GetFormatTag(mWaveFormat); if (tag == WAVE_FORMAT_WMAUDIO2 || tag == WAVE_FORMAT_WMAUDIO3) { - XAUDIO2_BUFFER_WMA wmaBuffer = {}; - wmaBuffer.PacketCount = mSeekCount; + XAUDIO2_BUFFER_WMA wmaBuffer = {}; + wmaBuffer.PacketCount = mSeekCount; wmaBuffer.pDecodedPacketCumulativeBytes = mSeekTable; hr = voice->SubmitSourceBuffer(&buffer, &wmaBuffer); } else - #endif // xWMA +#endif // xWMA { hr = voice->SubmitSourceBuffer(&buffer, nullptr); } @@ -362,54 +355,60 @@ void SoundEffect::Impl::Play(float volume, float pitch, float pan) { DebugTrace("ERROR: SoundEffect failed (%08X) when submitting buffer:\n", static_cast(hr)); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %u bytes\n", - mWaveFormat->wFormatTag, mWaveFormat->nChannels, mWaveFormat->wBitsPerSample, mWaveFormat->nSamplesPerSec, mAudioBytes); + mWaveFormat->wFormatTag, + mWaveFormat->nChannels, + mWaveFormat->wBitsPerSample, + mWaveFormat->nSamplesPerSec, + mAudioBytes); throw std::runtime_error("SubmitSourceBuffer"); } InterlockedIncrement(&mOneShots); } - //-------------------------------------------------------------------------------------- // SoundEffect //-------------------------------------------------------------------------------------- // Public constructors. -_Use_decl_annotations_ -SoundEffect::SoundEffect(AudioEngine* engine, const wchar_t* waveFileName) +_Use_decl_annotations_ SoundEffect::SoundEffect(AudioEngine* engine, const wchar_t* waveFileName) : pImpl(std::make_unique(engine)) { - WAVData wavInfo; + WAVData wavInfo; std::unique_ptr wavData; - HRESULT hr = LoadWAVAudioFromFileEx(waveFileName, wavData, wavInfo); + HRESULT hr = LoadWAVAudioFromFileEx(waveFileName, wavData, wavInfo); if (FAILED(hr)) { - DebugTrace("ERROR: SoundEffect failed (%08X) to load from .wav file \"%ls\"\n", - static_cast(hr), waveFileName); + DebugTrace("ERROR: SoundEffect failed (%08X) to load from .wav file \"%ls\"\n", static_cast(hr), waveFileName); throw std::runtime_error("SoundEffect"); } #ifdef DIRECTX_ENABLE_SEEK_TABLES - hr = pImpl->Initialize(engine, wavData, wavInfo.wfx, wavInfo.startAudio, wavInfo.audioBytes, - wavInfo.seek, wavInfo.seekCount, - wavInfo.loopStart, wavInfo.loopLength); + hr = pImpl->Initialize(engine, + wavData, + wavInfo.wfx, + wavInfo.startAudio, + wavInfo.audioBytes, + wavInfo.seek, + wavInfo.seekCount, + wavInfo.loopStart, + wavInfo.loopLength); #else - hr = pImpl->Initialize(engine, wavData, wavInfo.wfx, wavInfo.startAudio, wavInfo.audioBytes, - wavInfo.loopStart, wavInfo.loopLength); + hr = pImpl->Initialize(engine, wavData, wavInfo.wfx, wavInfo.startAudio, wavInfo.audioBytes, wavInfo.loopStart, wavInfo.loopLength); #endif if (FAILED(hr)) { - DebugTrace("ERROR: SoundEffect failed (%08X) to intialize from .wav file \"%ls\"\n", - static_cast(hr), waveFileName); + DebugTrace("ERROR: SoundEffect failed (%08X) to intialize from .wav file \"%ls\"\n", static_cast(hr), waveFileName); throw std::runtime_error("SoundEffect"); } } - -_Use_decl_annotations_ -SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavData, - const WAVEFORMATEX* wfx, const uint8_t* startAudio, size_t audioBytes) +_Use_decl_annotations_ SoundEffect::SoundEffect(AudioEngine* engine, + std::unique_ptr& wavData, + const WAVEFORMATEX* wfx, + const uint8_t* startAudio, + size_t audioBytes) : pImpl(std::make_unique(engine)) { #ifdef DIRECTX_ENABLE_SEEK_TABLES @@ -424,11 +423,13 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat } } - -_Use_decl_annotations_ -SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavData, - const WAVEFORMATEX* wfx, const uint8_t* startAudio, size_t audioBytes, - uint32_t loopStart, uint32_t loopLength) +_Use_decl_annotations_ SoundEffect::SoundEffect(AudioEngine* engine, + std::unique_ptr& wavData, + const WAVEFORMATEX* wfx, + const uint8_t* startAudio, + size_t audioBytes, + uint32_t loopStart, + uint32_t loopLength) : pImpl(std::make_unique(engine)) { #ifdef DIRECTX_ENABLE_SEEK_TABLES @@ -443,13 +444,15 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat } } - #ifdef DIRECTX_ENABLE_SEEK_TABLES -_Use_decl_annotations_ -SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavData, - const WAVEFORMATEX* wfx, const uint8_t* startAudio, size_t audioBytes, - const uint32_t* seekTable, size_t seekCount) +_Use_decl_annotations_ SoundEffect::SoundEffect(AudioEngine* engine, + std::unique_ptr& wavData, + const WAVEFORMATEX* wfx, + const uint8_t* startAudio, + size_t audioBytes, + const uint32_t* seekTable, + size_t seekCount) { HRESULT hr = pImpl->Initialize(engine, wavData, wfx, startAudio, audioBytes, seekTable, seekCount, 0, 0); if (FAILED(hr)) @@ -461,11 +464,9 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat #endif - -SoundEffect::SoundEffect(SoundEffect&&) noexcept = default; -SoundEffect& SoundEffect::operator= (SoundEffect&&) noexcept = default; -SoundEffect::~SoundEffect() = default; - +SoundEffect::SoundEffect(SoundEffect&&) noexcept = default; +SoundEffect& SoundEffect::operator=(SoundEffect&&) noexcept = default; +SoundEffect::~SoundEffect() = default; // Public methods. void SoundEffect::Play() @@ -473,13 +474,11 @@ void SoundEffect::Play() pImpl->Play(1.f, 0.f, 0.f); } - void SoundEffect::Play(float volume, float pitch, float pan) { pImpl->Play(volume, pitch, pan); } - std::unique_ptr SoundEffect::CreateInstance(SOUND_EFFECT_INSTANCE_FLAGS flags) { auto effect = new SoundEffectInstance(pImpl->mEngine, this, flags); @@ -488,7 +487,6 @@ std::unique_ptr SoundEffect::CreateInstance(SOUND_EFFECT_IN return std::unique_ptr(effect); } - void SoundEffect::UnregisterInstance(_In_ IVoiceNotify* instance) { auto it = std::find(pImpl->mInstances.begin(), pImpl->mInstances.end(), instance); @@ -498,20 +496,17 @@ void SoundEffect::UnregisterInstance(_In_ IVoiceNotify* instance) pImpl->mInstances.erase(it); } - // Public accessors. bool SoundEffect::IsInUse() const noexcept { return (pImpl->mOneShots > 0) || !pImpl->mInstances.empty(); } - size_t SoundEffect::GetSampleSizeInBytes() const noexcept { return pImpl->mAudioBytes; } - size_t SoundEffect::GetSampleDuration() const noexcept { if (!pImpl->mWaveFormat || !pImpl->mWaveFormat->nChannels) @@ -519,21 +514,20 @@ size_t SoundEffect::GetSampleDuration() const noexcept switch (GetFormatTag(pImpl->mWaveFormat)) { - case WAVE_FORMAT_ADPCM: - { - auto adpcmFmt = reinterpret_cast(pImpl->mWaveFormat); + case WAVE_FORMAT_ADPCM: { + auto adpcmFmt = reinterpret_cast(pImpl->mWaveFormat); - uint64_t duration = uint64_t(pImpl->mAudioBytes / adpcmFmt->wfx.nBlockAlign) * adpcmFmt->wSamplesPerBlock; - const unsigned int partial = pImpl->mAudioBytes % adpcmFmt->wfx.nBlockAlign; - if (partial) - { - if (partial >= (7u * adpcmFmt->wfx.nChannels)) - duration += (uint64_t(partial) * 2 / uint64_t(adpcmFmt->wfx.nChannels - 12)); - } - return static_cast(duration); + uint64_t duration = uint64_t(pImpl->mAudioBytes / adpcmFmt->wfx.nBlockAlign) * adpcmFmt->wSamplesPerBlock; + const unsigned int partial = pImpl->mAudioBytes % adpcmFmt->wfx.nBlockAlign; + if (partial) + { + if (partial >= (7u * adpcmFmt->wfx.nChannels)) + duration += (uint64_t(partial) * 2 / uint64_t(adpcmFmt->wfx.nChannels - 12)); } + return static_cast(duration); + } - #ifdef DIRECTX_ENABLE_XWMA +#ifdef DIRECTX_ENABLE_XWMA case WAVE_FORMAT_WMAUDIO2: case WAVE_FORMAT_WMAUDIO3: @@ -543,27 +537,25 @@ size_t SoundEffect::GetSampleDuration() const noexcept } break; - #endif +#endif - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 - case WAVE_FORMAT_XMA2: - return reinterpret_cast(pImpl->mWaveFormat)->SamplesEncoded; + case WAVE_FORMAT_XMA2: return reinterpret_cast(pImpl->mWaveFormat)->SamplesEncoded; - #endif +#endif default: if (pImpl->mWaveFormat->wBitsPerSample > 0) { return static_cast((uint64_t(pImpl->mAudioBytes) * 8) - / (uint64_t(pImpl->mWaveFormat->wBitsPerSample) * uint64_t(pImpl->mWaveFormat->nChannels))); + / (uint64_t(pImpl->mWaveFormat->wBitsPerSample) * uint64_t(pImpl->mWaveFormat->nChannels))); } } return 0; } - size_t SoundEffect::GetSampleDurationMS() const noexcept { if (!pImpl->mWaveFormat || !pImpl->mWaveFormat->nSamplesPerSec) @@ -573,13 +565,11 @@ size_t SoundEffect::GetSampleDurationMS() const noexcept return static_cast((samples * 1000) / pImpl->mWaveFormat->nSamplesPerSec); } - const WAVEFORMATEX* SoundEffect::GetFormat() const noexcept { return pImpl->mWaveFormat; } - #ifdef DIRECTX_ENABLE_XWMA bool SoundEffect::FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const @@ -589,13 +579,13 @@ bool SoundEffect::FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_B buffer.AudioBytes = pImpl->mAudioBytes; buffer.pAudioData = pImpl->mStartAudio; - buffer.LoopBegin = pImpl->mLoopStart; + buffer.LoopBegin = pImpl->mLoopStart; buffer.LoopLength = pImpl->mLoopLength; const uint32_t tag = GetFormatTag(pImpl->mWaveFormat); if (tag == WAVE_FORMAT_WMAUDIO2 || tag == WAVE_FORMAT_WMAUDIO3) { - wmaBuffer.PacketCount = pImpl->mSeekCount; + wmaBuffer.PacketCount = pImpl->mSeekCount; wmaBuffer.pDecodedPacketCumulativeBytes = pImpl->mSeekTable; return true; } @@ -610,20 +600,18 @@ void SoundEffect::FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer) const memset(&buffer, 0, sizeof(buffer)); buffer.AudioBytes = pImpl->mAudioBytes; buffer.pAudioData = pImpl->mStartAudio; - buffer.LoopBegin = pImpl->mLoopStart; + buffer.LoopBegin = pImpl->mLoopStart; buffer.LoopLength = pImpl->mLoopLength; } #endif - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -_Use_decl_annotations_ -SoundEffect::SoundEffect(AudioEngine* engine, const __wchar_t* waveFileName) : - SoundEffect(engine, reinterpret_cast(waveFileName)) +_Use_decl_annotations_ SoundEffect::SoundEffect(AudioEngine* engine, const __wchar_t* waveFileName) + : SoundEffect(engine, reinterpret_cast(waveFileName)) {} #endif // !_NATIVE_WCHAR_T_DEFINED diff --git a/Audio/SoundEffectInstance.cpp b/Audio/SoundEffectInstance.cpp index 15bb515e..404fca8d 100644 --- a/Audio/SoundEffectInstance.cpp +++ b/Audio/SoundEffectInstance.cpp @@ -13,7 +13,6 @@ using namespace DirectX; - //====================================================================================== // SoundEffectInstance //====================================================================================== @@ -22,12 +21,12 @@ using namespace DirectX; class SoundEffectInstance::Impl : public IVoiceNotify { public: - Impl(_In_ AudioEngine* engine, _In_ SoundEffect* effect, SOUND_EFFECT_INSTANCE_FLAGS flags) : - mBase(), - mEffect(effect), - mWaveBank(nullptr), - mIndex(0), - mLooped(false) + Impl(_In_ AudioEngine* engine, _In_ SoundEffect* effect, SOUND_EFFECT_INSTANCE_FLAGS flags) + : mBase(), + mEffect(effect), + mWaveBank(nullptr), + mIndex(0), + mLooped(false) { assert(engine != nullptr); engine->RegisterNotify(this, false); @@ -36,27 +35,27 @@ class SoundEffectInstance::Impl : public IVoiceNotify mBase.Initialize(engine, effect->GetFormat(), flags); } - Impl(_In_ AudioEngine* engine, _In_ WaveBank* waveBank, uint32_t index, SOUND_EFFECT_INSTANCE_FLAGS flags) : - mBase(), - mEffect(nullptr), - mWaveBank(waveBank), - mIndex(index), - mLooped(false) + Impl(_In_ AudioEngine* engine, _In_ WaveBank* waveBank, uint32_t index, SOUND_EFFECT_INSTANCE_FLAGS flags) + : mBase(), + mEffect(nullptr), + mWaveBank(waveBank), + mIndex(index), + mLooped(false) { assert(engine != nullptr); engine->RegisterNotify(this, false); char buff[64] = {}; - auto wfx = reinterpret_cast(buff); + auto wfx = reinterpret_cast(buff); assert(mWaveBank != nullptr); mBase.Initialize(engine, mWaveBank->GetFormat(index, wfx, sizeof(buff)), flags); } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() override { @@ -78,15 +77,9 @@ class SoundEffectInstance::Impl : public IVoiceNotify assert(false); } - void __cdecl OnCriticalError() override - { - mBase.OnCriticalError(); - } + void __cdecl OnCriticalError() override { mBase.OnCriticalError(); } - void __cdecl OnReset() override - { - mBase.OnReset(); - } + void __cdecl OnReset() override { mBase.OnReset(); } void __cdecl OnUpdate() override { @@ -94,36 +87,26 @@ class SoundEffectInstance::Impl : public IVoiceNotify assert(false); } - void __cdecl OnDestroyEngine() noexcept override - { - mBase.OnDestroy(); - } + void __cdecl OnDestroyEngine() noexcept override { mBase.OnDestroy(); } - void __cdecl OnTrim() override - { - mBase.OnTrim(); - } + void __cdecl OnTrim() override { mBase.OnTrim(); } - void __cdecl GatherStatistics(AudioStatistics& stats) const noexcept override - { - mBase.GatherStatistics(stats); - } + void __cdecl GatherStatistics(AudioStatistics& stats) const noexcept override { mBase.GatherStatistics(stats); } void __cdecl OnDestroyParent() noexcept override { mBase.OnDestroy(); mWaveBank = nullptr; - mEffect = nullptr; + mEffect = nullptr; } - SoundEffectInstanceBase mBase; - SoundEffect* mEffect; - WaveBank* mWaveBank; - uint32_t mIndex; - bool mLooped; + SoundEffectInstanceBase mBase; + SoundEffect* mEffect; + WaveBank* mWaveBank; + uint32_t mIndex; + bool mLooped; }; - void SoundEffectInstance::Impl::Play(bool loop) { if (!mBase.voice) @@ -131,7 +114,7 @@ void SoundEffectInstance::Impl::Play(bool loop) if (mWaveBank) { char buff[64] = {}; - auto wfx = reinterpret_cast(buff); + auto wfx = reinterpret_cast(buff); mBase.AllocateVoice(mWaveBank->GetFormat(mIndex, wfx, sizeof(buff))); } else @@ -149,7 +132,7 @@ void SoundEffectInstance::Impl::Play(bool loop) #ifdef DIRECTX_ENABLE_XWMA - bool iswma = false; + bool iswma = false; XAUDIO2_BUFFER_WMA wmaBuffer = {}; if (mWaveBank) { @@ -178,12 +161,12 @@ void SoundEffectInstance::Impl::Play(bool loop) buffer.Flags = XAUDIO2_END_OF_STREAM; if (loop) { - mLooped = true; + mLooped = true; buffer.LoopCount = XAUDIO2_LOOP_INFINITE; } else { - mLooped = false; + mLooped = false; buffer.LoopCount = buffer.LoopBegin = buffer.LoopLength = 0; } buffer.pContext = nullptr; @@ -195,51 +178,50 @@ void SoundEffectInstance::Impl::Play(bool loop) hr = mBase.voice->SubmitSourceBuffer(&buffer, &wmaBuffer); } else - #endif +#endif { hr = mBase.voice->SubmitSourceBuffer(&buffer, nullptr); } if (FAILED(hr)) { - #ifdef _DEBUG +#ifdef _DEBUG DebugTrace("ERROR: SoundEffectInstance failed (%08X) when submitting buffer:\n", static_cast(hr)); char buff[64] = {}; - auto wfx = (mWaveBank) ? mWaveBank->GetFormat(mIndex, reinterpret_cast(buff), sizeof(buff)) - : mEffect->GetFormat(); + auto wfx = (mWaveBank) ? mWaveBank->GetFormat(mIndex, reinterpret_cast(buff), sizeof(buff)) : mEffect->GetFormat(); const size_t length = (mWaveBank) ? mWaveBank->GetSampleSizeInBytes(mIndex) : mEffect->GetSampleSizeInBytes(); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %zu bytes\n", - wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nSamplesPerSec, length); - #endif + wfx->wFormatTag, + wfx->nChannels, + wfx->wBitsPerSample, + wfx->nSamplesPerSec, + length); +#endif mBase.Stop(true, mLooped); throw std::runtime_error("SubmitSourceBuffer"); } } - //-------------------------------------------------------------------------------------- // SoundEffectInstance //-------------------------------------------------------------------------------------- // Private constructors -_Use_decl_annotations_ -SoundEffectInstance::SoundEffectInstance(AudioEngine* engine, SoundEffect* effect, SOUND_EFFECT_INSTANCE_FLAGS flags) : - pImpl(std::make_unique(engine, effect, flags)) +_Use_decl_annotations_ SoundEffectInstance::SoundEffectInstance(AudioEngine* engine, SoundEffect* effect, SOUND_EFFECT_INSTANCE_FLAGS flags) + : pImpl(std::make_unique(engine, effect, flags)) {} _Use_decl_annotations_ -SoundEffectInstance::SoundEffectInstance(AudioEngine* engine, WaveBank* waveBank, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags) : - pImpl(std::make_unique(engine, waveBank, index, flags)) +SoundEffectInstance::SoundEffectInstance(AudioEngine* engine, WaveBank* waveBank, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags) + : pImpl(std::make_unique(engine, waveBank, index, flags)) {} - // Move ctor/operator. -SoundEffectInstance::SoundEffectInstance(SoundEffectInstance&&) noexcept = default; -SoundEffectInstance& SoundEffectInstance::operator= (SoundEffectInstance&&) noexcept = default; - +SoundEffectInstance::SoundEffectInstance(SoundEffectInstance&&) noexcept = default; +SoundEffectInstance& SoundEffectInstance::operator=(SoundEffectInstance&&) noexcept = default; // Public destructor. SoundEffectInstance::~SoundEffectInstance() @@ -260,75 +242,63 @@ SoundEffectInstance::~SoundEffectInstance() } } - // Public methods. void SoundEffectInstance::Play(bool loop) { pImpl->Play(loop); } - void SoundEffectInstance::Stop(bool immediate) noexcept { pImpl->mBase.Stop(immediate, pImpl->mLooped); } - void SoundEffectInstance::Pause() noexcept { pImpl->mBase.Pause(); } - void SoundEffectInstance::Resume() { pImpl->mBase.Resume(); } - void SoundEffectInstance::SetVolume(float volume) { pImpl->mBase.SetVolume(volume); } - void SoundEffectInstance::SetPitch(float pitch) { pImpl->mBase.SetPitch(pitch); } - void SoundEffectInstance::SetPan(float pan) { pImpl->mBase.SetPan(pan); } - void SoundEffectInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } - // Public accessors. bool SoundEffectInstance::IsLooped() const noexcept { return pImpl->mLooped; } - SoundState SoundEffectInstance::GetState() noexcept { return pImpl->mBase.GetState(true); } - unsigned int SoundEffectInstance::GetChannelCount() const noexcept { return pImpl->mBase.GetChannelCount(); } - IVoiceNotify* SoundEffectInstance::GetVoiceNotify() const noexcept { return pImpl.get(); diff --git a/Audio/SoundStreamInstance.cpp b/Audio/SoundStreamInstance.cpp index dfc3d754..95695834 100644 --- a/Audio/SoundStreamInstance.cpp +++ b/Audio/SoundStreamInstance.cpp @@ -33,7 +33,7 @@ using namespace DirectX; #pragma warning(disable : 4061 4062) #endif -//#define VERBOSE_TRACE +// #define VERBOSE_TRACE #ifdef VERBOSE_TRACE #pragma message("NOTE: Verbose tracing enabled") @@ -41,9 +41,9 @@ using namespace DirectX; namespace { - constexpr size_t DVD_SECTOR_SIZE = 2048; + constexpr size_t DVD_SECTOR_SIZE = 2048; constexpr size_t ADVANCED_FORMAT_SECTOR_SIZE = 4096; - constexpr size_t MAX_BUFFER_COUNT = 3; + constexpr size_t MAX_BUFFER_COUNT = 3; #ifdef DIRECTX_ENABLE_SEEK_TABLES constexpr size_t MAX_STREAMING_SEEK_PACKETS = 2048; @@ -52,7 +52,14 @@ namespace #ifdef DIRECTX_ENABLE_XMA2 constexpr size_t XMA2_64KBLOCKINBYTES = 65536; - struct apu_deleter { void operator()(void* p) noexcept { if (p) ApuFree(p); } }; + struct apu_deleter + { + void operator()(void* p) noexcept + { + if (p) + ApuFree(p); + } + }; #endif size_t ComputeAsyncPacketSize(_In_ const WAVEFORMATEX* wfx, uint32_t tag, uint32_t alignment) @@ -62,23 +69,22 @@ namespace size_t buffer = size_t(wfx->nAvgBytesPerSec) * 2u; - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 if (tag == WAVE_FORMAT_XMA2) { buffer = AlignUp(buffer, XMA2_64KBLOCKINBYTES); buffer = std::max(XMA2_64KBLOCKINBYTES, buffer); return buffer; } - #else +#else UNREFERENCED_PARAMETER(tag); - #endif +#endif buffer = AlignUp(buffer, size_t(alignment) * 2); buffer = std::max(65536u, buffer); return buffer; } -} - +} // namespace //====================================================================================== // SoundStreamInstance @@ -88,58 +94,56 @@ namespace class SoundStreamInstance::Impl : public IVoiceNotify { public: - Impl(_In_ AudioEngine* engine, - WaveBank* waveBank, - uint32_t index, - SOUND_EFFECT_INSTANCE_FLAGS flags) noexcept(false) : - mBase(), - mWaveBank(waveBank), - mIndex(index), - mPlaying(false), - mLooped(false), - mEndStream(false), - mPrefetch(false), - mSitching(false), - mPackets{}, - mCurrentDiskReadBuffer(0), - mCurrentPlayBuffer(0), - mBlockAlign(0), - mAsyncAlign(DVD_SECTOR_SIZE), - mCurrentPosition(0), - mOffsetBytes(0), - mLengthInBytes(0), - mPacketSize(0), - mTotalSize(0) - #ifdef DIRECTX_ENABLE_SEEK_TABLES - , mSeekCount(0), - mSeekTable(nullptr), - mSeekTableCopy{} - #endif + Impl(_In_ AudioEngine* engine, WaveBank* waveBank, uint32_t index, SOUND_EFFECT_INSTANCE_FLAGS flags) noexcept(false) + : mBase(), + mWaveBank(waveBank), + mIndex(index), + mPlaying(false), + mLooped(false), + mEndStream(false), + mPrefetch(false), + mSitching(false), + mPackets{}, + mCurrentDiskReadBuffer(0), + mCurrentPlayBuffer(0), + mBlockAlign(0), + mAsyncAlign(DVD_SECTOR_SIZE), + mCurrentPosition(0), + mOffsetBytes(0), + mLengthInBytes(0), + mPacketSize(0), + mTotalSize(0) +#ifdef DIRECTX_ENABLE_SEEK_TABLES + , + mSeekCount(0), + mSeekTable(nullptr), + mSeekTableCopy{} +#endif { assert(engine != nullptr); engine->RegisterNotify(this, true); char buff[64] = {}; - auto wfx = reinterpret_cast(buff); + auto wfx = reinterpret_cast(buff); assert(mWaveBank != nullptr); mBase.Initialize(engine, mWaveBank->GetFormat(index, wfx, sizeof(buff)), flags); WaveBankReader::Metadata metadata = {}; - std::ignore = mWaveBank->GetPrivateData(index, &metadata, sizeof(metadata)); + std::ignore = mWaveBank->GetPrivateData(index, &metadata, sizeof(metadata)); - mOffsetBytes = metadata.offsetBytes; + mOffsetBytes = metadata.offsetBytes; mLengthInBytes = metadata.lengthBytes; - mAsyncAlign = mWaveBank->IsAdvancedFormat() ? ADVANCED_FORMAT_SECTOR_SIZE : DVD_SECTOR_SIZE; + mAsyncAlign = mWaveBank->IsAdvancedFormat() ? ADVANCED_FORMAT_SECTOR_SIZE : DVD_SECTOR_SIZE; - #ifdef DIRECTX_ENABLE_SEEK_TABLES +#ifdef DIRECTX_ENABLE_SEEK_TABLES WaveBankSeekData seekData = {}; - std::ignore = mWaveBank->GetPrivateData(index, &seekData, sizeof(seekData)); + std::ignore = mWaveBank->GetPrivateData(index, &seekData, sizeof(seekData)); if (seekData.tag == WAVE_FORMAT_WMAUDIO2 || seekData.tag == WAVE_FORMAT_WMAUDIO3) { mSeekCount = seekData.seekCount; mSeekTable = seekData.seekTable; } - #endif +#endif mBufferEnd.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); mBufferRead.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); @@ -150,9 +154,9 @@ class SoundStreamInstance::Impl : public IVoiceNotify ThrowIfFailed(AllocateStreamingBuffers(wfx)); - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO (Streaming): packet size %zu, play length %zu\n", mPacketSize, mLengthInBytes); - #endif +#endif mPrefetch = true; ThrowIfFailed(ReadBuffers()); @@ -183,11 +187,11 @@ class SoundStreamInstance::Impl : public IVoiceNotify mPacketSize = 0; } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; void Play(bool loop) { @@ -197,14 +201,14 @@ class SoundStreamInstance::Impl : public IVoiceNotify return; char buff[64] = {}; - auto wfx = reinterpret_cast(buff); + auto wfx = reinterpret_cast(buff); mBase.AllocateVoice(mWaveBank->GetFormat(mIndex, wfx, sizeof(buff))); } if (!mBase.Play()) return; - mLooped = loop; + mLooped = loop; mEndStream = false; if (!mPrefetch) @@ -221,15 +225,9 @@ class SoundStreamInstance::Impl : public IVoiceNotify // Not used } - virtual void __cdecl OnCriticalError() override - { - mBase.OnCriticalError(); - } + virtual void __cdecl OnCriticalError() override { mBase.OnCriticalError(); } - virtual void __cdecl OnReset() override - { - mBase.OnReset(); - } + virtual void __cdecl OnReset() override { mBase.OnReset(); } virtual void __cdecl OnUpdate() override { @@ -240,31 +238,30 @@ class SoundStreamInstance::Impl : public IVoiceNotify switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { default: - case WAIT_TIMEOUT: - break; + case WAIT_TIMEOUT: break; case WAIT_OBJECT_0: // Read completed - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO (Streaming): Playing... (readpos %zu) [", mCurrentPosition); for (uint32_t k = 0; k < MAX_BUFFER_COUNT; ++k) { DebugTrace("%ls ", s_debugState[static_cast(mPackets[k].state)]); } DebugTrace("]\n"); - #endif +#endif mPrefetch = false; ThrowIfFailed(PlayBuffers()); break; case (WAIT_OBJECT_0 + 1): // Play completed - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO (Streaming): Reading... (readpos %zu) [", mCurrentPosition); for (uint32_t k = 0; k < MAX_BUFFER_COUNT; ++k) { DebugTrace("%ls ", s_debugState[static_cast(mPackets[k].state)]); } DebugTrace("]\n"); - #endif +#endif ThrowIfFailed(ReadBuffers()); break; @@ -273,15 +270,9 @@ class SoundStreamInstance::Impl : public IVoiceNotify } } - virtual void __cdecl OnDestroyEngine() noexcept override - { - mBase.OnDestroy(); - } + virtual void __cdecl OnDestroyEngine() noexcept override { mBase.OnDestroy(); } - virtual void __cdecl OnTrim() override - { - mBase.OnTrim(); - } + virtual void __cdecl OnTrim() override { mBase.OnTrim(); } virtual void __cdecl GatherStatistics(AudioStatistics& stats) const noexcept override { @@ -296,17 +287,17 @@ class SoundStreamInstance::Impl : public IVoiceNotify mWaveBank = nullptr; } - SoundEffectInstanceBase mBase; - WaveBank* mWaveBank; - uint32_t mIndex; - bool mPlaying; - bool mLooped; - bool mEndStream; - bool mPrefetch; - bool mSitching; + SoundEffectInstanceBase mBase; + WaveBank* mWaveBank; + uint32_t mIndex; + bool mPlaying; + bool mLooped; + bool mEndStream; + bool mPrefetch; + bool mSitching; - ScopedHandle mBufferEnd; - ScopedHandle mBufferRead; + ScopedHandle mBufferEnd; + ScopedHandle mBufferRead; enum class State : uint32_t { @@ -322,9 +313,16 @@ class SoundStreamInstance::Impl : public IVoiceNotify struct BufferNotify : public IVoiceNotify { - BufferNotify() : mParent(nullptr), mIndex(0) {} + BufferNotify() + : mParent(nullptr), + mIndex(0) + {} - void Set(SoundStreamInstance::Impl* parent, size_t index) noexcept(true) { mParent = parent; mIndex = index; } + void Set(SoundStreamInstance::Impl* parent, size_t index) noexcept(true) + { + mParent = parent; + mIndex = index; + } void __cdecl OnBufferEnd() override { @@ -333,61 +331,89 @@ class SoundStreamInstance::Impl : public IVoiceNotify SetEvent(mParent->mBufferEnd.get()); } - void __cdecl OnCriticalError() override { assert(mParent != nullptr); mParent->OnCriticalError(); } - void __cdecl OnReset() override { assert(mParent != nullptr); mParent->OnReset(); } - void __cdecl OnUpdate() override { assert(mParent != nullptr); mParent->OnUpdate(); } - void __cdecl OnDestroyEngine() noexcept override { assert(mParent != nullptr); mParent->OnDestroyEngine(); } - void __cdecl OnTrim() override { assert(mParent != nullptr); mParent->OnTrim(); } - void __cdecl GatherStatistics(AudioStatistics& stats) const override { assert(mParent != nullptr); mParent->GatherStatistics(stats); } - void __cdecl OnDestroyParent() noexcept override { assert(mParent != nullptr); mParent->OnDestroyParent(); } + void __cdecl OnCriticalError() override + { + assert(mParent != nullptr); + mParent->OnCriticalError(); + } + void __cdecl OnReset() override + { + assert(mParent != nullptr); + mParent->OnReset(); + } + void __cdecl OnUpdate() override + { + assert(mParent != nullptr); + mParent->OnUpdate(); + } + void __cdecl OnDestroyEngine() noexcept override + { + assert(mParent != nullptr); + mParent->OnDestroyEngine(); + } + void __cdecl OnTrim() override + { + assert(mParent != nullptr); + mParent->OnTrim(); + } + void __cdecl GatherStatistics(AudioStatistics& stats) const override + { + assert(mParent != nullptr); + mParent->GatherStatistics(stats); + } + void __cdecl OnDestroyParent() noexcept override + { + assert(mParent != nullptr); + mParent->OnDestroyParent(); + } private: SoundStreamInstance::Impl* mParent; - size_t mIndex; + size_t mIndex; }; struct Packets { - State state; - uint8_t* buffer; - uint8_t* stitchBuffer; - uint32_t valid; - uint32_t audioBytes; - uint32_t startPosition; - OVERLAPPED request; + State state; + uint8_t* buffer; + uint8_t* stitchBuffer; + uint32_t valid; + uint32_t audioBytes; + uint32_t startPosition; + OVERLAPPED request; BufferNotify notify; - Packets() : - state(State::FREE), - buffer(nullptr), - stitchBuffer(nullptr), - valid(0), - audioBytes(0), - startPosition(0), - request{}, - notify{} + Packets() + : state(State::FREE), + buffer(nullptr), + stitchBuffer(nullptr), + valid(0), + audioBytes(0), + startPosition(0), + request{}, + notify{} {} }; - Packets mPackets[MAX_BUFFER_COUNT]; + Packets mPackets[MAX_BUFFER_COUNT]; private: - uint32_t mCurrentDiskReadBuffer; - uint32_t mCurrentPlayBuffer; - uint32_t mBlockAlign; - uint32_t mAsyncAlign; - size_t mCurrentPosition; - size_t mOffsetBytes; - size_t mLengthInBytes; - - size_t mPacketSize; - size_t mTotalSize; + uint32_t mCurrentDiskReadBuffer; + uint32_t mCurrentPlayBuffer; + uint32_t mBlockAlign; + uint32_t mAsyncAlign; + size_t mCurrentPosition; + size_t mOffsetBytes; + size_t mLengthInBytes; + + size_t mPacketSize; + size_t mTotalSize; std::unique_ptr mStreamBuffer; #ifdef DIRECTX_ENABLE_SEEK_TABLES - uint32_t mSeekCount; - const uint32_t* mSeekTable; - uint32_t mSeekTableCopy[MAX_STREAMING_SEEK_PACKETS]; + uint32_t mSeekCount; + const uint32_t* mSeekTable; + uint32_t mSeekTableCopy[MAX_STREAMING_SEEK_PACKETS]; #endif #ifdef DIRECTX_ENABLE_XMA2 @@ -399,7 +425,6 @@ class SoundStreamInstance::Impl : public IVoiceNotify HRESULT PlayBuffers() noexcept; }; - HRESULT SoundStreamInstance::Impl::AllocateStreamingBuffers(const WAVEFORMATEX* wfx) noexcept { if (!wfx) @@ -417,7 +442,7 @@ HRESULT SoundStreamInstance::Impl::AllocateStreamingBuffers(const WAVEFORMATEX* mPacketSize = packetSize; mBlockAlign = wfx->nBlockAlign; - mSitching = false; + mSitching = false; size_t stitchSize = 0; if ((packetSize % wfx->nBlockAlign) != 0) @@ -432,51 +457,53 @@ HRESULT SoundStreamInstance::Impl::AllocateStreamingBuffers(const WAVEFORMATEX* #ifdef DIRECTX_ENABLE_XMA2 if ((mTotalSize < totalSize) || (tag == WAVE_FORMAT_XMA2 && !mXMAMemory) || (tag != WAVE_FORMAT_XMA2 && !mStreamBuffer)) - #else +#else if (mTotalSize < totalSize) - #endif +#endif { mStreamBuffer.reset(); - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 mXMAMemory.reset(); if (tag == WAVE_FORMAT_XMA2) { - void* xmaMemory = nullptr; - HRESULT hr = ApuAlloc(&xmaMemory, nullptr, static_cast(totalSize), SHAPE_XMA_INPUT_BUFFER_ALIGNMENT); + void* xmaMemory = nullptr; + HRESULT hr = ApuAlloc(&xmaMemory, nullptr, static_cast(totalSize), SHAPE_XMA_INPUT_BUFFER_ALIGNMENT); if (FAILED(hr)) { - DebugTrace("ERROR: ApuAlloc failed (%llu bytes). Did you allocate a large enough heap with ApuCreateHeap for all your XMA wave data?\n", totalSize); + DebugTrace( + "ERROR: ApuAlloc failed (%llu bytes). Did you allocate a large enough heap with ApuCreateHeap for all your XMA wave " + "data?\n", + totalSize); return hr; } mXMAMemory.reset(static_cast(xmaMemory)); } else - #endif +#endif { - mStreamBuffer.reset(reinterpret_cast( - VirtualAlloc(nullptr, static_cast(totalSize), MEM_COMMIT, PAGE_READWRITE) - )); + mStreamBuffer.reset( + reinterpret_cast(VirtualAlloc(nullptr, static_cast(totalSize), MEM_COMMIT, PAGE_READWRITE))); if (!mStreamBuffer) { DebugTrace("ERROR: Failed allocating %llu bytes for SoundStreamInstance\n", totalSize); mPacketSize = 0; - totalSize = 0; + totalSize = 0; return E_OUTOFMEMORY; } } mTotalSize = static_cast(totalSize); - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 uint8_t* ptr = (tag == WAVE_FORMAT_XMA2) ? mXMAMemory.get() : mStreamBuffer.get(); - #else +#else uint8_t* ptr = mStreamBuffer.get(); - #endif +#endif for (size_t j = 0; j < MAX_BUFFER_COUNT; ++j) { - mPackets[j].buffer = ptr; - mPackets[j].stitchBuffer = nullptr; + mPackets[j].buffer = ptr; + mPackets[j].stitchBuffer = nullptr; mPackets[j].request.hEvent = mBufferRead.get(); mPackets[j].notify.Set(this, j); ptr += packetSize; @@ -495,7 +522,6 @@ HRESULT SoundStreamInstance::Impl::AllocateStreamingBuffers(const WAVEFORMATEX* return S_OK; } - HRESULT SoundStreamInstance::Impl::ReadBuffers() noexcept { if (mCurrentPosition >= mLengthInBytes) @@ -506,9 +532,9 @@ HRESULT SoundStreamInstance::Impl::ReadBuffers() noexcept return S_FALSE; } - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO (Streaming): Loop restart\n"); - #endif +#endif mCurrentPosition = 0; } @@ -527,9 +553,9 @@ HRESULT SoundStreamInstance::Impl::ReadBuffers() noexcept { const auto cbValid = static_cast(std::min(mPacketSize, mLengthInBytes - mCurrentPosition)); - mPackets[entry].valid = cbValid; - mPackets[entry].audioBytes = 0; - mPackets[entry].startPosition = static_cast(mCurrentPosition); + mPackets[entry].valid = cbValid; + mPackets[entry].audioBytes = 0; + mPackets[entry].startPosition = static_cast(mCurrentPosition); mPackets[entry].request.Offset = static_cast(mOffsetBytes + mCurrentPosition); if (!ReadFile(async, mPackets[entry].buffer, uint32_t(mPacketSize), nullptr, &mPackets[entry].request)) @@ -537,13 +563,14 @@ HRESULT SoundStreamInstance::Impl::ReadBuffers() noexcept const DWORD error = GetLastError(); if (error != ERROR_IO_PENDING) { - #ifdef _DEBUG +#ifdef _DEBUG if (error == ERROR_INVALID_PARAMETER) { // May be due to Advanced Format (4Kn) vs. DVD sector size. See the xwbtool -af switch. - OutputDebugStringA("ERROR: non-buffered async I/O failed: check disk sector size vs. streaming wave bank alignment!\n"); + OutputDebugStringA( + "ERROR: non-buffered async I/O failed: check disk sector size vs. streaming wave bank alignment!\n"); } - #endif +#endif return HRESULT_FROM_WIN32(error); } } @@ -556,9 +583,9 @@ HRESULT SoundStreamInstance::Impl::ReadBuffers() noexcept if ((cbValid < mPacketSize) && mLooped) { - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO (Streaming): Loop restart\n"); - #endif +#endif mCurrentPosition = 0; } } @@ -568,7 +595,6 @@ HRESULT SoundStreamInstance::Impl::ReadBuffers() noexcept return S_OK; } - HRESULT SoundStreamInstance::Impl::PlayBuffers() noexcept { HANDLE async = mWaveBank->GetAsyncHandle(); @@ -579,7 +605,7 @@ HRESULT SoundStreamInstance::Impl::PlayBuffers() noexcept { if (mPackets[j].state == State::PENDING) { - DWORD cb = 0; + DWORD cb = 0; const BOOL result = GetOverlappedResultEx(async, &mPackets[j].request, &cb, 0, FALSE); if (result) { @@ -604,16 +630,16 @@ HRESULT SoundStreamInstance::Impl::PlayBuffers() noexcept if (mPackets[mCurrentPlayBuffer].state != State::READY) break; - const uint8_t* ptr = mPackets[mCurrentPlayBuffer].buffer; - uint32_t valid = mPackets[mCurrentPlayBuffer].valid; + const uint8_t* ptr = mPackets[mCurrentPlayBuffer].buffer; + uint32_t valid = mPackets[mCurrentPlayBuffer].valid; bool endstream = false; if (valid < mPacketSize) { endstream = true; - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO (Streaming): End of stream (%u of %zu bytes)\n", mPackets[mCurrentPlayBuffer].valid, mPacketSize); - #endif +#endif } uint32_t thisFrameStitch = 0; @@ -634,10 +660,10 @@ HRESULT SoundStreamInstance::Impl::PlayBuffers() noexcept { // Compute how many bytes at the start of the previous packet were the tail of the previous stitch block. uint32_t prevFrameStitchOffset = (mPackets[k].startPosition % mBlockAlign); - prevFrameStitchOffset = (prevFrameStitchOffset > 0) ? (mBlockAlign - prevFrameStitchOffset) : 0u; + prevFrameStitchOffset = (prevFrameStitchOffset > 0) ? (mBlockAlign - prevFrameStitchOffset) : 0u; // Point to the start of the partial block's head in the previous packet. - const auto *prevBuffer = mPackets[k].buffer + prevFrameStitchOffset + mPackets[k].audioBytes; + const auto* prevBuffer = mPackets[k].buffer + prevFrameStitchOffset + mPackets[k].audioBytes; // Merge the the head partial block in the previous packet with the tail partial block at the start of our packet. memcpy(buffer, prevBuffer, prevFrameStitch); @@ -645,32 +671,33 @@ HRESULT SoundStreamInstance::Impl::PlayBuffers() noexcept // Submit stitch packet (only need to get notified if we aren't submitting another packet for this buffer). XAUDIO2_BUFFER buf = {}; - buf.AudioBytes = mBlockAlign; - buf.pAudioData = buffer; + buf.AudioBytes = mBlockAlign; + buf.pAudioData = buffer; if (endstream && (valid <= thisFrameStitch)) { - buf.Flags = XAUDIO2_END_OF_STREAM; + buf.Flags = XAUDIO2_END_OF_STREAM; buf.pContext = &mPackets[mCurrentPlayBuffer].notify; } - #ifdef VERBOSE_TRACE +#ifdef VERBOSE_TRACE DebugTrace("INFO (Streaming): Stitch packet (%u + %u = %u)\n", prevFrameStitch, thisFrameStitch, mBlockAlign); - #endif - #ifdef DIRECTX_ENABLE_XWMA +#endif +#ifdef DIRECTX_ENABLE_XWMA if (mSeekCount > 0) { - XAUDIO2_BUFFER_WMA wmaBuf = {}; + XAUDIO2_BUFFER_WMA wmaBuf = {}; wmaBuf.pDecodedPacketCumulativeBytes = mSeekTableCopy; - wmaBuf.PacketCount = 1; + wmaBuf.PacketCount = 1; - const uint32_t seekOffset = (mPackets[k].startPosition + prevFrameStitchOffset + mPackets[k].audioBytes) / mBlockAlign; + const uint32_t seekOffset + = (mPackets[k].startPosition + prevFrameStitchOffset + mPackets[k].audioBytes) / mBlockAlign; assert(seekOffset > 0); mSeekTableCopy[0] = mSeekTable[seekOffset] - mSeekTable[seekOffset - 1]; ThrowIfFailed(mBase.voice->SubmitSourceBuffer(&buf, &wmaBuf)); } else - #endif // XWMA +#endif // XWMA { ThrowIfFailed(mBase.voice->SubmitSourceBuffer(&buf)); } @@ -689,12 +716,12 @@ HRESULT SoundStreamInstance::Impl::PlayBuffers() noexcept mPackets[mCurrentPlayBuffer].audioBytes = valid; XAUDIO2_BUFFER buf = {}; - buf.Flags = (endstream) ? XAUDIO2_END_OF_STREAM : 0; - buf.AudioBytes = valid; - buf.pAudioData = ptr; - buf.pContext = &mPackets[mCurrentPlayBuffer].notify; + buf.Flags = (endstream) ? XAUDIO2_END_OF_STREAM : 0; + buf.AudioBytes = valid; + buf.pAudioData = ptr; + buf.pContext = &mPackets[mCurrentPlayBuffer].notify; - #ifdef DIRECTX_ENABLE_XWMA +#ifdef DIRECTX_ENABLE_XWMA if (mSeekCount > 0) { XAUDIO2_BUFFER_WMA wmaBuf = {}; @@ -724,45 +751,36 @@ HRESULT SoundStreamInstance::Impl::PlayBuffers() noexcept ThrowIfFailed(mBase.voice->SubmitSourceBuffer(&buf, &wmaBuf)); } else - #endif // xWMA +#endif // xWMA { ThrowIfFailed(mBase.voice->SubmitSourceBuffer(&buf)); } } mPackets[mCurrentPlayBuffer].state = State::PLAYING; - mCurrentPlayBuffer = (mCurrentPlayBuffer + 1) % uint32_t(MAX_BUFFER_COUNT); + mCurrentPlayBuffer = (mCurrentPlayBuffer + 1) % uint32_t(MAX_BUFFER_COUNT); } return S_OK; } #ifdef VERBOSE_TRACE -const wchar_t* SoundStreamInstance::Impl::s_debugState[4] = -{ - L"FREE", - L"PENDING", - L"READY", - L"PLAYING" -}; +const wchar_t* SoundStreamInstance::Impl::s_debugState[4] = { L"FREE", L"PENDING", L"READY", L"PLAYING" }; #endif - //-------------------------------------------------------------------------------------- // SoundStreamInstance //-------------------------------------------------------------------------------------- // Private constructors _Use_decl_annotations_ -SoundStreamInstance::SoundStreamInstance(AudioEngine* engine, WaveBank* waveBank, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags) : - pImpl(std::make_unique(engine, waveBank, index, flags)) +SoundStreamInstance::SoundStreamInstance(AudioEngine* engine, WaveBank* waveBank, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags) + : pImpl(std::make_unique(engine, waveBank, index, flags)) {} - // Move ctor/operator. -SoundStreamInstance::SoundStreamInstance(SoundStreamInstance&&) noexcept = default; -SoundStreamInstance& SoundStreamInstance::operator= (SoundStreamInstance&&) noexcept = default; - +SoundStreamInstance::SoundStreamInstance(SoundStreamInstance&&) noexcept = default; +SoundStreamInstance& SoundStreamInstance::operator=(SoundStreamInstance&&) noexcept = default; // Public destructor. SoundStreamInstance::~SoundStreamInstance() @@ -777,7 +795,6 @@ SoundStreamInstance::~SoundStreamInstance() } } - // Public methods. void SoundStreamInstance::Play(bool loop) { @@ -785,57 +802,48 @@ void SoundStreamInstance::Play(bool loop) pImpl->mPlaying = true; } - void SoundStreamInstance::Stop(bool immediate) noexcept { pImpl->mBase.Stop(immediate, pImpl->mLooped); pImpl->mPlaying = !immediate; } - void SoundStreamInstance::Pause() noexcept { pImpl->mBase.Pause(); } - void SoundStreamInstance::Resume() { pImpl->mBase.Resume(); } - void SoundStreamInstance::SetVolume(float volume) { pImpl->mBase.SetVolume(volume); } - void SoundStreamInstance::SetPitch(float pitch) { pImpl->mBase.SetPitch(pitch); } - void SoundStreamInstance::SetPan(float pan) { pImpl->mBase.SetPan(pan); } - void SoundStreamInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } - // Public accessors. bool SoundStreamInstance::IsLooped() const noexcept { return pImpl->mLooped; } - SoundState SoundStreamInstance::GetState() noexcept { const SoundState state = pImpl->mBase.GetState(pImpl->mEndStream); @@ -846,13 +854,11 @@ SoundState SoundStreamInstance::GetState() noexcept return state; } - unsigned int SoundStreamInstance::GetChannelCount() const noexcept { return pImpl->mBase.GetChannelCount(); } - IVoiceNotify* SoundStreamInstance::GetVoiceNotify() const noexcept { return pImpl.get(); diff --git a/Audio/WAVFileReader.cpp b/Audio/WAVFileReader.cpp index 04dfcc37..f01511c7 100644 --- a/Audio/WAVFileReader.cpp +++ b/Audio/WAVFileReader.cpp @@ -16,27 +16,26 @@ using namespace DirectX; - namespace { //--------------------------------------------------------------------------------- // .WAV files //--------------------------------------------------------------------------------- - constexpr uint32_t FOURCC_RIFF_TAG = MAKEFOURCC('R', 'I', 'F', 'F'); - constexpr uint32_t FOURCC_FORMAT_TAG = MAKEFOURCC('f', 'm', 't', ' '); - constexpr uint32_t FOURCC_DATA_TAG = MAKEFOURCC('d', 'a', 't', 'a'); + constexpr uint32_t FOURCC_RIFF_TAG = MAKEFOURCC('R', 'I', 'F', 'F'); + constexpr uint32_t FOURCC_FORMAT_TAG = MAKEFOURCC('f', 'm', 't', ' '); + constexpr uint32_t FOURCC_DATA_TAG = MAKEFOURCC('d', 'a', 't', 'a'); constexpr uint32_t FOURCC_WAVE_FILE_TAG = MAKEFOURCC('W', 'A', 'V', 'E'); constexpr uint32_t FOURCC_XWMA_FILE_TAG = MAKEFOURCC('X', 'W', 'M', 'A'); - constexpr uint32_t FOURCC_DLS_SAMPLE = MAKEFOURCC('w', 's', 'm', 'p'); - constexpr uint32_t FOURCC_MIDI_SAMPLE = MAKEFOURCC('s', 'm', 'p', 'l'); - constexpr uint32_t FOURCC_XWMA_DPDS = MAKEFOURCC('d', 'p', 'd', 's'); - constexpr uint32_t FOURCC_XMA_SEEK = MAKEFOURCC('s', 'e', 'e', 'k'); + constexpr uint32_t FOURCC_DLS_SAMPLE = MAKEFOURCC('w', 's', 'm', 'p'); + constexpr uint32_t FOURCC_MIDI_SAMPLE = MAKEFOURCC('s', 'm', 'p', 'l'); + constexpr uint32_t FOURCC_XWMA_DPDS = MAKEFOURCC('d', 'p', 'd', 's'); + constexpr uint32_t FOURCC_XMA_SEEK = MAKEFOURCC('s', 'e', 'e', 'k'); constexpr size_t SIZEOF_XMA2WAVEFORMATEX = 52; constexpr uint16_t MSADPCM_FORMAT_EXTRA_BYTES = 32; -#pragma pack(push,1) +#pragma pack(push, 1) struct RIFFChunk { uint32_t tag; @@ -63,22 +62,22 @@ namespace struct RIFFDLSSample { - static constexpr uint32_t OPTIONS_NOTRUNCATION = 0x00000001; + static constexpr uint32_t OPTIONS_NOTRUNCATION = 0x00000001; static constexpr uint32_t OPTIONS_NOCOMPRESSION = 0x00000002; - uint32_t size; - uint16_t unityNote; - int16_t fineTune; - int32_t gain; - uint32_t options; - uint32_t loopCount; + uint32_t size; + uint16_t unityNote; + int16_t fineTune; + int32_t gain; + uint32_t options; + uint32_t loopCount; }; struct MIDILoop { - static constexpr uint32_t LOOP_TYPE_FORWARD = 0x00000000; + static constexpr uint32_t LOOP_TYPE_FORWARD = 0x00000000; static constexpr uint32_t LOOP_TYPE_ALTERNATING = 0x00000001; - static constexpr uint32_t LOOP_TYPE_BACKWARD = 0x00000002; + static constexpr uint32_t LOOP_TYPE_BACKWARD = 0x00000002; uint32_t cuePointId; uint32_t type; @@ -90,15 +89,15 @@ namespace struct RIFFMIDISample { - uint32_t manufacturerId; - uint32_t productId; - uint32_t samplePeriod; - uint32_t unityNode; - uint32_t pitchFraction; - uint32_t SMPTEFormat; - uint32_t SMPTEOffset; - uint32_t loopCount; - uint32_t samplerData; + uint32_t manufacturerId; + uint32_t productId; + uint32_t samplePeriod; + uint32_t unityNode; + uint32_t pitchFraction; + uint32_t SMPTEFormat; + uint32_t SMPTEOffset; + uint32_t loopCount; + uint32_t samplerData; }; #pragma pack(pop) @@ -110,11 +109,10 @@ namespace static_assert(sizeof(RIFFMIDISample) == 36, "structure size mismatch"); //--------------------------------------------------------------------------------- - const RIFFChunk* FindChunk( - _In_reads_bytes_(sizeBytes) const uint8_t* data, - _In_ size_t sizeBytes, - _In_ const uint8_t* upperBound, - _In_ uint32_t tag) noexcept + const RIFFChunk* FindChunk(_In_reads_bytes_(sizeBytes) const uint8_t* data, + _In_ size_t sizeBytes, + _In_ const uint8_t* upperBound, + _In_ uint32_t tag) noexcept { if (!data || !upperBound) return nullptr; @@ -153,16 +151,14 @@ namespace return nullptr; } - //--------------------------------------------------------------------------------- - HRESULT WaveFindFormatAndData( - _In_reads_bytes_(wavDataSize) const uint8_t* wavData, - _In_ size_t wavDataSize, - _Outptr_ const WAVEFORMATEX** pwfx, - _Outptr_ const uint8_t** pdata, - _Out_ uint32_t* dataSize, - _Out_ bool& dpds, - _Out_ bool& seek) noexcept + HRESULT WaveFindFormatAndData(_In_reads_bytes_(wavDataSize) const uint8_t* wavData, + _In_ size_t wavDataSize, + _Outptr_ const WAVEFORMATEX** pwfx, + _Outptr_ const uint8_t** pdata, + _Out_ uint32_t* dataSize, + _Out_ bool& dpds, + _Out_ bool& seek) noexcept { if (!wavData || !pwfx) return E_POINTER; @@ -225,110 +221,105 @@ namespace // We validiated chunk as at least sizeof(PCMWAVEFORMAT) above break; - default: + default: { + if (fmtChunk->size < sizeof(WAVEFORMATEX)) + { + return E_FAIL; + } + + if ((ptr + sizeof(WAVEFORMATEX)) > wavEnd) { - if (fmtChunk->size < sizeof(WAVEFORMATEX)) + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + auto wfx = reinterpret_cast(ptr); + + if (fmtChunk->size < (sizeof(WAVEFORMATEX) + wfx->cbSize)) + { + return E_FAIL; + } + + if ((ptr + (sizeof(WAVEFORMATEX) + wfx->cbSize)) > wavEnd) + { + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + switch (wfx->wFormatTag) + { + case WAVE_FORMAT_WMAUDIO2: + case WAVE_FORMAT_WMAUDIO3: dpds = true; break; + + case 0x166 /*WAVE_FORMAT_XMA2*/: // XMA2 is supported by Xbox One & Xbox Series X|S + if ((fmtChunk->size < SIZEOF_XMA2WAVEFORMATEX) || (wfx->cbSize < (SIZEOF_XMA2WAVEFORMATEX - sizeof(WAVEFORMATEX)))) { return E_FAIL; } - if ((ptr + sizeof(WAVEFORMATEX)) > wavEnd) + if ((ptr + SIZEOF_XMA2WAVEFORMATEX) > wavEnd) { return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } - auto wfx = reinterpret_cast(ptr); + seek = true; + break; - if (fmtChunk->size < (sizeof(WAVEFORMATEX) + wfx->cbSize)) + case WAVE_FORMAT_ADPCM: + if ((fmtChunk->size < (sizeof(WAVEFORMATEX) + MSADPCM_FORMAT_EXTRA_BYTES)) || (wfx->cbSize < MSADPCM_FORMAT_EXTRA_BYTES)) { return E_FAIL; } - if ((ptr + (sizeof(WAVEFORMATEX) + wfx->cbSize)) > wavEnd) + if ((ptr + sizeof(WAVEFORMATEX) + MSADPCM_FORMAT_EXTRA_BYTES) > wavEnd) { return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } + break; - switch (wfx->wFormatTag) + case WAVE_FORMAT_EXTENSIBLE: + if ((fmtChunk->size < sizeof(WAVEFORMATEXTENSIBLE)) + || (wfx->cbSize < (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)))) { - case WAVE_FORMAT_WMAUDIO2: - case WAVE_FORMAT_WMAUDIO3: - dpds = true; - break; - - case 0x166 /*WAVE_FORMAT_XMA2*/: // XMA2 is supported by Xbox One & Xbox Series X|S - if ((fmtChunk->size < SIZEOF_XMA2WAVEFORMATEX) || (wfx->cbSize < (SIZEOF_XMA2WAVEFORMATEX - sizeof(WAVEFORMATEX)))) - { - return E_FAIL; - } + return E_FAIL; + } + else + { + static const GUID s_wfexBase = { 0x00000000, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 } }; - if ((ptr + SIZEOF_XMA2WAVEFORMATEX) > wavEnd) + if ((ptr + sizeof(WAVEFORMATEXTENSIBLE)) > wavEnd) { return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } - seek = true; - break; + auto wfex = reinterpret_cast(ptr); - case WAVE_FORMAT_ADPCM: - if ((fmtChunk->size < (sizeof(WAVEFORMATEX) + MSADPCM_FORMAT_EXTRA_BYTES)) || (wfx->cbSize < MSADPCM_FORMAT_EXTRA_BYTES)) + if (memcmp(reinterpret_cast(&wfex->SubFormat) + sizeof(DWORD), + reinterpret_cast(&s_wfexBase) + sizeof(DWORD), + sizeof(GUID) - sizeof(DWORD)) + != 0) { - return E_FAIL; + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } - if ((ptr + sizeof(WAVEFORMATEX) + MSADPCM_FORMAT_EXTRA_BYTES) > wavEnd) + switch (wfex->SubFormat.Data1) { - return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); - } - break; - - case WAVE_FORMAT_EXTENSIBLE: - if ((fmtChunk->size < sizeof(WAVEFORMATEXTENSIBLE)) || (wfx->cbSize < (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)))) - { - return E_FAIL; - } - else - { - static const GUID s_wfexBase = { 0x00000000, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 } }; - - if ((ptr + sizeof(WAVEFORMATEXTENSIBLE)) > wavEnd) - { - return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); - } - - auto wfex = reinterpret_cast(ptr); - - if (memcmp(reinterpret_cast(&wfex->SubFormat) + sizeof(DWORD), - reinterpret_cast(&s_wfexBase) + sizeof(DWORD), sizeof(GUID) - sizeof(DWORD)) != 0) - { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); - } - - switch (wfex->SubFormat.Data1) - { - case WAVE_FORMAT_PCM: - case WAVE_FORMAT_IEEE_FLOAT: - break; + case WAVE_FORMAT_PCM: + case WAVE_FORMAT_IEEE_FLOAT: + break; // MS-ADPCM and XMA2 are not supported as WAVEFORMATEXTENSIBLE - case WAVE_FORMAT_WMAUDIO2: - case WAVE_FORMAT_WMAUDIO3: - dpds = true; - break; - - default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); - } + case WAVE_FORMAT_WMAUDIO2: + case WAVE_FORMAT_WMAUDIO3: dpds = true; break; + default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } - break; - - default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } + break; + + default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } + } // Locate 'data' ptr = reinterpret_cast(riffHeader) + sizeof(RIFFChunkHeader); @@ -349,19 +340,17 @@ namespace return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } - *pwfx = reinterpret_cast(wf); - *pdata = ptr; + *pwfx = reinterpret_cast(wf); + *pdata = ptr; *dataSize = dataChunk->size; return S_OK; } - //--------------------------------------------------------------------------------- - HRESULT WaveFindLoopInfo( - _In_reads_bytes_(wavDataSize) const uint8_t* wavData, - _In_ size_t wavDataSize, - _Out_ uint32_t* pLoopStart, - _Out_ uint32_t* pLoopLength) noexcept + HRESULT WaveFindLoopInfo(_In_reads_bytes_(wavDataSize) const uint8_t* wavData, + _In_ size_t wavDataSize, + _Out_ uint32_t* pLoopStart, + _Out_ uint32_t* pLoopLength) noexcept { if (!wavData || !pLoopStart || !pLoopLength) return E_POINTER; @@ -371,7 +360,7 @@ namespace return E_FAIL; } - *pLoopStart = 0; + *pLoopStart = 0; *pLoopLength = 0; const uint8_t* wavEnd = wavData + wavDataSize; @@ -423,7 +412,7 @@ namespace if ((loops[j].loopType == DLSLoop::LOOP_TYPE_FORWARD || loops[j].loopType == DLSLoop::LOOP_TYPE_RELEASE)) { // Return 'forward' loop - *pLoopStart = loops[j].loopStart; + *pLoopStart = loops[j].loopStart; *pLoopLength = loops[j].loopLength; return S_OK; } @@ -454,7 +443,7 @@ namespace if (loops[j].type == MIDILoop::LOOP_TYPE_FORWARD) { // Return 'forward' loop - *pLoopStart = loops[j].start; + *pLoopStart = loops[j].start; *pLoopLength = loops[j].end - loops[j].start + 1; return S_OK; } @@ -466,14 +455,12 @@ namespace return S_OK; } - //--------------------------------------------------------------------------------- - HRESULT WaveFindTable( - _In_reads_bytes_(wavDataSize) const uint8_t* wavData, - _In_ size_t wavDataSize, - _In_ uint32_t tag, - _Outptr_result_maybenull_ const uint32_t** pData, - _Out_ uint32_t* dataCount) noexcept + HRESULT WaveFindTable(_In_reads_bytes_(wavDataSize) const uint8_t* wavData, + _In_ size_t wavDataSize, + _In_ uint32_t tag, + _Outptr_result_maybenull_ const uint32_t** pData, + _Out_ uint32_t* dataCount) noexcept { if (!wavData || !pData || !dataCount) return E_POINTER; @@ -483,7 +470,7 @@ namespace return E_FAIL; } - *pData = nullptr; + *pData = nullptr; *dataCount = 0; const uint8_t* wavEnd = wavData + wavDataSize; @@ -522,28 +509,22 @@ namespace return E_FAIL; } - *pData = reinterpret_cast(ptr); + *pData = reinterpret_cast(ptr); *dataCount = tableChunk->size / 4; } return S_OK; } - //--------------------------------------------------------------------------------- - HRESULT LoadAudioFromFile( - _In_z_ const wchar_t* szFileName, - _Inout_ std::unique_ptr& wavData, - _Out_ DWORD* bytesRead) noexcept + HRESULT + LoadAudioFromFile(_In_z_ const wchar_t* szFileName, _Inout_ std::unique_ptr& wavData, _Out_ DWORD* bytesRead) noexcept { if (!szFileName) return E_INVALIDARG; // open the file - ScopedHandle hFile(safe_handle(CreateFile2( - szFileName, - GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, - nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(szFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); if (!hFile) { return HRESULT_FROM_WIN32(GetLastError()); @@ -576,33 +557,26 @@ namespace } // read the data in - if (!ReadFile(hFile.get(), - wavData.get(), - fileInfo.EndOfFile.LowPart, - bytesRead, - nullptr - )) + if (!ReadFile(hFile.get(), wavData.get(), fileInfo.EndOfFile.LowPart, bytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } return (*bytesRead < fileInfo.EndOfFile.LowPart) ? E_FAIL : S_OK; } -} +} // namespace //------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWAVAudioInMemory( - const uint8_t* wavData, - size_t wavDataSize, - const WAVEFORMATEX** wfx, - const uint8_t** startAudio, - uint32_t* audioBytes) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWAVAudioInMemory(const uint8_t* wavData, + size_t wavDataSize, + const WAVEFORMATEX** wfx, + const uint8_t** startAudio, + uint32_t* audioBytes) noexcept { if (!wavData || !wfx || !startAudio || !audioBytes) return E_INVALIDARG; - *wfx = nullptr; + *wfx = nullptr; *startAudio = nullptr; *audioBytes = 0; @@ -612,7 +586,7 @@ HRESULT DirectX::LoadWAVAudioInMemory( return E_FAIL; } - bool dpds, seek; + bool dpds, seek; HRESULT hr = WaveFindFormatAndData(wavData, wavDataSize, wfx, startAudio, audioBytes, dpds, seek); if (FAILED(hr)) return hr; @@ -620,25 +594,22 @@ HRESULT DirectX::LoadWAVAudioInMemory( return (dpds || seek) ? E_FAIL : S_OK; } - //------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWAVAudioFromFile( - const wchar_t* szFileName, - std::unique_ptr& wavData, - const WAVEFORMATEX** wfx, - const uint8_t** startAudio, - uint32_t* audioBytes) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWAVAudioFromFile(const wchar_t* szFileName, + std::unique_ptr& wavData, + const WAVEFORMATEX** wfx, + const uint8_t** startAudio, + uint32_t* audioBytes) noexcept { if (!szFileName || !wfx || !startAudio || !audioBytes) return E_INVALIDARG; - *wfx = nullptr; + *wfx = nullptr; *startAudio = nullptr; *audioBytes = 0; - DWORD bytesRead = 0; - HRESULT hr = LoadAudioFromFile(szFileName, wavData, &bytesRead); + DWORD bytesRead = 0; + HRESULT hr = LoadAudioFromFile(szFileName, wavData, &bytesRead); if (FAILED(hr)) { return hr; @@ -652,13 +623,10 @@ HRESULT DirectX::LoadWAVAudioFromFile( return (dpds || seek) ? E_FAIL : S_OK; } - //------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWAVAudioInMemoryEx( - const uint8_t* wavData, - size_t wavDataSize, - DirectX::WAVData& result) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWAVAudioInMemoryEx(const uint8_t* wavData, + size_t wavDataSize, + DirectX::WAVData& result) noexcept { if (!wavData) return E_INVALIDARG; @@ -671,7 +639,7 @@ HRESULT DirectX::LoadWAVAudioInMemoryEx( return E_FAIL; } - bool dpds, seek; + bool dpds, seek; HRESULT hr = WaveFindFormatAndData(wavData, wavDataSize, &result.wfx, &result.startAudio, &result.audioBytes, dpds, seek); if (FAILED(hr)) return hr; @@ -696,21 +664,18 @@ HRESULT DirectX::LoadWAVAudioInMemoryEx( return S_OK; } - //------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWAVAudioFromFileEx( - const wchar_t* szFileName, - std::unique_ptr& wavData, - DirectX::WAVData& result) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWAVAudioFromFileEx(const wchar_t* szFileName, + std::unique_ptr& wavData, + DirectX::WAVData& result) noexcept { if (!szFileName) return E_INVALIDARG; memset(&result, 0, sizeof(result)); - DWORD bytesRead = 0; - HRESULT hr = LoadAudioFromFile(szFileName, wavData, &bytesRead); + DWORD bytesRead = 0; + HRESULT hr = LoadAudioFromFile(szFileName, wavData, &bytesRead); if (FAILED(hr)) { return hr; diff --git a/Audio/WAVFileReader.h b/Audio/WAVFileReader.h index df386f25..1583f2aa 100644 --- a/Audio/WAVFileReader.h +++ b/Audio/WAVFileReader.h @@ -18,41 +18,34 @@ #include #include - namespace DirectX { - HRESULT LoadWAVAudioInMemory( - _In_reads_bytes_(wavDataSize) const uint8_t* wavData, - _In_ size_t wavDataSize, - _Outptr_ const WAVEFORMATEX** wfx, - _Outptr_ const uint8_t** startAudio, - _Out_ uint32_t* audioBytes) noexcept; - - HRESULT LoadWAVAudioFromFile( - _In_z_ const wchar_t* szFileName, + HRESULT LoadWAVAudioInMemory(_In_reads_bytes_(wavDataSize) const uint8_t* wavData, + _In_ size_t wavDataSize, + _Outptr_ const WAVEFORMATEX** wfx, + _Outptr_ const uint8_t** startAudio, + _Out_ uint32_t* audioBytes) noexcept; + + HRESULT LoadWAVAudioFromFile(_In_z_ const wchar_t* szFileName, _Inout_ std::unique_ptr& wavData, - _Outptr_ const WAVEFORMATEX** wfx, - _Outptr_ const uint8_t** startAudio, - _Out_ uint32_t* audioBytes) noexcept; + _Outptr_ const WAVEFORMATEX** wfx, + _Outptr_ const uint8_t** startAudio, + _Out_ uint32_t* audioBytes) noexcept; struct WAVData { const WAVEFORMATEX* wfx; - const uint8_t* startAudio; - uint32_t audioBytes; - uint32_t loopStart; - uint32_t loopLength; - const uint32_t* seek; // Note: XMA Seek data is Big-Endian - uint32_t seekCount; + const uint8_t* startAudio; + uint32_t audioBytes; + uint32_t loopStart; + uint32_t loopLength; + const uint32_t* seek; // Note: XMA Seek data is Big-Endian + uint32_t seekCount; }; - HRESULT LoadWAVAudioInMemoryEx( - _In_reads_bytes_(wavDataSize) const uint8_t* wavData, - _In_ size_t wavDataSize, - _Out_ WAVData& result) noexcept; + HRESULT + LoadWAVAudioInMemoryEx(_In_reads_bytes_(wavDataSize) const uint8_t* wavData, _In_ size_t wavDataSize, _Out_ WAVData& result) noexcept; - HRESULT LoadWAVAudioFromFileEx( - _In_z_ const wchar_t* szFileName, - _Inout_ std::unique_ptr& wavData, - _Out_ WAVData& result) noexcept; -} + HRESULT + LoadWAVAudioFromFileEx(_In_z_ const wchar_t* szFileName, _Inout_ std::unique_ptr& wavData, _Out_ WAVData& result) noexcept; +} // namespace DirectX diff --git a/Audio/WaveBank.cpp b/Audio/WaveBank.cpp index 03dd4c1a..46196fe8 100644 --- a/Audio/WaveBank.cpp +++ b/Audio/WaveBank.cpp @@ -18,7 +18,6 @@ using namespace DirectX; - //====================================================================================== // WaveBank //====================================================================================== @@ -27,11 +26,11 @@ using namespace DirectX; class WaveBank::Impl : public IVoiceNotify { public: - explicit Impl(_In_ AudioEngine* engine) : - mEngine(engine), - mOneShots(0), - mPrepared(false), - mStreaming(false) + explicit Impl(_In_ AudioEngine* engine) + : mEngine(engine), + mOneShots(0), + mPrepared(false), + mStreaming(false) { if (!engine) throw std::invalid_argument("AudioEngine is required"); @@ -39,18 +38,17 @@ class WaveBank::Impl : public IVoiceNotify mEngine->RegisterNotify(this, false); } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() override { if (!mInstances.empty()) { - DebugTrace("WARNING: Destroying WaveBank \"%hs\" with %zu outstanding instances\n", - mReader.BankName(), mInstances.size()); + DebugTrace("WARNING: Destroying WaveBank \"%hs\" with %zu outstanding instances\n", mReader.BankName(), mInstances.size()); for (auto it : mInstances) { @@ -63,8 +61,7 @@ class WaveBank::Impl : public IVoiceNotify if (mOneShots > 0) { - DebugTrace("WARNING: Destroying WaveBank \"%hs\" with %u outstanding one shot effects\n", - mReader.BankName(), mOneShots); + DebugTrace("WARNING: Destroying WaveBank \"%hs\" with %u outstanding one shot effects\n", mReader.BankName(), mOneShots); } if (mEngine) @@ -79,15 +76,9 @@ class WaveBank::Impl : public IVoiceNotify void Play(unsigned int index, float volume, float pitch, float pan); // IVoiceNotify - void __cdecl OnBufferEnd() override - { - InterlockedDecrement(&mOneShots); - } + void __cdecl OnBufferEnd() override { InterlockedDecrement(&mOneShots); } - void __cdecl OnCriticalError() override - { - mOneShots = 0; - } + void __cdecl OnCriticalError() override { mOneShots = 0; } void __cdecl OnReset() override { @@ -102,7 +93,7 @@ class WaveBank::Impl : public IVoiceNotify void __cdecl OnDestroyEngine() noexcept override { - mEngine = nullptr; + mEngine = nullptr; mOneShots = 0; } @@ -119,27 +110,24 @@ class WaveBank::Impl : public IVoiceNotify { stats.audioBytes += mReader.BankAudioSize(); - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 if (mReader.HasXMA()) stats.xmaAudioBytes += mReader.BankAudioSize(); - #endif +#endif } } - void __cdecl OnDestroyParent() noexcept override - {} + void __cdecl OnDestroyParent() noexcept override {} - AudioEngine* mEngine; - std::list mInstances; - WaveBankReader mReader; - uint32_t mOneShots; - bool mPrepared; - bool mStreaming; + AudioEngine* mEngine; + std::list mInstances; + WaveBankReader mReader; + uint32_t mOneShots; + bool mPrepared; + bool mStreaming; }; - -_Use_decl_annotations_ -HRESULT WaveBank::Impl::Initialize(const AudioEngine* engine, const wchar_t* wbFileName) noexcept +_Use_decl_annotations_ HRESULT WaveBank::Impl::Initialize(const AudioEngine* engine, const wchar_t* wbFileName) noexcept { if (!engine || !wbFileName) return E_INVALIDARG; @@ -153,7 +141,6 @@ HRESULT WaveBank::Impl::Initialize(const AudioEngine* engine, const wchar_t* wbF return S_OK; } - void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float pan) { assert(volume >= -XAUDIO2_MAX_VOLUME_LEVEL && volume <= XAUDIO2_MAX_VOLUME_LEVEL); @@ -168,8 +155,7 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p if (index >= mReader.Count()) { - DebugTrace("WARNING: Index %u not found in wave bank with only %u entries, one-shot not triggered\n", - index, mReader.Count()); + DebugTrace("WARNING: Index %u not found in wave bank with only %u entries, one-shot not triggered\n", index, mReader.Count()); return; } @@ -179,9 +165,9 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p mPrepared = true; } - char wfxbuff[64] = {}; - auto wfx = reinterpret_cast(wfxbuff); - HRESULT hr = mReader.GetFormat(index, wfx, sizeof(wfxbuff)); + char wfxbuff[64] = {}; + auto wfx = reinterpret_cast(wfxbuff); + HRESULT hr = mReader.GetFormat(index, wfx, sizeof(wfxbuff)); ThrowIfFailed(hr); IXAudio2SourceVoice* voice = nullptr; @@ -218,14 +204,14 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p ThrowIfFailed(hr); XAUDIO2_BUFFER buffer = {}; - hr = mReader.GetWaveData(index, &buffer.pAudioData, buffer.AudioBytes); + hr = mReader.GetWaveData(index, &buffer.pAudioData, buffer.AudioBytes); ThrowIfFailed(hr); WaveBankReader::Metadata metadata; hr = mReader.GetMetadata(index, metadata); ThrowIfFailed(hr); - buffer.Flags = XAUDIO2_END_OF_STREAM; + buffer.Flags = XAUDIO2_END_OF_STREAM; buffer.pContext = this; #ifdef DIRECTX_ENABLE_XWMA @@ -241,7 +227,7 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p hr = voice->SubmitSourceBuffer(&buffer, &wmaBuffer); } else - #endif // xWMA +#endif // xWMA { hr = voice->SubmitSourceBuffer(&buffer, nullptr); } @@ -249,40 +235,41 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p { DebugTrace("ERROR: WaveBank failed (%08X) when submitting buffer:\n", static_cast(hr)); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %u bytes\n", - wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nSamplesPerSec, metadata.lengthBytes); + wfx->wFormatTag, + wfx->nChannels, + wfx->wBitsPerSample, + wfx->nSamplesPerSec, + metadata.lengthBytes); throw std::runtime_error("SubmitSourceBuffer"); } InterlockedIncrement(&mOneShots); } - //-------------------------------------------------------------------------------------- // WaveBank //-------------------------------------------------------------------------------------- // Public constructors. -_Use_decl_annotations_ -WaveBank::WaveBank(AudioEngine* engine, const wchar_t* wbFileName) +_Use_decl_annotations_ WaveBank::WaveBank(AudioEngine* engine, const wchar_t* wbFileName) : pImpl(std::make_unique(engine)) { HRESULT hr = pImpl->Initialize(engine, wbFileName); if (FAILED(hr)) { - DebugTrace("ERROR: WaveBank failed (%08X) to intialize from .xwb file \"%ls\"\n", - static_cast(hr), wbFileName); + DebugTrace("ERROR: WaveBank failed (%08X) to intialize from .xwb file \"%ls\"\n", static_cast(hr), wbFileName); throw std::runtime_error("WaveBank"); } DebugTrace("INFO: WaveBank \"%hs\" with %u entries loaded from .xwb file \"%ls\"\n", - pImpl->mReader.BankName(), pImpl->mReader.Count(), wbFileName); + pImpl->mReader.BankName(), + pImpl->mReader.Count(), + wbFileName); } - -WaveBank::WaveBank(WaveBank&&) noexcept = default; -WaveBank& WaveBank::operator= (WaveBank&&) noexcept = default; -WaveBank::~WaveBank() = default; - +WaveBank::WaveBank(WaveBank&&) noexcept = default; +WaveBank& WaveBank::operator=(WaveBank&&) noexcept = default; +WaveBank::~WaveBank() = default; // Public methods (one-shots) void WaveBank::Play(unsigned int index) @@ -290,13 +277,11 @@ void WaveBank::Play(unsigned int index) pImpl->Play(index, 1.f, 0.f, 0.f); } - void WaveBank::Play(unsigned int index, float volume, float pitch, float pan) { pImpl->Play(index, volume, pitch, pan); } - void WaveBank::Play(_In_z_ const char* name) { const unsigned int index = pImpl->mReader.Find(name); @@ -309,7 +294,6 @@ void WaveBank::Play(_In_z_ const char* name) pImpl->Play(index, 1.f, 0.f, 0.f); } - void WaveBank::Play(_In_z_ const char* name, float volume, float pitch, float pan) { const unsigned int index = pImpl->mReader.Find(name); @@ -322,7 +306,6 @@ void WaveBank::Play(_In_z_ const char* name, float volume, float pitch, float pa pImpl->Play(index, volume, pitch, pan); } - // Public methods (sound effect instance) std::unique_ptr WaveBank::CreateInstance(unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags) { @@ -352,7 +335,6 @@ std::unique_ptr WaveBank::CreateInstance(unsigned int index return std::unique_ptr(effect); } - std::unique_ptr WaveBank::CreateInstance(_In_z_ const char* name, SOUND_EFFECT_INSTANCE_FLAGS flags) { const unsigned int index = pImpl->mReader.Find(name); @@ -365,7 +347,6 @@ std::unique_ptr WaveBank::CreateInstance(_In_z_ const char* return CreateInstance(index, flags); } - // Public methods (sound stream instance) std::unique_ptr WaveBank::CreateStreamInstance(unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags) { @@ -395,7 +376,6 @@ std::unique_ptr WaveBank::CreateStreamInstance(unsigned int return std::unique_ptr(effect); } - std::unique_ptr WaveBank::CreateStreamInstance(_In_z_ const char* name, SOUND_EFFECT_INSTANCE_FLAGS flags) { const unsigned int index = pImpl->mReader.Find(name); @@ -408,7 +388,6 @@ std::unique_ptr WaveBank::CreateStreamInstance(_In_z_ const return CreateStreamInstance(index, flags); } - void WaveBank::UnregisterInstance(_In_ IVoiceNotify* instance) { auto it = std::find(pImpl->mInstances.begin(), pImpl->mInstances.end(), instance); @@ -418,7 +397,6 @@ void WaveBank::UnregisterInstance(_In_ IVoiceNotify* instance) pImpl->mInstances.erase(it); } - // Public accessors. bool WaveBank::IsPrepared() const noexcept { @@ -432,61 +410,55 @@ bool WaveBank::IsPrepared() const noexcept return true; } - bool WaveBank::IsInUse() const noexcept { return (pImpl->mOneShots > 0) || !pImpl->mInstances.empty(); } - bool WaveBank::IsStreamingBank() const noexcept { return pImpl->mReader.IsStreamingBank(); } - bool WaveBank::IsAdvancedFormat() const noexcept { return (pImpl->mReader.GetWaveAlignment() == 4096); } - size_t WaveBank::GetSampleSizeInBytes(unsigned int index) const noexcept { if (index >= pImpl->mReader.Count()) return 0; WaveBankReader::Metadata metadata; - HRESULT hr = pImpl->mReader.GetMetadata(index, metadata); + HRESULT hr = pImpl->mReader.GetMetadata(index, metadata); if (FAILED(hr)) return 0; return metadata.lengthBytes; } - size_t WaveBank::GetSampleDuration(unsigned int index) const noexcept { if (index >= pImpl->mReader.Count()) return 0; WaveBankReader::Metadata metadata; - HRESULT hr = pImpl->mReader.GetMetadata(index, metadata); + HRESULT hr = pImpl->mReader.GetMetadata(index, metadata); if (FAILED(hr)) return 0; return metadata.duration; } - size_t WaveBank::GetSampleDurationMS(unsigned int index) const noexcept { if (index >= pImpl->mReader.Count()) return 0; - char buff[64] = {}; - auto wfx = reinterpret_cast(buff); - HRESULT hr = pImpl->mReader.GetFormat(index, wfx, sizeof(buff)); + char buff[64] = {}; + auto wfx = reinterpret_cast(buff); + HRESULT hr = pImpl->mReader.GetFormat(index, wfx, sizeof(buff)); if (FAILED(hr)) return 0; @@ -498,9 +470,7 @@ size_t WaveBank::GetSampleDurationMS(unsigned int index) const noexcept return static_cast((uint64_t(metadata.duration) * 1000) / wfx->nSamplesPerSec); } - -_Use_decl_annotations_ -const WAVEFORMATEX* WaveBank::GetFormat(unsigned int index, WAVEFORMATEX* wfx, size_t maxsize) const noexcept +_Use_decl_annotations_ const WAVEFORMATEX* WaveBank::GetFormat(unsigned int index, WAVEFORMATEX* wfx, size_t maxsize) const noexcept { if (index >= pImpl->mReader.Count()) return nullptr; @@ -512,18 +482,14 @@ const WAVEFORMATEX* WaveBank::GetFormat(unsigned int index, WAVEFORMATEX* wfx, s return wfx; } - -_Use_decl_annotations_ -int WaveBank::Find(const char* name) const +_Use_decl_annotations_ int WaveBank::Find(const char* name) const { return static_cast(pImpl->mReader.Find(name)); } - #ifdef DIRECTX_ENABLE_XWMA -_Use_decl_annotations_ -bool WaveBank::FillSubmitBuffer(unsigned int index, XAUDIO2_BUFFER& buffer, XAUDIO2_BUFFER_WMA& wmaBuffer) const +_Use_decl_annotations_ bool WaveBank::FillSubmitBuffer(unsigned int index, XAUDIO2_BUFFER& buffer, XAUDIO2_BUFFER_WMA& wmaBuffer) const { memset(&buffer, 0, sizeof(buffer)); memset(&wmaBuffer, 0, sizeof(wmaBuffer)); @@ -535,7 +501,7 @@ bool WaveBank::FillSubmitBuffer(unsigned int index, XAUDIO2_BUFFER& buffer, XAUD hr = pImpl->mReader.GetMetadata(index, metadata); ThrowIfFailed(hr); - buffer.LoopBegin = metadata.loopStart; + buffer.LoopBegin = metadata.loopStart; buffer.LoopLength = metadata.loopLength; uint32_t tag; @@ -547,8 +513,7 @@ bool WaveBank::FillSubmitBuffer(unsigned int index, XAUDIO2_BUFFER& buffer, XAUD #else // !xWMA -_Use_decl_annotations_ -void WaveBank::FillSubmitBuffer(unsigned int index, XAUDIO2_BUFFER& buffer) const +_Use_decl_annotations_ void WaveBank::FillSubmitBuffer(unsigned int index, XAUDIO2_BUFFER& buffer) const { memset(&buffer, 0, sizeof(buffer)); @@ -559,13 +524,12 @@ void WaveBank::FillSubmitBuffer(unsigned int index, XAUDIO2_BUFFER& buffer) cons hr = pImpl->mReader.GetMetadata(index, metadata); ThrowIfFailed(hr); - buffer.LoopBegin = metadata.loopStart; + buffer.LoopBegin = metadata.loopStart; buffer.LoopLength = metadata.loopLength; } #endif - HANDLE WaveBank::GetAsyncHandle() const noexcept { if (pImpl) @@ -576,9 +540,7 @@ HANDLE WaveBank::GetAsyncHandle() const noexcept return nullptr; } - -_Use_decl_annotations_ -bool WaveBank::GetPrivateData(unsigned int index, void* data, size_t datasize) +_Use_decl_annotations_ bool WaveBank::GetPrivateData(unsigned int index, void* data, size_t datasize) { if (index >= pImpl->mReader.Count()) return false; @@ -588,31 +550,26 @@ bool WaveBank::GetPrivateData(unsigned int index, void* data, size_t datasize) switch (datasize) { - case sizeof(WaveBankReader::Metadata) : - { - auto ptr = reinterpret_cast(data); - return SUCCEEDED(pImpl->mReader.GetMetadata(index, *ptr)); - } + case sizeof(WaveBankReader::Metadata): { + auto ptr = reinterpret_cast(data); + return SUCCEEDED(pImpl->mReader.GetMetadata(index, *ptr)); + } - case sizeof(WaveBankSeekData) : - { - auto ptr = reinterpret_cast(data); - return SUCCEEDED(pImpl->mReader.GetSeekTable(index, &ptr->seekTable, ptr->seekCount, ptr->tag)); - } + case sizeof(WaveBankSeekData): { + auto ptr = reinterpret_cast(data); + return SUCCEEDED(pImpl->mReader.GetSeekTable(index, &ptr->seekTable, ptr->seekCount, ptr->tag)); + } - default: - return false; + default: return false; } } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -_Use_decl_annotations_ -WaveBank::WaveBank(AudioEngine* engine, const __wchar_t* wbFileName) : - WaveBank(engine, reinterpret_cast(wbFileName)) +_Use_decl_annotations_ WaveBank::WaveBank(AudioEngine* engine, const __wchar_t* wbFileName) + : WaveBank(engine, reinterpret_cast(wbFileName)) {} #endif // !_NATIVE_WCHAR_T_DEFINED diff --git a/Audio/WaveBankReader.cpp b/Audio/WaveBankReader.cpp index f184d6fd..6661b53a 100644 --- a/Audio/WaveBankReader.cpp +++ b/Audio/WaveBankReader.cpp @@ -25,28 +25,27 @@ #include #endif - namespace { #pragma pack(push, 1) constexpr uint16_t MSADPCM_FORMAT_EXTRA_BYTES = 32; - constexpr uint16_t MSADPCM_NUM_COEFFICIENTS = 7; + constexpr uint16_t MSADPCM_NUM_COEFFICIENTS = 7; constexpr size_t DVD_SECTOR_SIZE = 2048; - constexpr size_t DVD_BLOCK_SIZE = DVD_SECTOR_SIZE * 16; + constexpr size_t DVD_BLOCK_SIZE = DVD_SECTOR_SIZE * 16; constexpr size_t ALIGNMENT_MIN = 4; constexpr size_t ALIGNMENT_MAX = 0xFFFF; constexpr size_t ALIGNMENT_DVD = DVD_SECTOR_SIZE; - constexpr size_t MAX_DATA_SEGMENT_SIZE = 0xFFFFFFFF; + constexpr size_t MAX_DATA_SEGMENT_SIZE = 0xFFFFFFFF; constexpr size_t MAX_COMPACT_DATA_SEGMENT_SIZE = 0x001FFFFF; struct REGION { - uint32_t dwOffset; // Region offset, in bytes. - uint32_t dwLength; // Region length, in bytes. + uint32_t dwOffset; // Region offset, in bytes. + uint32_t dwLength; // Region length, in bytes. void BigEndian() noexcept { @@ -57,42 +56,42 @@ namespace struct SAMPLEREGION { - uint32_t dwStartSample; // Start sample for the region. - uint32_t dwTotalSamples; // Region length in samples. + uint32_t dwStartSample; // Start sample for the region. + uint32_t dwTotalSamples; // Region length in samples. void BigEndian() noexcept { - dwStartSample = _byteswap_ulong(dwStartSample); + dwStartSample = _byteswap_ulong(dwStartSample); dwTotalSamples = _byteswap_ulong(dwTotalSamples); } }; struct HEADER { - static constexpr uint32_t SIGNATURE = MAKEFOURCC('W', 'B', 'N', 'D'); + static constexpr uint32_t SIGNATURE = MAKEFOURCC('W', 'B', 'N', 'D'); static constexpr uint32_t BE_SIGNATURE = MAKEFOURCC('D', 'N', 'B', 'W'); - static constexpr uint32_t VERSION = 44; + static constexpr uint32_t VERSION = 44; enum SEGIDX { - SEGIDX_BANKDATA = 0, // Bank data - SEGIDX_ENTRYMETADATA, // Entry meta-data - SEGIDX_SEEKTABLES, // Storage for seek tables for the encoded waves. - SEGIDX_ENTRYNAMES, // Entry friendly names - SEGIDX_ENTRYWAVEDATA, // Entry wave data + SEGIDX_BANKDATA = 0, // Bank data + SEGIDX_ENTRYMETADATA, // Entry meta-data + SEGIDX_SEEKTABLES, // Storage for seek tables for the encoded waves. + SEGIDX_ENTRYNAMES, // Entry friendly names + SEGIDX_ENTRYWAVEDATA, // Entry wave data SEGIDX_COUNT }; - uint32_t dwSignature; // File signature - uint32_t dwVersion; // Version of the tool that created the file - uint32_t dwHeaderVersion; // Version of the file format - REGION Segments[SEGIDX_COUNT]; // Segment lookup table + uint32_t dwSignature; // File signature + uint32_t dwVersion; // Version of the tool that created the file + uint32_t dwHeaderVersion; // Version of the file format + REGION Segments[SEGIDX_COUNT]; // Segment lookup table void BigEndian() noexcept { // Leave dwSignature alone as indicator of BE vs. LE - dwVersion = _byteswap_ulong(dwVersion); + dwVersion = _byteswap_ulong(dwVersion); dwHeaderVersion = _byteswap_ulong(dwHeaderVersion); for (size_t j = 0; j < SEGIDX_COUNT; ++j) { @@ -102,36 +101,33 @@ namespace }; #ifdef _MSC_VER -#pragma warning( disable : 4201 4203 ) +#pragma warning(disable : 4201 4203) #endif union MINIWAVEFORMAT { - static constexpr uint32_t TAG_PCM = 0x0; - static constexpr uint32_t TAG_XMA = 0x1; + static constexpr uint32_t TAG_PCM = 0x0; + static constexpr uint32_t TAG_XMA = 0x1; static constexpr uint32_t TAG_ADPCM = 0x2; - static constexpr uint32_t TAG_WMA = 0x3; + static constexpr uint32_t TAG_WMA = 0x3; - static constexpr uint32_t BITDEPTH_8 = 0x0; // PCM only + static constexpr uint32_t BITDEPTH_8 = 0x0; // PCM only static constexpr uint32_t BITDEPTH_16 = 0x1; // PCM only static constexpr size_t ADPCM_BLOCKALIGN_CONVERSION_OFFSET = 22; struct { - uint32_t wFormatTag : 2; // Format tag - uint32_t nChannels : 3; // Channel count (1 - 6) - uint32_t nSamplesPerSec : 18; // Sampling rate - uint32_t wBlockAlign : 8; // Block alignment. For WMA, lower 6 bits block alignment index, upper 2 bits bytes-per-second index. - uint32_t wBitsPerSample : 1; // Bits per sample (8 vs. 16, PCM only); WMAudio2/WMAudio3 (for WMA) + uint32_t wFormatTag : 2; // Format tag + uint32_t nChannels : 3; // Channel count (1 - 6) + uint32_t nSamplesPerSec : 18; // Sampling rate + uint32_t wBlockAlign : 8; // Block alignment. For WMA, lower 6 bits block alignment index, upper 2 bits bytes-per-second index. + uint32_t wBitsPerSample : 1; // Bits per sample (8 vs. 16, PCM only); WMAudio2/WMAudio3 (for WMA) }; - uint32_t dwValue; + uint32_t dwValue; - void BigEndian() noexcept - { - dwValue = _byteswap_ulong(dwValue); - } + void BigEndian() noexcept { dwValue = _byteswap_ulong(dwValue); } WORD BitsPerSample() const noexcept { @@ -150,46 +146,23 @@ namespace { switch (wFormatTag) { - case TAG_PCM: - return wBlockAlign; + case TAG_PCM: return wBlockAlign; - case TAG_XMA: - return (nChannels * 16 / 8); // XMA_OUTPUT_SAMPLE_BITS = 16 + case TAG_XMA: return (nChannels * 16 / 8); // XMA_OUTPUT_SAMPLE_BITS = 16 - case TAG_ADPCM: - return (wBlockAlign + ADPCM_BLOCKALIGN_CONVERSION_OFFSET) * nChannels; + case TAG_ADPCM: return (wBlockAlign + ADPCM_BLOCKALIGN_CONVERSION_OFFSET) * nChannels; - case TAG_WMA: - { - static const uint32_t aWMABlockAlign[17] = - { - 929, - 1487, - 1280, - 2230, - 8917, - 8192, - 4459, - 5945, - 2304, - 1536, - 1485, - 1008, - 2731, - 4096, - 6827, - 5462, - 1280 - }; - - const uint32_t dwBlockAlignIndex = wBlockAlign & 0x1F; - if (dwBlockAlignIndex < 17) - return aWMABlockAlign[dwBlockAlignIndex]; - } - break; + case TAG_WMA: { + static const uint32_t aWMABlockAlign[17] + = { 929, 1487, 1280, 2230, 8917, 8192, 4459, 5945, 2304, 1536, 1485, 1008, 2731, 4096, 6827, 5462, 1280 }; - default: - break; + const uint32_t dwBlockAlignIndex = wBlockAlign & 0x1F; + if (dwBlockAlignIndex < 17) + return aWMABlockAlign[dwBlockAlignIndex]; + } + break; + + default: break; } return 0; @@ -199,41 +172,27 @@ namespace { switch (wFormatTag) { - case TAG_PCM: - return nSamplesPerSec * wBlockAlign; + case TAG_PCM: return nSamplesPerSec * wBlockAlign; - case TAG_XMA: - return nSamplesPerSec * BlockAlign(); + case TAG_XMA: return nSamplesPerSec * BlockAlign(); - case TAG_ADPCM: - { - const uint32_t blockAlign = BlockAlign(); - const uint32_t samplesPerAdpcmBlock = AdpcmSamplesPerBlock(); - return blockAlign * nSamplesPerSec / samplesPerAdpcmBlock; - } + case TAG_ADPCM: { + const uint32_t blockAlign = BlockAlign(); + const uint32_t samplesPerAdpcmBlock = AdpcmSamplesPerBlock(); + return blockAlign * nSamplesPerSec / samplesPerAdpcmBlock; + } - case TAG_WMA: - { - static const uint32_t aWMAAvgBytesPerSec[7] = - { - 12000, - 24000, - 4000, - 6000, - 8000, - 20000, - 2500 - }; - // bitrate = entry * 8 - - const uint32_t dwBytesPerSecIndex = wBlockAlign >> 5; - if (dwBytesPerSecIndex < 7) - return aWMAAvgBytesPerSec[dwBytesPerSecIndex]; - } - break; + case TAG_WMA: { + static const uint32_t aWMAAvgBytesPerSec[7] = { 12000, 24000, 4000, 6000, 8000, 20000, 2500 }; + // bitrate = entry * 8 - default: - break; + const uint32_t dwBytesPerSecIndex = wBlockAlign >> 5; + if (dwBytesPerSecIndex < 7) + return aWMAAvgBytesPerSec[dwBytesPerSecIndex]; + } + break; + + default: break; } return 0; @@ -245,13 +204,14 @@ namespace return nBlockAlign * 2 / uint32_t(nChannels) - 12; } - void AdpcmFillCoefficientTable(ADPCMWAVEFORMAT *fmt) const noexcept + void AdpcmFillCoefficientTable(ADPCMWAVEFORMAT* fmt) const noexcept { // These are fixed since we are always using MS ADPCM fmt->wNumCoef = MSADPCM_NUM_COEFFICIENTS; - static ADPCMCOEFSET aCoef[7] = { { 256, 0}, {512, -256}, {0,0}, {192,64}, {240,0}, {460, -208}, {392,-232} }; - memcpy(&fmt->aCoef, aCoef, sizeof(aCoef)); // CodeQL [SM01947] Code scanner doesn't understand the 0-length MSVC array extension. MSADPCM_FORMAT_EXTRA_BYTES includes this memory. + static ADPCMCOEFSET aCoef[7] = { { 256, 0 }, { 512, -256 }, { 0, 0 }, { 192, 64 }, { 240, 0 }, { 460, -208 }, { 392, -232 } }; + memcpy(&fmt->aCoef, aCoef, sizeof(aCoef)); // CodeQL [SM01947] Code scanner doesn't understand the 0-length MSVC array + // extension. MSADPCM_FORMAT_EXTRA_BYTES includes this memory. } }; @@ -259,52 +219,52 @@ namespace { static constexpr size_t BANKNAME_LENGTH = 64; - static constexpr uint32_t TYPE_BUFFER = 0x00000000; + static constexpr uint32_t TYPE_BUFFER = 0x00000000; static constexpr uint32_t TYPE_STREAMING = 0x00000001; - static constexpr uint32_t TYPE_MASK = 0x00000001; + static constexpr uint32_t TYPE_MASK = 0x00000001; - static constexpr uint32_t FLAGS_ENTRYNAMES = 0x00010000; - static constexpr uint32_t FLAGS_COMPACT = 0x00020000; + static constexpr uint32_t FLAGS_ENTRYNAMES = 0x00010000; + static constexpr uint32_t FLAGS_COMPACT = 0x00020000; static constexpr uint32_t FLAGS_SYNC_DISABLED = 0x00040000; - static constexpr uint32_t FLAGS_SEEKTABLES = 0x00080000; - static constexpr uint32_t FLAGS_MASK = 0x000F0000; - - uint32_t dwFlags; // Bank flags - uint32_t dwEntryCount; // Number of entries in the bank - char szBankName[BANKNAME_LENGTH]; // Bank friendly name - uint32_t dwEntryMetaDataElementSize; // Size of each entry meta-data element, in bytes - uint32_t dwEntryNameElementSize; // Size of each entry name element, in bytes - uint32_t dwAlignment; // Entry alignment, in bytes - MINIWAVEFORMAT CompactFormat; // Format data for compact bank - FILETIME BuildTime; // Build timestamp + static constexpr uint32_t FLAGS_SEEKTABLES = 0x00080000; + static constexpr uint32_t FLAGS_MASK = 0x000F0000; + + uint32_t dwFlags; // Bank flags + uint32_t dwEntryCount; // Number of entries in the bank + char szBankName[BANKNAME_LENGTH]; // Bank friendly name + uint32_t dwEntryMetaDataElementSize; // Size of each entry meta-data element, in bytes + uint32_t dwEntryNameElementSize; // Size of each entry name element, in bytes + uint32_t dwAlignment; // Entry alignment, in bytes + MINIWAVEFORMAT CompactFormat; // Format data for compact bank + FILETIME BuildTime; // Build timestamp void BigEndian() noexcept { - dwFlags = _byteswap_ulong(dwFlags); - dwEntryCount = _byteswap_ulong(dwEntryCount); + dwFlags = _byteswap_ulong(dwFlags); + dwEntryCount = _byteswap_ulong(dwEntryCount); dwEntryMetaDataElementSize = _byteswap_ulong(dwEntryMetaDataElementSize); - dwEntryNameElementSize = _byteswap_ulong(dwEntryNameElementSize); - dwAlignment = _byteswap_ulong(dwAlignment); + dwEntryNameElementSize = _byteswap_ulong(dwEntryNameElementSize); + dwAlignment = _byteswap_ulong(dwAlignment); CompactFormat.BigEndian(); - BuildTime.dwLowDateTime = _byteswap_ulong(BuildTime.dwLowDateTime); + BuildTime.dwLowDateTime = _byteswap_ulong(BuildTime.dwLowDateTime); BuildTime.dwHighDateTime = _byteswap_ulong(BuildTime.dwHighDateTime); } }; struct ENTRY { - static constexpr uint32_t FLAGS_READAHEAD = 0x00000001; // Enable stream read-ahead - static constexpr uint32_t FLAGS_LOOPCACHE = 0x00000002; // One or more looping sounds use this wave - static constexpr uint32_t FLAGS_REMOVELOOPTAIL = 0x00000004;// Remove data after the end of the loop region - static constexpr uint32_t FLAGS_IGNORELOOP = 0x00000008; // Used internally when the loop region can't be used - static constexpr uint32_t FLAGS_MASK = 0x00000008; + static constexpr uint32_t FLAGS_READAHEAD = 0x00000001; // Enable stream read-ahead + static constexpr uint32_t FLAGS_LOOPCACHE = 0x00000002; // One or more looping sounds use this wave + static constexpr uint32_t FLAGS_REMOVELOOPTAIL = 0x00000004; // Remove data after the end of the loop region + static constexpr uint32_t FLAGS_IGNORELOOP = 0x00000008; // Used internally when the loop region can't be used + static constexpr uint32_t FLAGS_MASK = 0x00000008; union { struct { // Entry flags - uint32_t dwFlags : 4; + uint32_t dwFlags : 4; // Duration of the wave, in units of one sample. // For instance, a ten second long wave sampled @@ -312,14 +272,14 @@ namespace // This value is not affected by the number of // channels, the number of bits per sample, or the // compression format of the wave. - uint32_t Duration : 28; + uint32_t Duration : 28; }; uint32_t dwFlagsAndDuration; }; - MINIWAVEFORMAT Format; // Entry format. - REGION PlayRegion; // Region within the wave data segment that contains this entry. - SAMPLEREGION LoopRegion; // Region within the wave data (in samples) that should loop. + MINIWAVEFORMAT Format; // Entry format. + REGION PlayRegion; // Region within the wave data segment that contains this entry. + SAMPLEREGION LoopRegion; // Region within the wave data (in samples) that should loop. void BigEndian() noexcept { @@ -332,15 +292,17 @@ namespace struct ENTRYCOMPACT { - uint32_t dwOffset : 21; // Data offset, in multiplies of the bank alignment - uint32_t dwLengthDeviation : 11; // Data length deviation, in bytes + uint32_t dwOffset : 21; // Data offset, in multiplies of the bank alignment + uint32_t dwLengthDeviation : 11; // Data length deviation, in bytes - void BigEndian() noexcept - { - *reinterpret_cast(this) = _byteswap_ulong(*reinterpret_cast(this)); - } + void BigEndian() noexcept { *reinterpret_cast(this) = _byteswap_ulong(*reinterpret_cast(this)); } - void ComputeLocations(DWORD& offset, DWORD& length, uint32_t index, const HEADER& header, const BANKDATA& data, const ENTRYCOMPACT* entries) const noexcept + void ComputeLocations(DWORD& offset, + DWORD& length, + uint32_t index, + const HEADER& header, + const BANKDATA& data, + const ENTRYCOMPACT* entries) const noexcept { offset = dwOffset * data.dwAlignment; @@ -358,17 +320,16 @@ namespace { switch (data.CompactFormat.wFormatTag) { - case MINIWAVEFORMAT::TAG_ADPCM: + case MINIWAVEFORMAT::TAG_ADPCM: { + uint32_t duration = (length / data.CompactFormat.BlockAlign()) * data.CompactFormat.AdpcmSamplesPerBlock(); + const uint32_t partial = length % data.CompactFormat.BlockAlign(); + if (partial) { - uint32_t duration = (length / data.CompactFormat.BlockAlign()) * data.CompactFormat.AdpcmSamplesPerBlock(); - const uint32_t partial = length % data.CompactFormat.BlockAlign(); - if (partial) - { - if (partial >= (7u * data.CompactFormat.nChannels)) - duration += (partial * 2 / data.CompactFormat.nChannels - 12); - } - return duration; + if (partial >= (7u * data.CompactFormat.nChannels)) + duration += (partial * 2 / data.CompactFormat.nChannels - 12); } + return duration; + } case MINIWAVEFORMAT::TAG_WMA: if (seekTable) @@ -393,15 +354,16 @@ namespace return 0; default: - return uint32_t((uint64_t(length) * 8) - / (uint64_t(data.CompactFormat.BitsPerSample()) * uint64_t(data.CompactFormat.nChannels))); + return uint32_t( + (uint64_t(length) * 8) / (uint64_t(data.CompactFormat.BitsPerSample()) * uint64_t(data.CompactFormat.nChannels))); } } }; #pragma pack(pop) - inline const uint32_t* FindSeekTable(uint32_t index, _In_opt_ const uint8_t* seekTable, const HEADER& header, const BANKDATA& data) noexcept + inline const uint32_t* + FindSeekTable(uint32_t index, _In_opt_ const uint8_t* seekTable, const HEADER& header, const BANKDATA& data) noexcept { if (!seekTable || index >= data.dwEntryCount) return nullptr; @@ -413,7 +375,7 @@ namespace if ((uint64_t(index) + 1u) * sizeof(uint32_t) > seekSize) return nullptr; - auto table = reinterpret_cast(seekTable); + auto table = reinterpret_cast(seekTable); const uint32_t entry = table[index]; if (entry == uint32_t(-1)) return nullptr; @@ -436,7 +398,7 @@ namespace return result; } -} +} // namespace static_assert(sizeof(REGION) == 8, "Mismatch with xact3wb.h"); static_assert(sizeof(SAMPLEREGION) == 8, "Mismatch with xact3wb.h"); @@ -453,27 +415,28 @@ using namespace DirectX; class WaveBankReader::Impl { public: - Impl() noexcept : - m_async(INVALID_HANDLE_VALUE), - m_request{}, - m_prepared(false), - m_header{}, - m_data{} - #ifdef DIRECTX_ENABLE_XMA2 - , m_xmaMemory(nullptr) - #endif + Impl() noexcept + : m_async(INVALID_HANDLE_VALUE), + m_request{}, + m_prepared(false), + m_header{}, + m_data{} +#ifdef DIRECTX_ENABLE_XMA2 + , + m_xmaMemory(nullptr) +#endif {} - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() { Close(); } HRESULT Open(_In_z_ const wchar_t* szFileName) noexcept(false); - void Close() noexcept; + void Close() noexcept; HRESULT GetFormat(_In_ uint32_t index, _Out_writes_bytes_(maxsize) WAVEFORMATEX* pFormat, _In_ size_t maxsize) const noexcept; @@ -495,38 +458,36 @@ class WaveBankReader::Impl m_seekData.reset(); m_waveData.reset(); - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 if (m_xmaMemory) { ApuFree(m_xmaMemory); m_xmaMemory = nullptr; } - #endif +#endif } - HANDLE m_async; - ScopedHandle m_event; - OVERLAPPED m_request; - bool m_prepared; + HANDLE m_async; + ScopedHandle m_event; + OVERLAPPED m_request; + bool m_prepared; - HEADER m_header; - BANKDATA m_data; - std::map m_names; + HEADER m_header; + BANKDATA m_data; + std::map m_names; private: - std::unique_ptr m_entries; - std::unique_ptr m_seekData; - std::unique_ptr m_waveData; + std::unique_ptr m_entries; + std::unique_ptr m_seekData; + std::unique_ptr m_waveData; #ifdef DIRECTX_ENABLE_XMA2 public: - void* m_xmaMemory; + void* m_xmaMemory; #endif }; - -_Use_decl_annotations_ -HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) +_Use_decl_annotations_ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) { Close(); Clear(); @@ -543,12 +504,9 @@ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) } CREATEFILE2_EXTENDED_PARAMETERS params = { sizeof(CREATEFILE2_EXTENDED_PARAMETERS), 0, 0, 0, {}, nullptr }; - params.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; - params.dwFileFlags = FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN; - ScopedHandle hFile(safe_handle(CreateFile2( - szFileName, - GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, - ¶ms))); + params.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; + params.dwFileFlags = FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN; + ScopedHandle hFile(safe_handle(CreateFile2(szFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms))); if (!hFile) { return HRESULT_FROM_WIN32(GetLastError()); @@ -556,7 +514,7 @@ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) // Read and verify header OVERLAPPED request = {}; - request.hEvent = m_event.get(); + request.hEvent = m_event.get(); if (!ReadFile(hFile.get(), &m_header, sizeof(m_header), nullptr, &request)) { @@ -566,7 +524,7 @@ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) } DWORD bytes; - BOOL result = GetOverlappedResultEx(hFile.get(), &request, &bytes, INFINITE, FALSE); + BOOL result = GetOverlappedResultEx(hFile.get(), &request, &bytes, INFINITE, FALSE); if (!result || (bytes != sizeof(m_header))) { return HRESULT_FROM_WIN32(GetLastError()); @@ -801,12 +759,9 @@ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) hFile.reset(); CREATEFILE2_EXTENDED_PARAMETERS params2 = { sizeof(CREATEFILE2_EXTENDED_PARAMETERS), 0, 0, 0, {}, nullptr }; - params2.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; - params2.dwFileFlags = FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING; - m_async = CreateFile2( - szFileName, - GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, - ¶ms2); + params2.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; + params2.dwFileFlags = FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING; + m_async = CreateFile2(szFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms2); if (m_async == INVALID_HANDLE_VALUE) { return HRESULT_FROM_WIN32(GetLastError()); @@ -819,7 +774,7 @@ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) // If in-memory, kick off read of wave data void* dest = nullptr; - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 bool xma = false; if (m_data.dwFlags & BANKDATA::FLAGS_COMPACT) { @@ -851,7 +806,7 @@ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) dest = m_xmaMemory; } else - #endif // XMA2 +#endif // XMA2 { m_waveData.reset(new (std::nothrow) uint8_t[waveLen]); if (!m_waveData) @@ -882,7 +837,6 @@ HRESULT WaveBankReader::Impl::Open(const wchar_t* szFileName) noexcept(false) return S_OK; } - void WaveBankReader::Impl::Close() noexcept { if (m_async != INVALID_HANDLE_VALUE) @@ -907,9 +861,7 @@ void WaveBankReader::Impl::Close() noexcept #endif } - -_Use_decl_annotations_ -HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, size_t maxsize) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, size_t maxsize) const noexcept { if (!pFormat || !maxsize) return E_INVALIDARG; @@ -919,7 +871,8 @@ HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, s return E_FAIL; } - auto& miniFmt = (m_data.dwFlags & BANKDATA::FLAGS_COMPACT) ? m_data.CompactFormat : (reinterpret_cast(m_entries.get())[index].Format); + auto& miniFmt = (m_data.dwFlags & BANKDATA::FLAGS_COMPACT) ? m_data.CompactFormat : + (reinterpret_cast(m_entries.get())[index].Format); switch (miniFmt.wFormatTag) { @@ -940,9 +893,9 @@ HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, s return HRESULT_FROM_WIN32(ERROR_MORE_DATA); pFormat->wFormatTag = WAVE_FORMAT_ADPCM; - pFormat->cbSize = MSADPCM_FORMAT_EXTRA_BYTES; + pFormat->cbSize = MSADPCM_FORMAT_EXTRA_BYTES; { - auto adpcmFmt = reinterpret_cast(pFormat); + auto adpcmFmt = reinterpret_cast(pFormat); adpcmFmt->wSamplesPerBlock = static_cast(miniFmt.AdpcmSamplesPerBlock()); miniFmt.AdpcmFillCoefficientTable(adpcmFmt); } @@ -953,21 +906,21 @@ HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, s return HRESULT_FROM_WIN32(ERROR_MORE_DATA); pFormat->wFormatTag = static_cast((miniFmt.wBitsPerSample & 0x1) ? WAVE_FORMAT_WMAUDIO3 : WAVE_FORMAT_WMAUDIO2); - pFormat->cbSize = 0; + pFormat->cbSize = 0; break; case MINIWAVEFORMAT::TAG_XMA: // XMA2 is supported by Xbox One - #ifdef DIRECTX_ENABLE_XMA2 +#ifdef DIRECTX_ENABLE_XMA2 if (maxsize < sizeof(XMA2WAVEFORMATEX)) return HRESULT_FROM_WIN32(ERROR_MORE_DATA); pFormat->wFormatTag = WAVE_FORMAT_XMA2; - pFormat->cbSize = sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX); + pFormat->cbSize = sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX); { auto xmaFmt = reinterpret_cast(pFormat); - xmaFmt->NumStreams = static_cast((miniFmt.nChannels + 1) / 2); - xmaFmt->BytesPerBlock = 65536 /* XACT_FIXED_XMA_BLOCK_SIZE */; + xmaFmt->NumStreams = static_cast((miniFmt.nChannels + 1) / 2); + xmaFmt->BytesPerBlock = 65536 /* XACT_FIXED_XMA_BLOCK_SIZE */; xmaFmt->EncoderVersion = 4 /* XMAENCODER_VERSION_XMA2 */; auto seekTable = FindSeekTable(index, m_seekData.get(), m_header, m_data); @@ -982,14 +935,14 @@ HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, s switch (miniFmt.nChannels) { - case 1: xmaFmt->ChannelMask = SPEAKER_MONO; break; - case 2: xmaFmt->ChannelMask = SPEAKER_STEREO; break; - case 3: xmaFmt->ChannelMask = SPEAKER_2POINT1; break; - case 4: xmaFmt->ChannelMask = SPEAKER_QUAD; break; - case 5: xmaFmt->ChannelMask = SPEAKER_4POINT1; break; - case 6: xmaFmt->ChannelMask = SPEAKER_5POINT1; break; - case 7: xmaFmt->ChannelMask = SPEAKER_5POINT1 | SPEAKER_BACK_CENTER; break; - case 8: xmaFmt->ChannelMask = SPEAKER_7POINT1; break; + case 1: xmaFmt->ChannelMask = SPEAKER_MONO; break; + case 2: xmaFmt->ChannelMask = SPEAKER_STEREO; break; + case 3: xmaFmt->ChannelMask = SPEAKER_2POINT1; break; + case 4: xmaFmt->ChannelMask = SPEAKER_QUAD; break; + case 5: xmaFmt->ChannelMask = SPEAKER_4POINT1; break; + case 6: xmaFmt->ChannelMask = SPEAKER_5POINT1; break; + case 7: xmaFmt->ChannelMask = SPEAKER_5POINT1 | SPEAKER_BACK_CENTER; break; + case 8: xmaFmt->ChannelMask = SPEAKER_7POINT1; break; default: xmaFmt->ChannelMask = DWORD(-1); break; } @@ -1002,22 +955,21 @@ HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, s xmaFmt->SamplesEncoded = entry.GetDuration(dwLength, m_data, seekTable); - xmaFmt->PlayBegin = xmaFmt->PlayLength = - xmaFmt->LoopBegin = xmaFmt->LoopLength = xmaFmt->LoopCount = 0; + xmaFmt->PlayBegin = xmaFmt->PlayLength = xmaFmt->LoopBegin = xmaFmt->LoopLength = xmaFmt->LoopCount = 0; } else { auto& entry = reinterpret_cast(m_entries.get())[index]; xmaFmt->SamplesEncoded = entry.Duration; - xmaFmt->PlayBegin = 0; - xmaFmt->PlayLength = entry.PlayRegion.dwLength; + xmaFmt->PlayBegin = 0; + xmaFmt->PlayLength = entry.PlayRegion.dwLength; if (entry.LoopRegion.dwTotalSamples > 0) { - xmaFmt->LoopBegin = entry.LoopRegion.dwStartSample; + xmaFmt->LoopBegin = entry.LoopRegion.dwStartSample; xmaFmt->LoopLength = entry.LoopRegion.dwTotalSamples; - xmaFmt->LoopCount = 0xff /* XACTLOOPCOUNT_INFINITE */; + xmaFmt->LoopCount = 0xff /* XACTLOOPCOUNT_INFINITE */; } else { @@ -1026,26 +978,23 @@ HRESULT WaveBankReader::Impl::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, s } } break; - #else +#else return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); - #endif +#endif - default: - return E_FAIL; + default: return E_FAIL; } - pFormat->nChannels = miniFmt.nChannels; - pFormat->wBitsPerSample = miniFmt.BitsPerSample(); - pFormat->nBlockAlign = static_cast(miniFmt.BlockAlign()); - pFormat->nSamplesPerSec = miniFmt.nSamplesPerSec; + pFormat->nChannels = miniFmt.nChannels; + pFormat->wBitsPerSample = miniFmt.BitsPerSample(); + pFormat->nBlockAlign = static_cast(miniFmt.BlockAlign()); + pFormat->nSamplesPerSec = miniFmt.nSamplesPerSec; pFormat->nAvgBytesPerSec = miniFmt.AvgBytesPerSec(); return S_OK; } - -_Use_decl_annotations_ -HRESULT WaveBankReader::Impl::GetWaveData(uint32_t index, const uint8_t** pData, uint32_t& dataSize) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::Impl::GetWaveData(uint32_t index, const uint8_t** pData, uint32_t& dataSize) const noexcept { if (!pData) return E_INVALIDARG; @@ -1086,35 +1035,37 @@ HRESULT WaveBankReader::Impl::GetWaveData(uint32_t index, const uint8_t** pData, return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } - *pData = &waveData[dwOffset]; + *pData = &waveData[dwOffset]; dataSize = dwLength; } else { auto& entry = reinterpret_cast(m_entries.get())[index]; - if ((uint64_t(entry.PlayRegion.dwOffset) + uint64_t(entry.PlayRegion.dwLength)) > uint64_t(m_header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwLength)) + if ((uint64_t(entry.PlayRegion.dwOffset) + uint64_t(entry.PlayRegion.dwLength)) + > uint64_t(m_header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwLength)) { return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } - *pData = &waveData[entry.PlayRegion.dwOffset]; + *pData = &waveData[entry.PlayRegion.dwOffset]; dataSize = entry.PlayRegion.dwLength; } return S_OK; } - -_Use_decl_annotations_ -HRESULT WaveBankReader::Impl::GetSeekTable(uint32_t index, const uint32_t** pData, uint32_t& dataCount, uint32_t& tag) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::Impl::GetSeekTable(uint32_t index, + const uint32_t** pData, + uint32_t& dataCount, + uint32_t& tag) const noexcept { if (!pData) return E_INVALIDARG; - *pData = nullptr; + *pData = nullptr; dataCount = 0; - tag = 0; + tag = 0; if (index >= m_data.dwEntryCount || !m_entries) { @@ -1124,7 +1075,8 @@ HRESULT WaveBankReader::Impl::GetSeekTable(uint32_t index, const uint32_t** pDat if (!m_seekData) return S_OK; - auto& miniFmt = (m_data.dwFlags & BANKDATA::FLAGS_COMPACT) ? m_data.CompactFormat : (reinterpret_cast(m_entries.get())[index].Format); + auto& miniFmt = (m_data.dwFlags & BANKDATA::FLAGS_COMPACT) ? m_data.CompactFormat : + (reinterpret_cast(m_entries.get())[index].Format); switch (miniFmt.wFormatTag) { @@ -1132,12 +1084,9 @@ HRESULT WaveBankReader::Impl::GetSeekTable(uint32_t index, const uint32_t** pDat tag = static_cast((miniFmt.wBitsPerSample & 0x1) ? WAVE_FORMAT_WMAUDIO3 : WAVE_FORMAT_WMAUDIO2); break; - case MINIWAVEFORMAT::TAG_XMA: - tag = 0x166 /* WAVE_FORMAT_XMA2 */; - break; + case MINIWAVEFORMAT::TAG_XMA: tag = 0x166 /* WAVE_FORMAT_XMA2 */; break; - default: - return S_OK; + default: return S_OK; } auto seekTable = FindSeekTable(index, m_seekData.get(), m_header, m_data); @@ -1145,14 +1094,12 @@ HRESULT WaveBankReader::Impl::GetSeekTable(uint32_t index, const uint32_t** pDat return S_OK; dataCount = *seekTable; - *pData = seekTable + 1; + *pData = seekTable + 1; return S_OK; } - -_Use_decl_annotations_ -HRESULT WaveBankReader::Impl::GetMetadata(uint32_t index, Metadata& metadata) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::Impl::GetMetadata(uint32_t index, Metadata& metadata) const noexcept { if (index >= m_data.dwEntryCount || !m_entries) { @@ -1183,16 +1130,16 @@ HRESULT WaveBankReader::Impl::GetMetadata(uint32_t index, Metadata& metadata) co metadata.duration = entry.GetDuration(dwLength, m_data, nullptr); } metadata.loopStart = metadata.loopLength = 0; - metadata.offsetBytes = dwOffset; - metadata.lengthBytes = dwLength; + metadata.offsetBytes = dwOffset; + metadata.lengthBytes = dwLength; } else { auto& entry = reinterpret_cast(m_entries.get())[index]; - metadata.duration = entry.Duration; - metadata.loopStart = entry.LoopRegion.dwStartSample; - metadata.loopLength = entry.LoopRegion.dwTotalSamples; + metadata.duration = entry.Duration; + metadata.loopStart = entry.LoopRegion.dwStartSample; + metadata.loopLength = entry.LoopRegion.dwTotalSamples; metadata.offsetBytes = entry.PlayRegion.dwOffset; metadata.lengthBytes = entry.PlayRegion.dwLength; } @@ -1211,7 +1158,6 @@ HRESULT WaveBankReader::Impl::GetMetadata(uint32_t index, Metadata& metadata) co return S_OK; } - bool WaveBankReader::Impl::UpdatePrepared() noexcept { if (m_prepared) @@ -1223,7 +1169,7 @@ bool WaveBankReader::Impl::UpdatePrepared() noexcept if (m_request.hEvent) { - DWORD bytes; + DWORD bytes; const BOOL result = GetOverlappedResultEx(m_async, &m_request, &bytes, 0, FALSE); if (result) { @@ -1236,27 +1182,19 @@ bool WaveBankReader::Impl::UpdatePrepared() noexcept return m_prepared; } - - //-------------------------------------------------------------------------------------- -WaveBankReader::WaveBankReader() noexcept(false) : - pImpl(std::make_unique()) +WaveBankReader::WaveBankReader() noexcept(false) + : pImpl(std::make_unique()) {} +WaveBankReader::~WaveBankReader() {} -WaveBankReader::~WaveBankReader() -{} - - -_Use_decl_annotations_ -HRESULT WaveBankReader::Open(const wchar_t* szFileName) noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::Open(const wchar_t* szFileName) noexcept { return pImpl->Open(szFileName); } - -_Use_decl_annotations_ -uint32_t WaveBankReader::Find(const char* name) const +_Use_decl_annotations_ uint32_t WaveBankReader::Find(const char* name) const { if (name) { @@ -1270,7 +1208,6 @@ uint32_t WaveBankReader::Find(const char* name) const return uint32_t(-1); } - bool WaveBankReader::IsPrepared() noexcept { if (pImpl->m_prepared) @@ -1279,7 +1216,6 @@ bool WaveBankReader::IsPrepared() noexcept return pImpl->UpdatePrepared(); } - void WaveBankReader::WaitOnPrepare() noexcept { if (pImpl->m_prepared) @@ -1293,19 +1229,16 @@ void WaveBankReader::WaitOnPrepare() noexcept } } - bool WaveBankReader::HasNames() const noexcept { return !pImpl->m_names.empty(); } - bool WaveBankReader::IsStreamingBank() const noexcept { - return (pImpl->m_data.dwFlags & BANKDATA::TYPE_STREAMING) != 0; + return (pImpl->m_data.dwFlags & BANKDATA::TYPE_STREAMING) != 0; } - #ifdef DIRECTX_ENABLE_XMA2 bool WaveBankReader::HasXMA() const noexcept { @@ -1313,59 +1246,49 @@ bool WaveBankReader::HasXMA() const noexcept } #endif - const char* WaveBankReader::BankName() const noexcept { return pImpl->m_data.szBankName; } - uint32_t WaveBankReader::Count() const noexcept { return pImpl->m_data.dwEntryCount; } - uint32_t WaveBankReader::BankAudioSize() const noexcept { return pImpl->m_header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwLength; } - -_Use_decl_annotations_ -HRESULT WaveBankReader::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, size_t maxsize) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::GetFormat(uint32_t index, WAVEFORMATEX* pFormat, size_t maxsize) const noexcept { return pImpl->GetFormat(index, pFormat, maxsize); } - -_Use_decl_annotations_ -HRESULT WaveBankReader::GetWaveData(uint32_t index, const uint8_t** pData, uint32_t& dataSize) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::GetWaveData(uint32_t index, const uint8_t** pData, uint32_t& dataSize) const noexcept { return pImpl->GetWaveData(index, pData, dataSize); } - -_Use_decl_annotations_ -HRESULT WaveBankReader::GetSeekTable(uint32_t index, const uint32_t** pData, uint32_t& dataCount, uint32_t& tag) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::GetSeekTable(uint32_t index, + const uint32_t** pData, + uint32_t& dataCount, + uint32_t& tag) const noexcept { return pImpl->GetSeekTable(index, pData, dataCount, tag); } - -_Use_decl_annotations_ -HRESULT WaveBankReader::GetMetadata(uint32_t index, Metadata& metadata) const noexcept +_Use_decl_annotations_ HRESULT WaveBankReader::GetMetadata(uint32_t index, Metadata& metadata) const noexcept { return pImpl->GetMetadata(index, metadata); } - HANDLE WaveBankReader::GetAsyncHandle() const noexcept { return (pImpl->m_data.dwFlags & BANKDATA::TYPE_STREAMING) ? pImpl->m_async : INVALID_HANDLE_VALUE; } - uint32_t WaveBankReader::GetWaveAlignment() const noexcept { return pImpl->m_data.dwAlignment; diff --git a/Audio/WaveBankReader.h b/Audio/WaveBankReader.h index 6d1ddda6..56038d29 100644 --- a/Audio/WaveBankReader.h +++ b/Audio/WaveBankReader.h @@ -18,7 +18,6 @@ #include #include - namespace DirectX { class WaveBankReader @@ -26,11 +25,11 @@ namespace DirectX public: WaveBankReader() noexcept(false); - WaveBankReader(WaveBankReader&&) = default; - WaveBankReader& operator= (WaveBankReader&&) = default; + WaveBankReader(WaveBankReader&&) = default; + WaveBankReader& operator=(WaveBankReader&&) = default; - WaveBankReader(WaveBankReader const&) = delete; - WaveBankReader& operator= (WaveBankReader const&) = delete; + WaveBankReader(WaveBankReader const&) = delete; + WaveBankReader& operator=(WaveBankReader const&) = delete; ~WaveBankReader(); @@ -44,9 +43,9 @@ namespace DirectX bool HasNames() const noexcept; bool IsStreamingBank() const noexcept; - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) bool HasXMA() const noexcept; - #endif +#endif const char* BankName() const noexcept; @@ -58,7 +57,8 @@ namespace DirectX HRESULT GetWaveData(_In_ uint32_t index, _Outptr_ const uint8_t** pData, _Out_ uint32_t& dataSize) const noexcept; - HRESULT GetSeekTable(_In_ uint32_t index, _Out_ const uint32_t** pData, _Out_ uint32_t& dataCount, _Out_ uint32_t& tag) const noexcept; + HRESULT + GetSeekTable(_In_ uint32_t index, _Out_ const uint32_t** pData, _Out_ uint32_t& dataCount, _Out_ uint32_t& tag) const noexcept; HANDLE GetAsyncHandle() const noexcept; @@ -66,11 +66,11 @@ namespace DirectX struct Metadata { - uint32_t duration; - uint32_t loopStart; - uint32_t loopLength; - uint32_t offsetBytes; - uint32_t lengthBytes; + uint32_t duration; + uint32_t loopStart; + uint32_t loopLength; + uint32_t offsetBytes; + uint32_t lengthBytes; }; HRESULT GetMetadata(_In_ uint32_t index, _Out_ Metadata& metadata) const noexcept; @@ -80,4 +80,4 @@ namespace DirectX std::unique_ptr pImpl; }; -} +} // namespace DirectX diff --git a/Inc/Audio.h b/Inc/Audio.h index 993474d3..3b88cb00 100644 --- a/Inc/Audio.h +++ b/Inc/Audio.h @@ -26,7 +26,7 @@ #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) #include #ifdef _MSC_VER -#pragma comment(lib,"acphal.lib") +#pragma comment(lib, "acphal.lib") #endif #endif @@ -59,9 +59,9 @@ #if !defined(USING_XAUDIO2_REDIST) && defined(_MSC_VER) #if defined(USING_XAUDIO2_8) && defined(NTDDI_WIN10) && !defined(_M_IX86) // The xaudio2_8.lib in the Windows 10 SDK for x86 is incorrectly annotated as __cdecl instead of __stdcall, so avoid using it in this case. -#pragma comment(lib,"xaudio2_8.lib") +#pragma comment(lib, "xaudio2_8.lib") #else -#pragma comment(lib,"xaudio2.lib") +#pragma comment(lib, "xaudio2.lib") #endif #endif @@ -70,13 +70,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -85,7 +85,6 @@ #endif #endif - namespace DirectX { class SoundEffectInstance; @@ -94,57 +93,56 @@ namespace DirectX //---------------------------------------------------------------------------------- struct AudioStatistics { - size_t playingOneShots; // Number of one-shot sounds currently playing - size_t playingInstances; // Number of sound effect instances currently playing - size_t allocatedInstances; // Number of SoundEffectInstance allocated - size_t allocatedVoices; // Number of XAudio2 voices allocated (standard, 3D, one-shots, and idle one-shots) - size_t allocatedVoices3d; // Number of XAudio2 voices allocated for 3D - size_t allocatedVoicesOneShot; // Number of XAudio2 voices allocated for one-shot sounds - size_t allocatedVoicesIdle; // Number of XAudio2 voices allocated for one-shot sounds but not currently in use - size_t audioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) - size_t xmaAudioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks allocated with ApuAlloc - #endif - size_t streamingBytes; // Total size of streaming buffers (in bytes) in streaming WaveBanks + size_t playingOneShots; // Number of one-shot sounds currently playing + size_t playingInstances; // Number of sound effect instances currently playing + size_t allocatedInstances; // Number of SoundEffectInstance allocated + size_t allocatedVoices; // Number of XAudio2 voices allocated (standard, 3D, one-shots, and idle one-shots) + size_t allocatedVoices3d; // Number of XAudio2 voices allocated for 3D + size_t allocatedVoicesOneShot; // Number of XAudio2 voices allocated for one-shot sounds + size_t allocatedVoicesIdle; // Number of XAudio2 voices allocated for one-shot sounds but not currently in use + size_t audioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) + size_t xmaAudioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks allocated with ApuAlloc +#endif + size_t streamingBytes; // Total size of streaming buffers (in bytes) in streaming WaveBanks }; - //---------------------------------------------------------------------------------- class DIRECTX_TOOLKIT_API IVoiceNotify { public: virtual ~IVoiceNotify() = default; - IVoiceNotify(const IVoiceNotify&) = delete; + IVoiceNotify(const IVoiceNotify&) = delete; IVoiceNotify& operator=(const IVoiceNotify&) = delete; - IVoiceNotify(IVoiceNotify&&) = default; + IVoiceNotify(IVoiceNotify&&) = default; IVoiceNotify& operator=(IVoiceNotify&&) = default; virtual void __cdecl OnBufferEnd() = 0; - // Notfication that a voice buffer has finished - // Note this is called from XAudio2's worker thread, so it should perform very minimal and thread-safe operations + // Notfication that a voice buffer has finished + // Note this is called from XAudio2's worker thread, so it should perform very minimal and thread-safe operations virtual void __cdecl OnCriticalError() = 0; - // Notification that the audio engine encountered a critical error + // Notification that the audio engine encountered a critical error virtual void __cdecl OnReset() = 0; - // Notification of an audio engine reset + // Notification of an audio engine reset virtual void __cdecl OnUpdate() = 0; - // Notification of an audio engine per-frame update (opt-in) + // Notification of an audio engine per-frame update (opt-in) virtual void __cdecl OnDestroyEngine() noexcept = 0; - // Notification that the audio engine is being destroyed + // Notification that the audio engine is being destroyed virtual void __cdecl OnTrim() = 0; - // Notification of a request to trim the voice pool + // Notification of a request to trim the voice pool virtual void __cdecl GatherStatistics(AudioStatistics& stats) const = 0; - // Contribute to statistics request + // Contribute to statistics request virtual void __cdecl OnDestroyParent() noexcept = 0; - // Optional notification used by some objects + // Optional notification used by some objects protected: IVoiceNotify() = default; @@ -155,15 +153,15 @@ namespace DirectX { AudioEngine_Default = 0x0, - AudioEngine_EnvironmentalReverb = 0x1, - AudioEngine_ReverbUseFilters = 0x2, - AudioEngine_UseMasteringLimiter = 0x4, - AudioEngine_DisableLFERedirect = 0x8, + AudioEngine_EnvironmentalReverb = 0x1, + AudioEngine_ReverbUseFilters = 0x2, + AudioEngine_UseMasteringLimiter = 0x4, + AudioEngine_DisableLFERedirect = 0x8, AudioEngine_DisableDopplerEffect = 0x10, - AudioEngine_ZeroCenter3D = 0x20, + AudioEngine_ZeroCenter3D = 0x20, - AudioEngine_Debug = 0x10000, - AudioEngine_ThrowOnNoAudioHW = 0x20000, + AudioEngine_Debug = 0x10000, + AudioEngine_ThrowOnNoAudioHW = 0x20000, AudioEngine_DisableVoiceReuse = 0x40000, }; @@ -171,11 +169,11 @@ namespace DirectX { SoundEffectInstance_Default = 0x0, - SoundEffectInstance_Use3D = 0x1, + SoundEffectInstance_Use3D = 0x1, SoundEffectInstance_ReverbUseFilters = 0x2, - SoundEffectInstance_NoSetPitch = 0x4, - SoundEffectInstance_UseRedirectLFE = 0x8, - SoundEffectInstance_ZeroCenter3D = 0x10, + SoundEffectInstance_NoSetPitch = 0x4, + SoundEffectInstance_UseRedirectLFE = 0x8, + SoundEffectInstance_ZeroCenter3D = 0x10, }; enum AUDIO_ENGINE_REVERB : uint32_t @@ -221,101 +219,98 @@ namespace DirectX PAUSED }; - //---------------------------------------------------------------------------------- class AudioEngine { public: - DIRECTX_TOOLKIT_API explicit AudioEngine( - AUDIO_ENGINE_FLAGS flags = AudioEngine_Default, - _In_opt_ const WAVEFORMATEX* wfx = nullptr, - _In_opt_z_ const wchar_t* deviceId = nullptr, - AUDIO_STREAM_CATEGORY category = AudioCategory_GameEffects) noexcept(false); + DIRECTX_TOOLKIT_API explicit AudioEngine(AUDIO_ENGINE_FLAGS flags = AudioEngine_Default, + _In_opt_ const WAVEFORMATEX* wfx = nullptr, + _In_opt_z_ const wchar_t* deviceId = nullptr, + AUDIO_STREAM_CATEGORY category = AudioCategory_GameEffects) noexcept(false); - DIRECTX_TOOLKIT_API AudioEngine(AudioEngine&&) noexcept; - DIRECTX_TOOLKIT_API AudioEngine& operator= (AudioEngine&&) noexcept; + DIRECTX_TOOLKIT_API AudioEngine(AudioEngine&&) noexcept; + DIRECTX_TOOLKIT_API AudioEngine& operator=(AudioEngine&&) noexcept; - AudioEngine(AudioEngine const&) = delete; - AudioEngine& operator= (AudioEngine const&) = delete; + AudioEngine(AudioEngine const&) = delete; + AudioEngine& operator=(AudioEngine const&) = delete; DIRECTX_TOOLKIT_API virtual ~AudioEngine(); DIRECTX_TOOLKIT_API bool __cdecl Update(); - // Performs per-frame processing for the audio engine, returns false if in 'silent mode' + // Performs per-frame processing for the audio engine, returns false if in 'silent mode' - DIRECTX_TOOLKIT_API bool __cdecl Reset( - _In_opt_ const WAVEFORMATEX* wfx = nullptr, - _In_opt_z_ const wchar_t* deviceId = nullptr); - // Reset audio engine from critical error/silent mode using a new device; can also 'migrate' the graph - // Returns true if succesfully reset, false if in 'silent mode' due to no default device - // Note: One shots are lost, all SoundEffectInstances are in the STOPPED state after successful reset + DIRECTX_TOOLKIT_API bool __cdecl Reset(_In_opt_ const WAVEFORMATEX* wfx = nullptr, _In_opt_z_ const wchar_t* deviceId = nullptr); + // Reset audio engine from critical error/silent mode using a new device; can also 'migrate' the graph + // Returns true if succesfully reset, false if in 'silent mode' due to no default device + // Note: One shots are lost, all SoundEffectInstances are in the STOPPED state after successful reset DIRECTX_TOOLKIT_API void __cdecl Suspend() noexcept; DIRECTX_TOOLKIT_API void __cdecl Resume(); - // Suspend/resumes audio processing (i.e. global pause/resume) + // Suspend/resumes audio processing (i.e. global pause/resume) DIRECTX_TOOLKIT_API float __cdecl GetMasterVolume() const noexcept; - DIRECTX_TOOLKIT_API void __cdecl SetMasterVolume(float volume); - // Master volume property for all sounds + DIRECTX_TOOLKIT_API void __cdecl SetMasterVolume(float volume); + // Master volume property for all sounds DIRECTX_TOOLKIT_API void __cdecl SetReverb(AUDIO_ENGINE_REVERB reverb); DIRECTX_TOOLKIT_API void __cdecl SetReverb(_In_opt_ const XAUDIO2FX_REVERB_PARAMETERS* native); - // Sets environmental reverb for 3D positional audio (if active) + // Sets environmental reverb for 3D positional audio (if active) DIRECTX_TOOLKIT_API void __cdecl SetMasteringLimit(int release, int loudness); - // Sets the mastering volume limiter properties (if active) + // Sets the mastering volume limiter properties (if active) DIRECTX_TOOLKIT_API AudioStatistics __cdecl GetStatistics() const; - // Gathers audio engine statistics + // Gathers audio engine statistics DIRECTX_TOOLKIT_API WAVEFORMATEXTENSIBLE __cdecl GetOutputFormat() const noexcept; - // Returns the format of the audio output device associated with the mastering voice. + // Returns the format of the audio output device associated with the mastering voice. DIRECTX_TOOLKIT_API uint32_t __cdecl GetChannelMask() const noexcept; - // Returns the output channel mask + // Returns the output channel mask DIRECTX_TOOLKIT_API int __cdecl GetOutputSampleRate() const noexcept; - // Returns the sample rate going into the mastering voice + // Returns the sample rate going into the mastering voice DIRECTX_TOOLKIT_API unsigned int __cdecl GetOutputChannels() const noexcept; - // Returns the number of channels going into the mastering voice + // Returns the number of channels going into the mastering voice DIRECTX_TOOLKIT_API bool __cdecl IsAudioDevicePresent() const noexcept; - // Returns true if the audio graph is operating normally, false if in 'silent mode' + // Returns true if the audio graph is operating normally, false if in 'silent mode' DIRECTX_TOOLKIT_API bool __cdecl IsCriticalError() const noexcept; - // Returns true if the audio graph is halted due to a critical error (which also places the engine into 'silent mode') + // Returns true if the audio graph is halted due to a critical error (which also places the engine into 'silent mode') // Voice pool management. DIRECTX_TOOLKIT_API void __cdecl SetDefaultSampleRate(int sampleRate); - // Sample rate for voices in the reuse pool (defaults to 44100) + // Sample rate for voices in the reuse pool (defaults to 44100) DIRECTX_TOOLKIT_API void __cdecl SetMaxVoicePool(size_t maxOneShots, size_t maxInstances); - // Maximum number of voices to allocate for one-shots and instances - // Note: one-shots over this limit are ignored; too many instance voices throws an exception + // Maximum number of voices to allocate for one-shots and instances + // Note: one-shots over this limit are ignored; too many instance voices throws an exception DIRECTX_TOOLKIT_API void __cdecl TrimVoicePool(); - // Releases any currently unused voices + // Releases any currently unused voices // Internal-use functions void __cdecl AllocateVoice(_In_ const WAVEFORMATEX* wfx, - SOUND_EFFECT_INSTANCE_FLAGS flags, bool oneshot, + SOUND_EFFECT_INSTANCE_FLAGS flags, + bool oneshot, _Outptr_result_maybenull_ IXAudio2SourceVoice** voice); DIRECTX_TOOLKIT_API void __cdecl DestroyVoice(_In_ IXAudio2SourceVoice* voice) noexcept; - // Should only be called for instance voices, not one-shots + // Should only be called for instance voices, not one-shots DIRECTX_TOOLKIT_API void __cdecl RegisterNotify(_In_ IVoiceNotify* notify, bool usesUpdate); - void __cdecl UnregisterNotify(_In_ IVoiceNotify* notify, bool usesOneShots, bool usesUpdate); + void __cdecl UnregisterNotify(_In_ IVoiceNotify* notify, bool usesOneShots, bool usesUpdate); // XAudio2 interface access - DIRECTX_TOOLKIT_API IXAudio2* __cdecl GetInterface() const noexcept; + DIRECTX_TOOLKIT_API IXAudio2* __cdecl GetInterface() const noexcept; DIRECTX_TOOLKIT_API IXAudio2MasteringVoice* __cdecl GetMasterVoice() const noexcept; - DIRECTX_TOOLKIT_API IXAudio2SubmixVoice* __cdecl GetReverbVoice() const noexcept; + DIRECTX_TOOLKIT_API IXAudio2SubmixVoice* __cdecl GetReverbVoice() const noexcept; // X3DAudio interface access DIRECTX_TOOLKIT_API X3DAUDIO_HANDLE& __cdecl Get3DHandle() const noexcept; - DIRECTX_TOOLKIT_API uint32_t __cdecl Get3DCalculateFlags() const noexcept; + DIRECTX_TOOLKIT_API uint32_t __cdecl Get3DCalculateFlags() const noexcept; // Static functions struct RendererDetail @@ -325,19 +320,16 @@ namespace DirectX }; DIRECTX_TOOLKIT_API static std::vector __cdecl GetRendererDetails(); - // Returns a list of valid audio endpoint devices + // Returns a list of valid audio endpoint devices - #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) - DIRECTX_TOOLKIT_API explicit AudioEngine( - AUDIO_ENGINE_FLAGS flags = AudioEngine_Default, - _In_opt_ const WAVEFORMATEX* wfx = nullptr, - _In_opt_z_ const __wchar_t* deviceId = nullptr, - AUDIO_STREAM_CATEGORY category = AudioCategory_GameEffects) noexcept(false); +#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) + DIRECTX_TOOLKIT_API explicit AudioEngine(AUDIO_ENGINE_FLAGS flags = AudioEngine_Default, + _In_opt_ const WAVEFORMATEX* wfx = nullptr, + _In_opt_z_ const __wchar_t* deviceId = nullptr, + AUDIO_STREAM_CATEGORY category = AudioCategory_GameEffects) noexcept(false); - DIRECTX_TOOLKIT_API bool __cdecl Reset( - _In_opt_ const WAVEFORMATEX* wfx = nullptr, - _In_opt_z_ const __wchar_t* deviceId = nullptr); - #endif + DIRECTX_TOOLKIT_API bool __cdecl Reset(_In_opt_ const WAVEFORMATEX* wfx = nullptr, _In_opt_z_ const __wchar_t* deviceId = nullptr); +#endif private: // Private implementation. @@ -345,45 +337,34 @@ namespace DirectX std::unique_ptr pImpl; }; - //---------------------------------------------------------------------------------- class WaveBank { public: - DIRECTX_TOOLKIT_API WaveBank( - _In_ AudioEngine* engine, - _In_z_ const wchar_t* wbFileName); + DIRECTX_TOOLKIT_API WaveBank(_In_ AudioEngine* engine, _In_z_ const wchar_t* wbFileName); - DIRECTX_TOOLKIT_API WaveBank(WaveBank&&) noexcept; - DIRECTX_TOOLKIT_API WaveBank& operator= (WaveBank&&) noexcept; + DIRECTX_TOOLKIT_API WaveBank(WaveBank&&) noexcept; + DIRECTX_TOOLKIT_API WaveBank& operator=(WaveBank&&) noexcept; - WaveBank(WaveBank const&) = delete; - WaveBank& operator= (WaveBank const&) = delete; + WaveBank(WaveBank const&) = delete; + WaveBank& operator=(WaveBank const&) = delete; DIRECTX_TOOLKIT_API virtual ~WaveBank(); DIRECTX_TOOLKIT_API void __cdecl Play(unsigned int index); - DIRECTX_TOOLKIT_API void __cdecl Play( - unsigned int index, - float volume, float pitch, float pan); + DIRECTX_TOOLKIT_API void __cdecl Play(unsigned int index, float volume, float pitch, float pan); DIRECTX_TOOLKIT_API void __cdecl Play(_In_z_ const char* name); - DIRECTX_TOOLKIT_API void __cdecl Play( - _In_z_ const char* name, - float volume, float pitch, float pan); + DIRECTX_TOOLKIT_API void __cdecl Play(_In_z_ const char* name, float volume, float pitch, float pan); - DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateInstance( - unsigned int index, - SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); - DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateInstance( - _In_z_ const char* name, + DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateInstance(unsigned int index, + SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); + DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateInstance(_In_z_ const char* name, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); - DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateStreamInstance( - unsigned int index, + DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateStreamInstance(unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); - DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateStreamInstance( - _In_z_ const char* name, + DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateStreamInstance(_In_z_ const char* name, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); DIRECTX_TOOLKIT_API bool __cdecl IsPrepared() const noexcept; @@ -400,36 +381,27 @@ namespace DirectX DIRECTX_TOOLKIT_API size_t __cdecl GetSampleDurationMS(unsigned int index) const noexcept; // Returns the duration in milliseconds - DIRECTX_TOOLKIT_API const WAVEFORMATEX* __cdecl GetFormat( - unsigned int index, - _Out_writes_bytes_(maxsize) WAVEFORMATEX* wfx, size_t maxsize) const noexcept; + DIRECTX_TOOLKIT_API const WAVEFORMATEX* __cdecl + GetFormat(unsigned int index, _Out_writes_bytes_(maxsize) WAVEFORMATEX* wfx, size_t maxsize) const noexcept; DIRECTX_TOOLKIT_API int __cdecl Find(_In_z_ const char* name) const; - #ifdef USING_XAUDIO2_9 - DIRECTX_TOOLKIT_API bool __cdecl FillSubmitBuffer( - unsigned int index, - _Out_ XAUDIO2_BUFFER& buffer, - _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const; - #else - DIRECTX_TOOLKIT_API void __cdecl FillSubmitBuffer( - unsigned int index, - _Out_ XAUDIO2_BUFFER& buffer) const; - #endif +#ifdef USING_XAUDIO2_9 + DIRECTX_TOOLKIT_API bool __cdecl + FillSubmitBuffer(unsigned int index, _Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const; +#else + DIRECTX_TOOLKIT_API void __cdecl FillSubmitBuffer(unsigned int index, _Out_ XAUDIO2_BUFFER& buffer) const; +#endif DIRECTX_TOOLKIT_API void __cdecl UnregisterInstance(_In_ IVoiceNotify* instance); DIRECTX_TOOLKIT_API HANDLE __cdecl GetAsyncHandle() const noexcept; - DIRECTX_TOOLKIT_API bool __cdecl GetPrivateData( - unsigned int index, - _Out_writes_bytes_(datasize) void* data, size_t datasize); + DIRECTX_TOOLKIT_API bool __cdecl GetPrivateData(unsigned int index, _Out_writes_bytes_(datasize) void* data, size_t datasize); - #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) - DIRECTX_TOOLKIT_API WaveBank( - _In_ AudioEngine* engine, - _In_z_ const __wchar_t* wbFileName); - #endif +#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) + DIRECTX_TOOLKIT_API WaveBank(_In_ AudioEngine* engine, _In_z_ const __wchar_t* wbFileName); +#endif private: // Private implementation. @@ -438,51 +410,51 @@ namespace DirectX std::unique_ptr pImpl; }; - //---------------------------------------------------------------------------------- class SoundEffect { public: - DIRECTX_TOOLKIT_API SoundEffect( - _In_ AudioEngine* engine, - _In_z_ const wchar_t* waveFileName); - - DIRECTX_TOOLKIT_API SoundEffect( - _In_ AudioEngine* engine, - _Inout_ std::unique_ptr& wavData, - _In_ const WAVEFORMATEX* wfx, - _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes); - - DIRECTX_TOOLKIT_API SoundEffect( - _In_ AudioEngine* engine, - _Inout_ std::unique_ptr& wavData, - _In_ const WAVEFORMATEX* wfx, - _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes, - uint32_t loopStart, uint32_t loopLength); - - #ifdef USING_XAUDIO2_9 + DIRECTX_TOOLKIT_API SoundEffect(_In_ AudioEngine* engine, _In_z_ const wchar_t* waveFileName); + + DIRECTX_TOOLKIT_API SoundEffect(_In_ AudioEngine* engine, + _Inout_ std::unique_ptr& wavData, + _In_ const WAVEFORMATEX* wfx, + _In_reads_bytes_(audioBytes) const uint8_t* startAudio, + size_t audioBytes); + + DIRECTX_TOOLKIT_API SoundEffect(_In_ AudioEngine* engine, + _Inout_ std::unique_ptr& wavData, + _In_ const WAVEFORMATEX* wfx, + _In_reads_bytes_(audioBytes) const uint8_t* startAudio, + size_t audioBytes, + uint32_t loopStart, + uint32_t loopLength); + +#ifdef USING_XAUDIO2_9 + + DIRECTX_TOOLKIT_API SoundEffect(_In_ AudioEngine* engine, + _Inout_ std::unique_ptr& wavData, + _In_ const WAVEFORMATEX* wfx, + _In_reads_bytes_(audioBytes) const uint8_t* startAudio, + size_t audioBytes, + _In_reads_(seekCount) const uint32_t* seekTable, + size_t seekCount); - DIRECTX_TOOLKIT_API SoundEffect( - _In_ AudioEngine* engine, - _Inout_ std::unique_ptr& wavData, - _In_ const WAVEFORMATEX* wfx, - _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes, - _In_reads_(seekCount) const uint32_t* seekTable, size_t seekCount); - - #endif +#endif - DIRECTX_TOOLKIT_API SoundEffect(SoundEffect&&) noexcept; - DIRECTX_TOOLKIT_API SoundEffect& operator= (SoundEffect&&) noexcept; + DIRECTX_TOOLKIT_API SoundEffect(SoundEffect&&) noexcept; + DIRECTX_TOOLKIT_API SoundEffect& operator=(SoundEffect&&) noexcept; - SoundEffect(SoundEffect const&) = delete; - SoundEffect& operator= (SoundEffect const&) = delete; + SoundEffect(SoundEffect const&) = delete; + SoundEffect& operator=(SoundEffect const&) = delete; DIRECTX_TOOLKIT_API virtual ~SoundEffect(); DIRECTX_TOOLKIT_API void __cdecl Play(); DIRECTX_TOOLKIT_API void __cdecl Play(float volume, float pitch, float pan); - DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateInstance(SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); + DIRECTX_TOOLKIT_API std::unique_ptr __cdecl CreateInstance( + SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); DIRECTX_TOOLKIT_API bool __cdecl IsInUse() const noexcept; @@ -497,21 +469,17 @@ namespace DirectX DIRECTX_TOOLKIT_API const WAVEFORMATEX* __cdecl GetFormat() const noexcept; - #ifdef USING_XAUDIO2_9 - DIRECTX_TOOLKIT_API bool __cdecl FillSubmitBuffer( - _Out_ XAUDIO2_BUFFER& buffer, - _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const; - #else +#ifdef USING_XAUDIO2_9 + DIRECTX_TOOLKIT_API bool __cdecl FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const; +#else DIRECTX_TOOLKIT_API void __cdecl FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer) const; - #endif +#endif DIRECTX_TOOLKIT_API void __cdecl UnregisterInstance(_In_ IVoiceNotify* instance); - #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) - DIRECTX_TOOLKIT_API SoundEffect( - _In_ AudioEngine* engine, - _In_z_ const __wchar_t* waveFileName); - #endif +#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) + DIRECTX_TOOLKIT_API SoundEffect(_In_ AudioEngine* engine, _In_z_ const __wchar_t* waveFileName); +#endif private: // Private implementation. @@ -520,37 +488,30 @@ namespace DirectX std::unique_ptr pImpl; }; - //---------------------------------------------------------------------------------- struct DIRECTX_TOOLKIT_API AudioListener : public X3DAUDIO_LISTENER { - X3DAUDIO_CONE ListenerCone; + X3DAUDIO_CONE ListenerCone; - AudioListener() noexcept : - X3DAUDIO_LISTENER{}, - ListenerCone{} + AudioListener() noexcept + : X3DAUDIO_LISTENER{}, + ListenerCone{} { OrientFront.z = -1.f; OrientTop.y = 1.f; } - void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept - { - XMStoreFloat3(reinterpret_cast(&Position), v); - } - void __cdecl SetPosition(const XMFLOAT3& pos) noexcept + void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Position), v); } + void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; Position.y = pos.y; Position.z = pos.z; } - void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept - { - XMStoreFloat3(reinterpret_cast(&Velocity), v); - } - void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept + void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Velocity), v); } + void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; Velocity.y = vel.y; @@ -564,9 +525,12 @@ namespace DirectX } void __cdecl SetOrientation(const XMFLOAT3& forward, const XMFLOAT3& up) noexcept { - OrientFront.x = forward.x; OrientTop.x = up.x; - OrientFront.y = forward.y; OrientTop.y = up.y; - OrientFront.z = forward.z; OrientTop.z = up.z; + OrientFront.x = forward.x; + OrientTop.x = up.x; + OrientFront.y = forward.y; + OrientTop.y = up.y; + OrientFront.z = forward.z; + OrientTop.z = up.z; } void XM_CALLCONV SetOrientationFromQuaternion(FXMVECTOR quat) noexcept @@ -585,9 +549,9 @@ namespace DirectX { const XMVECTOR lastPos = XMLoadFloat3(reinterpret_cast(&Position)); - XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos); - const XMVECTOR vt = XMVectorReplicate(dt); - XMVECTOR v = XMVectorDivide(vDelta, vt); + XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos); + const XMVECTOR vt = XMVectorReplicate(dt); + XMVECTOR v = XMVectorDivide(vDelta, vt); XMStoreFloat3(reinterpret_cast(&Velocity), v); vDelta = XMVector3Normalize(vDelta); @@ -604,57 +568,44 @@ namespace DirectX } } - void __cdecl SetOmnidirectional() noexcept - { - pCone = nullptr; - } + void __cdecl SetOmnidirectional() noexcept { pCone = nullptr; } void __cdecl SetCone(const X3DAUDIO_CONE& listenerCone); bool __cdecl IsValid() const noexcept; }; - //---------------------------------------------------------------------------------- struct DIRECTX_TOOLKIT_API AudioEmitter : public X3DAUDIO_EMITTER { - X3DAUDIO_CONE EmitterCone; - float EmitterAzimuths[XAUDIO2_MAX_AUDIO_CHANNELS]; + X3DAUDIO_CONE EmitterCone; + float EmitterAzimuths[XAUDIO2_MAX_AUDIO_CHANNELS]; - AudioEmitter() noexcept : - X3DAUDIO_EMITTER{}, - EmitterCone{}, - EmitterAzimuths{} + AudioEmitter() noexcept + : X3DAUDIO_EMITTER{}, + EmitterCone{}, + EmitterAzimuths{} { OrientFront.z = -1.f; - OrientTop.y = - ChannelRadius = - CurveDistanceScaler = - DopplerScaler = 1.f; + OrientTop.y = ChannelRadius = CurveDistanceScaler = DopplerScaler = 1.f; - ChannelCount = 1; + ChannelCount = 1; pChannelAzimuths = EmitterAzimuths; InnerRadiusAngle = X3DAUDIO_PI / 4.0f; } - void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept - { - XMStoreFloat3(reinterpret_cast(&Position), v); - } - void __cdecl SetPosition(const XMFLOAT3& pos) noexcept + void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Position), v); } + void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; Position.y = pos.y; Position.z = pos.z; } - void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept - { - XMStoreFloat3(reinterpret_cast(&Velocity), v); - } - void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept + void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Velocity), v); } + void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; Velocity.y = vel.y; @@ -668,9 +619,12 @@ namespace DirectX } void __cdecl SetOrientation(const XMFLOAT3& forward, const XMFLOAT3& up) noexcept { - OrientFront.x = forward.x; OrientTop.x = up.x; - OrientFront.y = forward.y; OrientTop.y = up.y; - OrientFront.z = forward.z; OrientTop.z = up.z; + OrientFront.x = forward.x; + OrientTop.x = up.x; + OrientFront.y = forward.y; + OrientTop.y = up.y; + OrientFront.z = forward.z; + OrientTop.z = up.z; } void XM_CALLCONV SetOrientationFromQuaternion(FXMVECTOR quat) noexcept @@ -689,9 +643,9 @@ namespace DirectX { const XMVECTOR lastPos = XMLoadFloat3(reinterpret_cast(&Position)); - XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos); - const XMVECTOR vt = XMVectorReplicate(dt); - XMVECTOR v = XMVectorDivide(vDelta, vt); + XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos); + const XMVECTOR vt = XMVectorReplicate(dt); + XMVECTOR v = XMVectorDivide(vDelta, vt); XMStoreFloat3(reinterpret_cast(&Velocity), v); vDelta = XMVector3Normalize(vDelta); @@ -708,10 +662,7 @@ namespace DirectX } } - void __cdecl SetOmnidirectional() noexcept - { - pCone = nullptr; - } + void __cdecl SetOmnidirectional() noexcept { pCone = nullptr; } // Only used for single-channel emitters. void __cdecl SetCone(const X3DAUDIO_CONE& emitterCone); @@ -725,26 +676,25 @@ namespace DirectX void __cdecl EnableInverseSquareCurves() noexcept { - pVolumeCurve = nullptr; - pLFECurve = nullptr; + pVolumeCurve = nullptr; + pLFECurve = nullptr; pLPFDirectCurve = nullptr; pLPFReverbCurve = nullptr; - pReverbCurve = nullptr; + pReverbCurve = nullptr; } bool __cdecl IsValid() const noexcept; }; - //---------------------------------------------------------------------------------- class SoundEffectInstance { public: - DIRECTX_TOOLKIT_API SoundEffectInstance(SoundEffectInstance&&) noexcept; - DIRECTX_TOOLKIT_API SoundEffectInstance& operator= (SoundEffectInstance&&) noexcept; + DIRECTX_TOOLKIT_API SoundEffectInstance(SoundEffectInstance&&) noexcept; + DIRECTX_TOOLKIT_API SoundEffectInstance& operator=(SoundEffectInstance&&) noexcept; - SoundEffectInstance(SoundEffectInstance const&) = delete; - SoundEffectInstance& operator= (SoundEffectInstance const&) = delete; + SoundEffectInstance(SoundEffectInstance const&) = delete; + SoundEffectInstance& operator=(SoundEffectInstance const&) = delete; DIRECTX_TOOLKIT_API virtual ~SoundEffectInstance(); @@ -757,9 +707,7 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetPitch(float pitch); DIRECTX_TOOLKIT_API void __cdecl SetPan(float pan); - DIRECTX_TOOLKIT_API void __cdecl Apply3D( - const X3DAUDIO_LISTENER& listener, - const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); + DIRECTX_TOOLKIT_API void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); DIRECTX_TOOLKIT_API bool __cdecl IsLooped() const noexcept; @@ -777,22 +725,22 @@ namespace DirectX // Private constructors DIRECTX_TOOLKIT_API SoundEffectInstance(_In_ AudioEngine* engine, _In_ SoundEffect* effect, SOUND_EFFECT_INSTANCE_FLAGS flags); - DIRECTX_TOOLKIT_API SoundEffectInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags); + DIRECTX_TOOLKIT_API + SoundEffectInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags); friend std::unique_ptr __cdecl SoundEffect::CreateInstance(SOUND_EFFECT_INSTANCE_FLAGS); friend std::unique_ptr __cdecl WaveBank::CreateInstance(unsigned int, SOUND_EFFECT_INSTANCE_FLAGS); }; - //---------------------------------------------------------------------------------- class SoundStreamInstance { public: - DIRECTX_TOOLKIT_API SoundStreamInstance(SoundStreamInstance&&) noexcept; - DIRECTX_TOOLKIT_API SoundStreamInstance& operator= (SoundStreamInstance&&) noexcept; + DIRECTX_TOOLKIT_API SoundStreamInstance(SoundStreamInstance&&) noexcept; + DIRECTX_TOOLKIT_API SoundStreamInstance& operator=(SoundStreamInstance&&) noexcept; - SoundStreamInstance(SoundStreamInstance const&) = delete; - SoundStreamInstance& operator= (SoundStreamInstance const&) = delete; + SoundStreamInstance(SoundStreamInstance const&) = delete; + SoundStreamInstance& operator=(SoundStreamInstance const&) = delete; DIRECTX_TOOLKIT_API virtual ~SoundStreamInstance(); @@ -805,9 +753,7 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetPitch(float pitch); DIRECTX_TOOLKIT_API void __cdecl SetPan(float pan); - DIRECTX_TOOLKIT_API void __cdecl Apply3D( - const X3DAUDIO_LISTENER& listener, - const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); + DIRECTX_TOOLKIT_API void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); DIRECTX_TOOLKIT_API bool __cdecl IsLooped() const noexcept; @@ -824,27 +770,28 @@ namespace DirectX std::unique_ptr pImpl; // Private constructors - DIRECTX_TOOLKIT_API SoundStreamInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags); + DIRECTX_TOOLKIT_API + SoundStreamInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags); friend std::unique_ptr __cdecl WaveBank::CreateStreamInstance(unsigned int, SOUND_EFFECT_INSTANCE_FLAGS); }; - //---------------------------------------------------------------------------------- class DynamicSoundEffectInstance { public: - DIRECTX_TOOLKIT_API DynamicSoundEffectInstance( - _In_ AudioEngine* engine, + DIRECTX_TOOLKIT_API DynamicSoundEffectInstance(_In_ AudioEngine* engine, _In_ std::function bufferNeeded, - int sampleRate, int channels, int sampleBits = 16, - SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); + int sampleRate, + int channels, + int sampleBits = 16, + SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); - DIRECTX_TOOLKIT_API DynamicSoundEffectInstance(DynamicSoundEffectInstance&&) noexcept; - DIRECTX_TOOLKIT_API DynamicSoundEffectInstance& operator= (DynamicSoundEffectInstance&&) noexcept; + DIRECTX_TOOLKIT_API DynamicSoundEffectInstance(DynamicSoundEffectInstance&&) noexcept; + DIRECTX_TOOLKIT_API DynamicSoundEffectInstance& operator=(DynamicSoundEffectInstance&&) noexcept; - DynamicSoundEffectInstance(DynamicSoundEffectInstance const&) = delete; - DynamicSoundEffectInstance& operator= (DynamicSoundEffectInstance const&) = delete; + DynamicSoundEffectInstance(DynamicSoundEffectInstance const&) = delete; + DynamicSoundEffectInstance& operator=(DynamicSoundEffectInstance const&) = delete; DIRECTX_TOOLKIT_API virtual ~DynamicSoundEffectInstance(); @@ -857,16 +804,11 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetPitch(float pitch); DIRECTX_TOOLKIT_API void __cdecl SetPan(float pan); - DIRECTX_TOOLKIT_API void __cdecl Apply3D( - const X3DAUDIO_LISTENER& listener, - const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); + DIRECTX_TOOLKIT_API void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); - DIRECTX_TOOLKIT_API void __cdecl SubmitBuffer( - _In_reads_bytes_(audioBytes) const uint8_t* pAudioData, size_t audioBytes); - DIRECTX_TOOLKIT_API void __cdecl SubmitBuffer( - _In_reads_bytes_(audioBytes) const uint8_t* pAudioData, - uint32_t offset, - size_t audioBytes); + DIRECTX_TOOLKIT_API void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, size_t audioBytes); + DIRECTX_TOOLKIT_API void __cdecl + SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, uint32_t offset, size_t audioBytes); DIRECTX_TOOLKIT_API SoundState __cdecl GetState() noexcept; @@ -898,9 +840,9 @@ namespace DirectX #endif DEFINE_ENUM_FLAG_OPERATORS(AUDIO_ENGINE_FLAGS) - DEFINE_ENUM_FLAG_OPERATORS(SOUND_EFFECT_INSTANCE_FLAGS) + DEFINE_ENUM_FLAG_OPERATORS(SOUND_EFFECT_INSTANCE_FLAGS) - #ifdef __clang__ - #pragma clang diagnostic pop - #endif -} +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +} // namespace DirectX diff --git a/Inc/BufferHelpers.h b/Inc/BufferHelpers.h index 94fceff8..4308a010 100644 --- a/Inc/BufferHelpers.h +++ b/Inc/BufferHelpers.h @@ -26,13 +26,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -41,120 +41,117 @@ #endif #endif - namespace DirectX { class ResourceUploadBatch; // Helpers for creating initialized Direct3D buffer resources. DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateStaticBuffer( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(count* stride) const void* ptr, - size_t count, - size_t stride, - D3D12_RESOURCE_STATES afterState, - _COM_Outptr_ ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; + HRESULT __cdecl CreateStaticBuffer(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(count* stride) const void* ptr, + size_t count, + size_t stride, + D3D12_RESOURCE_STATES afterState, + _COM_Outptr_ ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; template - HRESULT CreateStaticBuffer( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_(count) T const* data, - size_t count, - D3D12_RESOURCE_STATES afterState, - _COM_Outptr_ ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept + HRESULT CreateStaticBuffer(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_(count) T const* data, + size_t count, + D3D12_RESOURCE_STATES afterState, + _COM_Outptr_ ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept { return CreateStaticBuffer(device, resourceUpload, data, count, sizeof(T), afterState, pBuffer, resFlags); } template - HRESULT CreateStaticBuffer( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - T const& data, - D3D12_RESOURCE_STATES afterState, - _COM_Outptr_ ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept + HRESULT CreateStaticBuffer(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + T const& data, + D3D12_RESOURCE_STATES afterState, + _COM_Outptr_ ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept { - return CreateStaticBuffer(device, resourceUpload, data.data(), data.size(), sizeof(typename T::value_type), - afterState, pBuffer, resFlags); + return CreateStaticBuffer(device, + resourceUpload, + data.data(), + data.size(), + sizeof(typename T::value_type), + afterState, + pBuffer, + resFlags); } DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateUAVBuffer( - _In_ ID3D12Device* device, - uint64_t bufferSize, - _COM_Outptr_ ID3D12Resource** pBuffer, - D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_FLAGS additionalResFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; + HRESULT __cdecl CreateUAVBuffer(_In_ ID3D12Device* device, + uint64_t bufferSize, + _COM_Outptr_ ID3D12Resource** pBuffer, + D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAGS additionalResFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateUploadBuffer( - _In_ ID3D12Device* device, - _In_reads_bytes_opt_(count* stride) const void* ptr, - size_t count, - size_t stride, - _COM_Outptr_ ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; + HRESULT __cdecl CreateUploadBuffer(_In_ ID3D12Device* device, + _In_reads_bytes_opt_(count* stride) const void* ptr, + size_t count, + size_t stride, + _COM_Outptr_ ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; template - HRESULT CreateUploadBuffer( - _In_ ID3D12Device* device, - _In_reads_(count) T const* data, - size_t count, - _COM_Outptr_ ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept + HRESULT CreateUploadBuffer(_In_ ID3D12Device* device, + _In_reads_(count) T const* data, + size_t count, + _COM_Outptr_ ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept { return CreateUploadBuffer(device, data, count, sizeof(T), pBuffer, resFlags); } template - HRESULT CreateUploadBuffer( - _In_ ID3D12Device* device, - T const& data, - _COM_Outptr_ ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept + HRESULT CreateUploadBuffer(_In_ ID3D12Device* device, + T const& data, + _COM_Outptr_ ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept { - return CreateUploadBuffer(device, data.data(), data.size(), sizeof(typename T::value_type), - pBuffer, resFlags); + return CreateUploadBuffer(device, data.data(), data.size(), sizeof(typename T::value_type), pBuffer, resFlags); } // Helpers for creating texture from memory arrays. DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateTextureFromMemory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - size_t width, - DXGI_FORMAT format, - const D3D12_SUBRESOURCE_DATA& initData, - _COM_Outptr_ ID3D12Resource** texture, - D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; + HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + size_t width, + DXGI_FORMAT format, + const D3D12_SUBRESOURCE_DATA& initData, + _COM_Outptr_ ID3D12Resource** texture, + D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateTextureFromMemory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - size_t width, size_t height, - DXGI_FORMAT format, - const D3D12_SUBRESOURCE_DATA& initData, - _COM_Outptr_ ID3D12Resource** texture, - bool generateMips = false, - D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; + HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + size_t width, + size_t height, + DXGI_FORMAT format, + const D3D12_SUBRESOURCE_DATA& initData, + _COM_Outptr_ ID3D12Resource** texture, + bool generateMips = false, + D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateTextureFromMemory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - size_t width, size_t height, size_t depth, - DXGI_FORMAT format, - const D3D12_SUBRESOURCE_DATA& initData, - _COM_Outptr_ ID3D12Resource** texture, - D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; -} + HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + size_t width, + size_t height, + size_t depth, + DXGI_FORMAT format, + const D3D12_SUBRESOURCE_DATA& initData, + _COM_Outptr_ ID3D12Resource** texture, + D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept; +} // namespace DirectX diff --git a/Inc/CommonStates.h b/Inc/CommonStates.h index c2f2cd06..b521e5f5 100644 --- a/Inc/CommonStates.h +++ b/Inc/CommonStates.h @@ -26,13 +26,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -41,7 +41,6 @@ #endif #endif - namespace DirectX { inline namespace DX12 @@ -51,11 +50,11 @@ namespace DirectX public: DIRECTX_TOOLKIT_API explicit CommonStates(_In_ ID3D12Device* device); - DIRECTX_TOOLKIT_API CommonStates(CommonStates&&) noexcept; - DIRECTX_TOOLKIT_API CommonStates& operator = (CommonStates&&) noexcept; + DIRECTX_TOOLKIT_API CommonStates(CommonStates&&) noexcept; + DIRECTX_TOOLKIT_API CommonStates& operator=(CommonStates&&) noexcept; - CommonStates(const CommonStates&) = delete; - CommonStates& operator = (const CommonStates&) = delete; + CommonStates(const CommonStates&) = delete; + CommonStates& operator=(const CommonStates&) = delete; DIRECTX_TOOLKIT_API virtual ~CommonStates(); @@ -79,12 +78,24 @@ namespace DirectX DIRECTX_TOOLKIT_API static const D3D12_RASTERIZER_DESC Wireframe; // Static sampler states. - DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticPointWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept; - DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticPointClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept; - DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticLinearWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept; - DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticLinearClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept; - DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept; - DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept; + DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticPointWrap(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + unsigned int registerSpace = 0) noexcept; + DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticPointClamp(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + unsigned int registerSpace = 0) noexcept; + DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticLinearWrap(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + unsigned int registerSpace = 0) noexcept; + DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticLinearClamp(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + unsigned int registerSpace = 0) noexcept; + DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicWrap(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + unsigned int registerSpace = 0) noexcept; + DIRECTX_TOOLKIT_API static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicClamp(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + unsigned int registerSpace = 0) noexcept; // Sampler states. DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE PointWrap() const; @@ -113,5 +124,5 @@ namespace DirectX std::unique_ptr pImpl; }; - } -} + } // namespace DX12 +} // namespace DirectX diff --git a/Inc/DDSTextureLoader.h b/Inc/DDSTextureLoader.h index 9f2af9c2..27c9b2e3 100644 --- a/Inc/DDSTextureLoader.h +++ b/Inc/DDSTextureLoader.h @@ -34,13 +34,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -49,7 +49,6 @@ #endif #endif - namespace DirectX { class ResourceUploadBatch; @@ -58,11 +57,11 @@ namespace DirectX #define DDS_ALPHA_MODE_DEFINED enum DDS_ALPHA_MODE : uint32_t { - DDS_ALPHA_MODE_UNKNOWN = 0, - DDS_ALPHA_MODE_STRAIGHT = 1, + DDS_ALPHA_MODE_UNKNOWN = 0, + DDS_ALPHA_MODE_STRAIGHT = 1, DDS_ALPHA_MODE_PREMULTIPLIED = 2, - DDS_ALPHA_MODE_OPAQUE = 3, - DDS_ALPHA_MODE_CUSTOM = 4, + DDS_ALPHA_MODE_OPAQUE = 3, + DDS_ALPHA_MODE_CUSTOM = 4, }; #endif @@ -70,8 +69,8 @@ namespace DirectX { enum DDS_LOADER_FLAGS : uint32_t { - DDS_LOADER_DEFAULT = 0, - DDS_LOADER_FORCE_SRGB = 0x1, + DDS_LOADER_DEFAULT = 0, + DDS_LOADER_FORCE_SRGB = 0x1, DDS_LOADER_IGNORE_SRGB = 0x2, DDS_LOADER_MIP_AUTOGEN = 0x8, DDS_LOADER_MIP_RESERVE = 0x10, @@ -81,164 +80,185 @@ namespace DirectX // Standard version DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadDDSTextureFromMemory( - _In_ ID3D12Device* device, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - size_t ddsDataSize, - _Outptr_ ID3D12Resource** texture, - std::vector& subresources, - size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl LoadDDSTextureFromMemory(_In_ ID3D12Device* device, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + size_t ddsDataSize, + _Outptr_ ID3D12Resource** texture, + std::vector& subresources, + size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadDDSTextureFromFile( - _In_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& ddsData, - std::vector& subresources, - size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl LoadDDSTextureFromFile(_In_ ID3D12Device* device, + _In_z_ const wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& ddsData, + std::vector& subresources, + size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); - // Standard version with resource upload + // Standard version with resource upload DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - size_t ddsDataSize, - _Outptr_ ID3D12Resource** texture, - bool generateMipsIfMissing = false, - size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + size_t ddsDataSize, + _Outptr_ ID3D12Resource** texture, + bool generateMipsIfMissing = false, + size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFile( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - bool generateMipsIfMissing = false, - size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl CreateDDSTextureFromFile(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + bool generateMipsIfMissing = false, + size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); - // Extended version + // Extended version DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadDDSTextureFromMemoryEx( - _In_ ID3D12Device* device, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::vector& subresources, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl LoadDDSTextureFromMemoryEx(_In_ ID3D12Device* device, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::vector& subresources, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadDDSTextureFromFileEx( - _In_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& ddsData, - std::vector& subresources, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl LoadDDSTextureFromFileEx(_In_ ID3D12Device* device, + _In_z_ const wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& ddsData, + std::vector& subresources, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); - // Extended version with resource upload + // Extended version with resource upload DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemoryEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl CreateDDSTextureFromMemoryEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFileEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr); + HRESULT __cdecl CreateDDSTextureFromFileEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr); #ifdef __cpp_lib_byte DIRECTX_TOOLKIT_API - inline HRESULT __cdecl LoadDDSTextureFromMemory( - _In_ ID3D12Device* device, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - size_t ddsDataSize, - _Outptr_ ID3D12Resource** texture, - std::vector& subresources, - size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr) + inline HRESULT __cdecl LoadDDSTextureFromMemory(_In_ ID3D12Device* device, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + size_t ddsDataSize, + _Outptr_ ID3D12Resource** texture, + std::vector& subresources, + size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr) { - return LoadDDSTextureFromMemory(device, reinterpret_cast(ddsData), ddsDataSize, texture, subresources, maxsize, alphaMode, isCubeMap); + return LoadDDSTextureFromMemory(device, + reinterpret_cast(ddsData), + ddsDataSize, + texture, + subresources, + maxsize, + alphaMode, + isCubeMap); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - size_t ddsDataSize, - _Outptr_ ID3D12Resource** texture, - bool generateMipsIfMissing = false, - size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr) + inline HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + size_t ddsDataSize, + _Outptr_ ID3D12Resource** texture, + bool generateMipsIfMissing = false, + size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr) { - return CreateDDSTextureFromMemory(device, resourceUpload, reinterpret_cast(ddsData), ddsDataSize, texture, generateMipsIfMissing, maxsize, alphaMode, isCubeMap); + return CreateDDSTextureFromMemory(device, + resourceUpload, + reinterpret_cast(ddsData), + ddsDataSize, + texture, + generateMipsIfMissing, + maxsize, + alphaMode, + isCubeMap); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl LoadDDSTextureFromMemoryEx( - _In_ ID3D12Device* device, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::vector& subresources, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr) + inline HRESULT __cdecl LoadDDSTextureFromMemoryEx(_In_ ID3D12Device* device, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::vector& subresources, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr) { - return LoadDDSTextureFromMemoryEx(device, reinterpret_cast(ddsData), ddsDataSize, maxsize, resFlags, loadFlags, texture, subresources, alphaMode, isCubeMap); + return LoadDDSTextureFromMemoryEx(device, + reinterpret_cast(ddsData), + ddsDataSize, + maxsize, + resFlags, + loadFlags, + texture, + subresources, + alphaMode, + isCubeMap); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemoryEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _Out_opt_ bool* isCubeMap = nullptr) + inline HRESULT __cdecl CreateDDSTextureFromMemoryEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ bool* isCubeMap = nullptr) { - return CreateDDSTextureFromMemoryEx(device, resourceUpload, reinterpret_cast(ddsData), ddsDataSize, maxsize, resFlags, loadFlags, texture, alphaMode, isCubeMap); + return CreateDDSTextureFromMemoryEx(device, + resourceUpload, + reinterpret_cast(ddsData), + ddsDataSize, + maxsize, + resFlags, + loadFlags, + texture, + alphaMode, + isCubeMap); } #endif // __cpp_lib_byte @@ -255,4 +275,4 @@ namespace DirectX #ifdef __clang__ #pragma clang diagnostic pop #endif -} +} // namespace DirectX diff --git a/Inc/DescriptorHeap.h b/Inc/DescriptorHeap.h index a8b32c65..2c14f6cf 100644 --- a/Inc/DescriptorHeap.h +++ b/Inc/DescriptorHeap.h @@ -31,13 +31,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -46,57 +46,43 @@ #endif #endif - namespace DirectX { // A contiguous linear random-access descriptor heap class DescriptorHeap { public: - DIRECTX_TOOLKIT_API DescriptorHeap( - _In_ ID3D12DescriptorHeap* pExistingHeap); - DIRECTX_TOOLKIT_API DescriptorHeap( - _In_ ID3D12Device* device, - _In_ const D3D12_DESCRIPTOR_HEAP_DESC* pDesc); - DIRECTX_TOOLKIT_API DescriptorHeap( - _In_ ID3D12Device* device, - D3D12_DESCRIPTOR_HEAP_TYPE type, - D3D12_DESCRIPTOR_HEAP_FLAGS flags, - size_t count); - DIRECTX_TOOLKIT_API inline DescriptorHeap( - _In_ ID3D12Device* device, - size_t count) : - DescriptorHeap(device, - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, count) + DIRECTX_TOOLKIT_API DescriptorHeap(_In_ ID3D12DescriptorHeap* pExistingHeap); + DIRECTX_TOOLKIT_API DescriptorHeap(_In_ ID3D12Device* device, _In_ const D3D12_DESCRIPTOR_HEAP_DESC* pDesc); + DIRECTX_TOOLKIT_API + DescriptorHeap(_In_ ID3D12Device* device, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags, size_t count); + DIRECTX_TOOLKIT_API inline DescriptorHeap(_In_ ID3D12Device* device, size_t count) + : DescriptorHeap(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, count) {} - DescriptorHeap(DescriptorHeap&&) = default; + DescriptorHeap(DescriptorHeap&&) = default; DescriptorHeap& operator=(DescriptorHeap&&) = default; - DescriptorHeap(const DescriptorHeap&) = delete; + DescriptorHeap(const DescriptorHeap&) = delete; DescriptorHeap& operator=(const DescriptorHeap&) = delete; - DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE __cdecl WriteDescriptors( - _In_ ID3D12Device* device, - uint32_t offsetIntoHeap, - uint32_t totalDescriptorCount, - _In_reads_(descriptorRangeCount) const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, - _In_reads_(descriptorRangeCount) const uint32_t* pDescriptorRangeSizes, - uint32_t descriptorRangeCount); - - DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE __cdecl WriteDescriptors( - _In_ ID3D12Device* device, - uint32_t offsetIntoHeap, - _In_reads_(descriptorRangeCount) const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, - _In_reads_(descriptorRangeCount) const uint32_t* pDescriptorRangeSizes, - uint32_t descriptorRangeCount); - - DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE __cdecl WriteDescriptors( - _In_ ID3D12Device* device, - uint32_t offsetIntoHeap, - _In_reads_(descriptorCount) const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptors, - uint32_t descriptorCount); + DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE __cdecl WriteDescriptors(_In_ ID3D12Device* device, + uint32_t offsetIntoHeap, + uint32_t totalDescriptorCount, + _In_reads_(descriptorRangeCount) const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, + _In_reads_(descriptorRangeCount) const uint32_t* pDescriptorRangeSizes, + uint32_t descriptorRangeCount); + + DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE __cdecl WriteDescriptors(_In_ ID3D12Device* device, + uint32_t offsetIntoHeap, + _In_reads_(descriptorRangeCount) const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, + _In_reads_(descriptorRangeCount) const uint32_t* pDescriptorRangeSizes, + uint32_t descriptorRangeCount); + + DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE __cdecl WriteDescriptors(_In_ ID3D12Device* device, + uint32_t offsetIntoHeap, + _In_reads_(descriptorCount) const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptors, + uint32_t descriptorCount); DIRECTX_TOOLKIT_API inline D3D12_GPU_DESCRIPTOR_HANDLE GetFirstGpuHandle() const noexcept { @@ -138,40 +124,36 @@ namespace DirectX return handle; } - DIRECTX_TOOLKIT_API inline size_t Count() const noexcept { return m_desc.NumDescriptors; } - DIRECTX_TOOLKIT_API inline unsigned int Flags() const noexcept { return m_desc.Flags; } + DIRECTX_TOOLKIT_API inline size_t Count() const noexcept { return m_desc.NumDescriptors; } + DIRECTX_TOOLKIT_API inline unsigned int Flags() const noexcept { return m_desc.Flags; } DIRECTX_TOOLKIT_API inline D3D12_DESCRIPTOR_HEAP_TYPE Type() const noexcept { return m_desc.Type; } - DIRECTX_TOOLKIT_API inline uint32_t Increment() const noexcept { return m_increment; } - DIRECTX_TOOLKIT_API inline ID3D12DescriptorHeap* Heap() const noexcept { return m_pHeap.Get(); } + DIRECTX_TOOLKIT_API inline uint32_t Increment() const noexcept { return m_increment; } + DIRECTX_TOOLKIT_API inline ID3D12DescriptorHeap* Heap() const noexcept { return m_pHeap.Get(); } - DIRECTX_TOOLKIT_API static void __cdecl DefaultDesc( - _In_ D3D12_DESCRIPTOR_HEAP_TYPE type, - _Out_ D3D12_DESCRIPTOR_HEAP_DESC* pDesc) noexcept; + DIRECTX_TOOLKIT_API static void __cdecl DefaultDesc(_In_ D3D12_DESCRIPTOR_HEAP_TYPE type, + _Out_ D3D12_DESCRIPTOR_HEAP_DESC* pDesc) noexcept; private: void Create(_In_ ID3D12Device* pDevice, _In_ const D3D12_DESCRIPTOR_HEAP_DESC* pDesc); - Microsoft::WRL::ComPtr m_pHeap; - D3D12_DESCRIPTOR_HEAP_DESC m_desc; - D3D12_CPU_DESCRIPTOR_HANDLE m_hCPU; - D3D12_GPU_DESCRIPTOR_HANDLE m_hGPU; - uint32_t m_increment; + Microsoft::WRL::ComPtr m_pHeap; + D3D12_DESCRIPTOR_HEAP_DESC m_desc; + D3D12_CPU_DESCRIPTOR_HANDLE m_hCPU; + D3D12_GPU_DESCRIPTOR_HANDLE m_hGPU; + uint32_t m_increment; }; - // Helper class for dynamically allocating descriptor indices. // The pile is statically sized and will throw an exception if it becomes full. class DescriptorPile : public DescriptorHeap { public: - using IndexType = size_t; + using IndexType = size_t; static constexpr IndexType INVALID_INDEX = size_t(-1); - DIRECTX_TOOLKIT_API inline DescriptorPile( - _In_ ID3D12DescriptorHeap* pExistingHeap, - size_t reserve = 0) + DIRECTX_TOOLKIT_API inline DescriptorPile(_In_ ID3D12DescriptorHeap* pExistingHeap, size_t reserve = 0) : DescriptorHeap(pExistingHeap), - m_top(reserve) + m_top(reserve) { if (reserve > 0 && m_top >= Count()) { @@ -179,12 +161,11 @@ namespace DirectX } } - DIRECTX_TOOLKIT_API inline DescriptorPile( - _In_ ID3D12Device* device, - _In_ const D3D12_DESCRIPTOR_HEAP_DESC* pDesc, - size_t reserve = 0) + DIRECTX_TOOLKIT_API inline DescriptorPile(_In_ ID3D12Device* device, + _In_ const D3D12_DESCRIPTOR_HEAP_DESC* pDesc, + size_t reserve = 0) : DescriptorHeap(device, pDesc), - m_top(reserve) + m_top(reserve) { if (reserve > 0 && m_top >= Count()) { @@ -192,14 +173,13 @@ namespace DirectX } } - DIRECTX_TOOLKIT_API inline DescriptorPile( - _In_ ID3D12Device* device, - D3D12_DESCRIPTOR_HEAP_TYPE type, - D3D12_DESCRIPTOR_HEAP_FLAGS flags, - size_t capacity, - size_t reserve = 0) + DIRECTX_TOOLKIT_API inline DescriptorPile(_In_ ID3D12Device* device, + D3D12_DESCRIPTOR_HEAP_TYPE type, + D3D12_DESCRIPTOR_HEAP_FLAGS flags, + size_t capacity, + size_t reserve = 0) : DescriptorHeap(device, type, flags, capacity), - m_top(reserve) + m_top(reserve) { if (reserve > 0 && m_top >= Count()) { @@ -207,19 +187,14 @@ namespace DirectX } } - DIRECTX_TOOLKIT_API inline DescriptorPile( - _In_ ID3D12Device* device, - size_t count, - size_t reserve = 0) : - DescriptorPile(device, - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, count, reserve) + DIRECTX_TOOLKIT_API inline DescriptorPile(_In_ ID3D12Device* device, size_t count, size_t reserve = 0) + : DescriptorPile(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, count, reserve) {} - DescriptorPile(DescriptorPile&&) = default; + DescriptorPile(DescriptorPile&&) = default; DescriptorPile& operator=(DescriptorPile&&) = default; - DescriptorPile(const DescriptorPile&) = delete; + DescriptorPile(const DescriptorPile&) = delete; DescriptorPile& operator=(const DescriptorPile&) = delete; DIRECTX_TOOLKIT_API inline IndexType Allocate() @@ -235,4 +210,4 @@ namespace DirectX private: IndexType m_top; }; -} +} // namespace DirectX diff --git a/Inc/DirectXHelpers.h b/Inc/DirectXHelpers.h index 7bb576c6..c6fa2939 100644 --- a/Inc/DirectXHelpers.h +++ b/Inc/DirectXHelpers.h @@ -31,19 +31,19 @@ #include #if !defined(_GAMING_XBOX) && defined(_MSC_VER) -#pragma comment(lib,"dxguid.lib") +#pragma comment(lib, "dxguid.lib") #endif #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -57,7 +57,6 @@ #pragma warning(disable : 4251) #endif - // // The d3dx12.h header includes the following helper C++ classes and functions // CD3DX12_RECT @@ -142,93 +141,91 @@ namespace DirectX #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) constexpr D3D12_RESOURCE_STATES c_initialCopyTargetState = D3D12_RESOURCE_STATE_COPY_DEST; constexpr D3D12_RESOURCE_STATES c_initialReadTargetState = D3D12_RESOURCE_STATE_GENERIC_READ; - constexpr D3D12_RESOURCE_STATES c_initialUAVTargetState = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + constexpr D3D12_RESOURCE_STATES c_initialUAVTargetState = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; #else constexpr D3D12_RESOURCE_STATES c_initialCopyTargetState = D3D12_RESOURCE_STATE_COMMON; constexpr D3D12_RESOURCE_STATES c_initialReadTargetState = D3D12_RESOURCE_STATE_COMMON; - constexpr D3D12_RESOURCE_STATES c_initialUAVTargetState = D3D12_RESOURCE_STATE_COMMON; + constexpr D3D12_RESOURCE_STATES c_initialUAVTargetState = D3D12_RESOURCE_STATE_COMMON; #endif constexpr D3D12_CPU_DESCRIPTOR_HANDLE D3D12_CPU_DESCRIPTOR_HANDLE_ZERO = {}; // Creates a shader resource view from an arbitrary resource DIRECTX_TOOLKIT_API - void __cdecl CreateShaderResourceView( - _In_ ID3D12Device* device, - _In_ ID3D12Resource* tex, - D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, - bool isCubeMap = false); + void __cdecl CreateShaderResourceView(_In_ ID3D12Device* device, + _In_ ID3D12Resource* tex, + D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, + bool isCubeMap = false); - // Creates an unordered access view from an arbitrary resource + // Creates an unordered access view from an arbitrary resource DIRECTX_TOOLKIT_API - void __cdecl CreateUnorderedAccessView( - _In_ ID3D12Device* device, - _In_ ID3D12Resource* tex, - D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, - uint32_t mipLevel = 0); + void __cdecl CreateUnorderedAccessView(_In_ ID3D12Device* device, + _In_ ID3D12Resource* tex, + D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, + uint32_t mipLevel = 0); - // Creates an render target view from an arbitrary resource + // Creates an render target view from an arbitrary resource DIRECTX_TOOLKIT_API - void __cdecl CreateRenderTargetView( - _In_ ID3D12Device* device, - _In_ ID3D12Resource* tex, - D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor, - uint32_t mipLevel = 0); + void __cdecl CreateRenderTargetView(_In_ ID3D12Device* device, + _In_ ID3D12Resource* tex, + D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor, + uint32_t mipLevel = 0); - // Creates a shader resource view from a buffer resource + // Creates a shader resource view from a buffer resource DIRECTX_TOOLKIT_API - void __cdecl CreateBufferShaderResourceView( - _In_ ID3D12Device* device, - _In_ ID3D12Resource* buffer, - D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, - uint32_t stride = 0); + void __cdecl CreateBufferShaderResourceView(_In_ ID3D12Device* device, + _In_ ID3D12Resource* buffer, + D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, + uint32_t stride = 0); - // Creates a unordered access view from a buffer resource + // Creates a unordered access view from a buffer resource DIRECTX_TOOLKIT_API - void __cdecl CreateBufferUnorderedAccessView( - _In_ ID3D12Device* device, - _In_ ID3D12Resource* buffer, - D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, - uint32_t stride, - D3D12_BUFFER_UAV_FLAGS flag = D3D12_BUFFER_UAV_FLAG_NONE, - uint32_t counterOffset = 0, - _In_opt_ ID3D12Resource* counterResource = nullptr); - - // Shorthand for creating a root signature + void __cdecl CreateBufferUnorderedAccessView(_In_ ID3D12Device* device, + _In_ ID3D12Resource* buffer, + D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, + uint32_t stride, + D3D12_BUFFER_UAV_FLAGS flag = D3D12_BUFFER_UAV_FLAG_NONE, + uint32_t counterOffset = 0, + _In_opt_ ID3D12Resource* counterResource = nullptr); + + // Shorthand for creating a root signature DIRECTX_TOOLKIT_API - inline HRESULT CreateRootSignature( - _In_ ID3D12Device* device, - _In_ const D3D12_ROOT_SIGNATURE_DESC* rootSignatureDesc, - _Out_ ID3D12RootSignature** rootSignature) noexcept + inline HRESULT CreateRootSignature(_In_ ID3D12Device* device, + _In_ const D3D12_ROOT_SIGNATURE_DESC* rootSignatureDesc, + _Out_ ID3D12RootSignature** rootSignature) noexcept { if (!device || !rootSignatureDesc || !rootSignature) return E_INVALIDARG; Microsoft::WRL::ComPtr pSignature; Microsoft::WRL::ComPtr pError; - HRESULT hr = D3D12SerializeRootSignature(rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, pSignature.GetAddressOf(), pError.GetAddressOf()); + HRESULT hr = D3D12SerializeRootSignature(rootSignatureDesc, + D3D_ROOT_SIGNATURE_VERSION_1, + pSignature.GetAddressOf(), + pError.GetAddressOf()); if (SUCCEEDED(hr)) { - hr = device->CreateRootSignature(0, pSignature->GetBufferPointer(), pSignature->GetBufferSize(), - IID_GRAPHICS_PPV_ARGS(rootSignature) - ); + hr = device->CreateRootSignature(0, + pSignature->GetBufferPointer(), + pSignature->GetBufferSize(), + IID_GRAPHICS_PPV_ARGS(rootSignature)); } return hr; } // Helper for obtaining texture size DIRECTX_TOOLKIT_API - inline XMUINT2 GetTextureSize(_In_ ID3D12Resource* tex) noexcept + inline XMUINT2 GetTextureSize(_In_ ID3D12Resource* tex) noexcept { if (!tex) return XMUINT2(0, 0); - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const auto desc = tex->GetDesc(); - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *tex->GetDesc(&tmpDesc); - #endif + const auto& desc = *tex->GetDesc(&tmpDesc); +#endif return XMUINT2(static_cast(desc.Width), static_cast(desc.Height)); } @@ -242,10 +239,7 @@ namespace DirectX { PIXBeginEvent(pCommandList, 0, pFormat); } - ~ScopedPixEvent() - { - PIXEndEvent(mCommandList); - } + ~ScopedPixEvent() { PIXEndEvent(mCommandList); } private: ID3D12GraphicsCommandList* mCommandList; @@ -255,10 +249,10 @@ namespace DirectX // Helper sets a D3D resource name string (used by PIX and debug layer leak reporting). #if !defined(NO_D3D12_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) template - inline void SetDebugObjectName(_In_ ID3D12DeviceChild* resource, _In_z_ const char(&name)[TNameLength]) noexcept + inline void SetDebugObjectName(_In_ ID3D12DeviceChild* resource, _In_z_ const char (&name)[TNameLength]) noexcept { wchar_t wname[MAX_PATH]; - int result = MultiByteToWideChar(CP_UTF8, 0, name, TNameLength, wname, MAX_PATH); + int result = MultiByteToWideChar(CP_UTF8, 0, name, TNameLength, wname, MAX_PATH); if (result > 0) { resource->SetName(wname); @@ -266,27 +260,26 @@ namespace DirectX } template - inline void SetDebugObjectName(_In_ ID3D12DeviceChild* resource, _In_z_ const wchar_t(&name)[TNameLength]) noexcept + inline void SetDebugObjectName(_In_ ID3D12DeviceChild* resource, _In_z_ const wchar_t (&name)[TNameLength]) noexcept { resource->SetName(name); } #else template - inline void SetDebugObjectName(_In_ ID3D12DeviceChild*, _In_z_ const char(&)[TNameLength]) noexcept + inline void SetDebugObjectName(_In_ ID3D12DeviceChild*, _In_z_ const char (&)[TNameLength]) noexcept {} template - inline void SetDebugObjectName(_In_ ID3D12DeviceChild*, _In_z_ const wchar_t(&)[TNameLength]) noexcept + inline void SetDebugObjectName(_In_ ID3D12DeviceChild*, _In_z_ const wchar_t (&)[TNameLength]) noexcept {} #endif -// Helper for resource barrier. + // Helper for resource barrier. DIRECTX_TOOLKIT_API - inline void TransitionResource( - _In_ ID3D12GraphicsCommandList* commandList, - _In_ ID3D12Resource* resource, - D3D12_RESOURCE_STATES stateBefore, - D3D12_RESOURCE_STATES stateAfter) noexcept + inline void TransitionResource(_In_ ID3D12GraphicsCommandList* commandList, + _In_ ID3D12Resource* resource, + D3D12_RESOURCE_STATES stateBefore, + D3D12_RESOURCE_STATES stateAfter) noexcept { assert(commandList != nullptr); assert(resource != nullptr); @@ -295,11 +288,11 @@ namespace DirectX return; D3D12_RESOURCE_BARRIER desc = {}; - desc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - desc.Transition.pResource = resource; + desc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + desc.Transition.pResource = resource; desc.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; desc.Transition.StateBefore = stateBefore; - desc.Transition.StateAfter = stateAfter; + desc.Transition.StateAfter = stateAfter; commandList->ResourceBarrier(1, &desc); } @@ -308,11 +301,9 @@ namespace DirectX class DIRECTX_TOOLKIT_API ScopedBarrier { public: - ScopedBarrier( - _In_ ID3D12GraphicsCommandList* commandList, - std::initializer_list barriers) noexcept(false) + ScopedBarrier(_In_ ID3D12GraphicsCommandList* commandList, std::initializer_list barriers) noexcept(false) : mCommandList(commandList), - mBarriers(barriers) + mBarriers(barriers) { assert(mBarriers.size() <= UINT32_MAX); @@ -320,12 +311,11 @@ namespace DirectX mCommandList->ResourceBarrier(static_cast(mBarriers.size()), mBarriers.data()); } - ScopedBarrier( - _In_ ID3D12GraphicsCommandList* commandList, - _In_reads_(count) const D3D12_RESOURCE_BARRIER *barriers, - size_t count) noexcept(false) + ScopedBarrier(_In_ ID3D12GraphicsCommandList* commandList, + _In_reads_(count) const D3D12_RESOURCE_BARRIER* barriers, + size_t count) noexcept(false) : mCommandList(commandList), - mBarriers(barriers, barriers + count) + mBarriers(barriers, barriers + count) { assert(count <= UINT32_MAX); @@ -334,11 +324,9 @@ namespace DirectX } template - ScopedBarrier( - _In_ ID3D12GraphicsCommandList* commandList, - const D3D12_RESOURCE_BARRIER(&barriers)[TBarrierLength]) noexcept(false) + ScopedBarrier(_In_ ID3D12GraphicsCommandList* commandList, const D3D12_RESOURCE_BARRIER (&barriers)[TBarrierLength]) noexcept(false) : mCommandList(commandList), - mBarriers(barriers, barriers + TBarrierLength) + mBarriers(barriers, barriers + TBarrierLength) { assert(TBarrierLength <= UINT32_MAX); @@ -346,11 +334,11 @@ namespace DirectX mCommandList->ResourceBarrier(static_cast(mBarriers.size()), mBarriers.data()); } - ScopedBarrier(ScopedBarrier&&) = default; - ScopedBarrier& operator= (ScopedBarrier&&) = default; + ScopedBarrier(ScopedBarrier&&) = default; + ScopedBarrier& operator=(ScopedBarrier&&) = default; - ScopedBarrier(ScopedBarrier const&) = delete; - ScopedBarrier& operator= (ScopedBarrier const&) = delete; + ScopedBarrier(ScopedBarrier const&) = delete; + ScopedBarrier& operator=(ScopedBarrier const&) = delete; ~ScopedBarrier() { @@ -365,7 +353,7 @@ namespace DirectX } private: - ID3D12GraphicsCommandList* mCommandList; + ID3D12GraphicsCommandList* mCommandList; std::vector mBarriers; }; @@ -373,7 +361,10 @@ namespace DirectX { // Helper to check for power-of-2 template - constexpr bool IsPowerOf2(T x) noexcept { return ((x != 0) && !(x & (x - 1))); } + constexpr bool IsPowerOf2(T x) noexcept + { + return ((x != 0) && !(x & (x - 1))); + } // Helpers for aligning values by a power of 2 template @@ -399,8 +390,8 @@ namespace DirectX } return size; } - } -} + } // namespace DX12 +} // namespace DirectX #if defined(DIRECTX_TOOLKIT_IMPORT) && defined(_MSC_VER) #pragma warning(pop) diff --git a/Inc/EffectPipelineStateDescription.h b/Inc/EffectPipelineStateDescription.h index e1c1a716..682fdf95 100644 --- a/Inc/EffectPipelineStateDescription.h +++ b/Inc/EffectPipelineStateDescription.h @@ -30,13 +30,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -45,95 +45,91 @@ #endif #endif - namespace DirectX { // Pipeline state information for creating effects. struct DIRECTX_TOOLKIT_API EffectPipelineStateDescription { - EffectPipelineStateDescription( - _In_opt_ const D3D12_INPUT_LAYOUT_DESC* iinputLayout, - const D3D12_BLEND_DESC& blend, - const D3D12_DEPTH_STENCIL_DESC& depthStencil, - const D3D12_RASTERIZER_DESC& rasterizer, - const RenderTargetState& renderTarget, - D3D12_PRIMITIVE_TOPOLOGY_TYPE iprimitiveTopology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + EffectPipelineStateDescription(_In_opt_ const D3D12_INPUT_LAYOUT_DESC* iinputLayout, + const D3D12_BLEND_DESC& blend, + const D3D12_DEPTH_STENCIL_DESC& depthStencil, + const D3D12_RASTERIZER_DESC& rasterizer, + const RenderTargetState& renderTarget, + D3D12_PRIMITIVE_TOPOLOGY_TYPE iprimitiveTopology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, D3D12_INDEX_BUFFER_STRIP_CUT_VALUE istripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED) noexcept - : - inputLayout{}, - blendDesc(blend), - depthStencilDesc(depthStencil), - rasterizerDesc(rasterizer), - renderTargetState(renderTarget), - primitiveTopology(iprimitiveTopology), - stripCutValue(istripCutValue) + : inputLayout{}, + blendDesc(blend), + depthStencilDesc(depthStencil), + rasterizerDesc(rasterizer), + renderTargetState(renderTarget), + primitiveTopology(iprimitiveTopology), + stripCutValue(istripCutValue) { if (iinputLayout) this->inputLayout = *iinputLayout; } - EffectPipelineStateDescription(const EffectPipelineStateDescription&) = default; + EffectPipelineStateDescription(const EffectPipelineStateDescription&) = default; EffectPipelineStateDescription& operator=(const EffectPipelineStateDescription&) = default; - EffectPipelineStateDescription(EffectPipelineStateDescription&&) = default; + EffectPipelineStateDescription(EffectPipelineStateDescription&&) = default; EffectPipelineStateDescription& operator=(EffectPipelineStateDescription&&) = default; - void CreatePipelineState( - _In_ ID3D12Device* device, - _In_ ID3D12RootSignature* rootSignature, - const D3D12_SHADER_BYTECODE& vertexShader, - const D3D12_SHADER_BYTECODE& pixelShader, - _Outptr_ ID3D12PipelineState** pPipelineState) const; + void CreatePipelineState(_In_ ID3D12Device* device, + _In_ ID3D12RootSignature* rootSignature, + const D3D12_SHADER_BYTECODE& vertexShader, + const D3D12_SHADER_BYTECODE& pixelShader, + _Outptr_ ID3D12PipelineState** pPipelineState) const; - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) D3D12_GRAPHICS_PIPELINE_STATE_DESC GetDesc() const noexcept { D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.BlendState = blendDesc; - psoDesc.SampleMask = renderTargetState.sampleMask; - psoDesc.RasterizerState = rasterizerDesc; - psoDesc.DepthStencilState = depthStencilDesc; - psoDesc.InputLayout = inputLayout; - psoDesc.IBStripCutValue = stripCutValue; - psoDesc.PrimitiveTopologyType = primitiveTopology; - psoDesc.NumRenderTargets = renderTargetState.numRenderTargets; + psoDesc.BlendState = blendDesc; + psoDesc.SampleMask = renderTargetState.sampleMask; + psoDesc.RasterizerState = rasterizerDesc; + psoDesc.DepthStencilState = depthStencilDesc; + psoDesc.InputLayout = inputLayout; + psoDesc.IBStripCutValue = stripCutValue; + psoDesc.PrimitiveTopologyType = primitiveTopology; + psoDesc.NumRenderTargets = renderTargetState.numRenderTargets; memcpy(psoDesc.RTVFormats, renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); - psoDesc.DSVFormat = renderTargetState.dsvFormat; + psoDesc.DSVFormat = renderTargetState.dsvFormat; psoDesc.SampleDesc = renderTargetState.sampleDesc; - psoDesc.NodeMask = renderTargetState.nodeMask; + psoDesc.NodeMask = renderTargetState.nodeMask; return psoDesc; } - #else +#else D3D12_GRAPHICS_PIPELINE_STATE_DESC* GetDesc(_Out_ D3D12_GRAPHICS_PIPELINE_STATE_DESC* psoDesc) const noexcept { if (!psoDesc) return nullptr; - *psoDesc = {}; - psoDesc->BlendState = blendDesc; - psoDesc->SampleMask = renderTargetState.sampleMask; - psoDesc->RasterizerState = rasterizerDesc; - psoDesc->DepthStencilState = depthStencilDesc; - psoDesc->InputLayout = inputLayout; - psoDesc->IBStripCutValue = stripCutValue; + *psoDesc = {}; + psoDesc->BlendState = blendDesc; + psoDesc->SampleMask = renderTargetState.sampleMask; + psoDesc->RasterizerState = rasterizerDesc; + psoDesc->DepthStencilState = depthStencilDesc; + psoDesc->InputLayout = inputLayout; + psoDesc->IBStripCutValue = stripCutValue; psoDesc->PrimitiveTopologyType = primitiveTopology; - psoDesc->NumRenderTargets = renderTargetState.numRenderTargets; + psoDesc->NumRenderTargets = renderTargetState.numRenderTargets; memcpy(psoDesc->RTVFormats, renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); - psoDesc->DSVFormat = renderTargetState.dsvFormat; + psoDesc->DSVFormat = renderTargetState.dsvFormat; psoDesc->SampleDesc = renderTargetState.sampleDesc; - psoDesc->NodeMask = renderTargetState.nodeMask; + psoDesc->NodeMask = renderTargetState.nodeMask; return psoDesc; } - #endif +#endif uint32_t ComputeHash() const noexcept; - D3D12_INPUT_LAYOUT_DESC inputLayout; - D3D12_BLEND_DESC blendDesc; - D3D12_DEPTH_STENCIL_DESC depthStencilDesc; - D3D12_RASTERIZER_DESC rasterizerDesc; - RenderTargetState renderTargetState; - D3D12_PRIMITIVE_TOPOLOGY_TYPE primitiveTopology; - D3D12_INDEX_BUFFER_STRIP_CUT_VALUE stripCutValue; + D3D12_INPUT_LAYOUT_DESC inputLayout; + D3D12_BLEND_DESC blendDesc; + D3D12_DEPTH_STENCIL_DESC depthStencilDesc; + D3D12_RASTERIZER_DESC rasterizerDesc; + RenderTargetState renderTargetState; + D3D12_PRIMITIVE_TOPOLOGY_TYPE primitiveTopology; + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE stripCutValue; }; -} +} // namespace DirectX diff --git a/Inc/Effects.h b/Inc/Effects.h index 49929e62..1409e84a 100644 --- a/Inc/Effects.h +++ b/Inc/Effects.h @@ -36,13 +36,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -56,7 +56,6 @@ #pragma warning(disable : 4251 4275) #endif - namespace DirectX { class DescriptorHeap; @@ -71,53 +70,51 @@ namespace DirectX public: virtual ~IEffect() = default; - IEffect(const IEffect&) = delete; + IEffect(const IEffect&) = delete; IEffect& operator=(const IEffect&) = delete; virtual void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) = 0; protected: - IEffect() = default; - IEffect(IEffect&&) = default; + IEffect() = default; + IEffect(IEffect&&) = default; IEffect& operator=(IEffect&&) = default; }; - // Abstract interface for effects with world, view, and projection matrices. class DIRECTX_TOOLKIT_API IEffectMatrices { public: virtual ~IEffectMatrices() = default; - IEffectMatrices(const IEffectMatrices&) = delete; + IEffectMatrices(const IEffectMatrices&) = delete; IEffectMatrices& operator=(const IEffectMatrices&) = delete; - virtual void XM_CALLCONV SetWorld(FXMMATRIX value) = 0; - virtual void XM_CALLCONV SetView(FXMMATRIX value) = 0; + virtual void XM_CALLCONV SetWorld(FXMMATRIX value) = 0; + virtual void XM_CALLCONV SetView(FXMMATRIX value) = 0; virtual void XM_CALLCONV SetProjection(FXMMATRIX value) = 0; virtual void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection); protected: - IEffectMatrices() = default; - IEffectMatrices(IEffectMatrices&&) = default; + IEffectMatrices() = default; + IEffectMatrices(IEffectMatrices&&) = default; IEffectMatrices& operator=(IEffectMatrices&&) = default; }; - // Abstract interface for effects which support directional lighting. class DIRECTX_TOOLKIT_API IEffectLights { public: virtual ~IEffectLights() = default; - IEffectLights(const IEffectLights&) = delete; + IEffectLights(const IEffectLights&) = delete; IEffectLights& operator=(const IEffectLights&) = delete; virtual void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) = 0; - virtual void __cdecl SetLightEnabled(int whichLight, bool value) = 0; - virtual void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) = 0; - virtual void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) = 0; + virtual void __cdecl SetLightEnabled(int whichLight, bool value) = 0; + virtual void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) = 0; + virtual void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) = 0; virtual void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) = 0; virtual void __cdecl EnableDefaultLighting() = 0; @@ -125,66 +122,63 @@ namespace DirectX static constexpr int MaxDirectionalLights = 3; protected: - IEffectLights() = default; - IEffectLights(IEffectLights&&) = default; + IEffectLights() = default; + IEffectLights(IEffectLights&&) = default; IEffectLights& operator=(IEffectLights&&) = default; }; - // Abstract interface for effects which support fog. class DIRECTX_TOOLKIT_API IEffectFog { public: virtual ~IEffectFog() = default; - IEffectFog(const IEffectFog&) = delete; + IEffectFog(const IEffectFog&) = delete; IEffectFog& operator=(const IEffectFog&) = delete; - virtual void __cdecl SetFogStart(float value) = 0; - virtual void __cdecl SetFogEnd(float value) = 0; + virtual void __cdecl SetFogStart(float value) = 0; + virtual void __cdecl SetFogEnd(float value) = 0; virtual void XM_CALLCONV SetFogColor(FXMVECTOR value) = 0; protected: - IEffectFog() = default; - IEffectFog(IEffectFog&&) = default; + IEffectFog() = default; + IEffectFog(IEffectFog&&) = default; IEffectFog& operator=(IEffectFog&&) = default; }; - // Abstract interface for effects which support skinning class DIRECTX_TOOLKIT_API IEffectSkinning { public: virtual ~IEffectSkinning() = default; - IEffectSkinning(const IEffectSkinning&) = delete; + IEffectSkinning(const IEffectSkinning&) = delete; IEffectSkinning& operator=(const IEffectSkinning&) = delete; virtual void __cdecl SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) = 0; - virtual void __cdecl ResetBoneTransforms() = 0; + virtual void __cdecl ResetBoneTransforms() = 0; static constexpr int MaxBones = 72; protected: - IEffectSkinning() = default; - IEffectSkinning(IEffectSkinning&&) = default; + IEffectSkinning() = default; + IEffectSkinning(IEffectSkinning&&) = default; IEffectSkinning& operator=(IEffectSkinning&&) = default; }; - //------------------------------------------------------------------------------ namespace EffectFlags { - constexpr uint32_t None = 0x00; - constexpr uint32_t Fog = 0x01; + constexpr uint32_t None = 0x00; + constexpr uint32_t Fog = 0x01; constexpr uint32_t Lighting = 0x02; constexpr uint32_t PerPixelLighting = 0x04 | Lighting; // per pixel lighting implies lighting enabled constexpr uint32_t VertexColor = 0x08; - constexpr uint32_t Texture = 0x10; - constexpr uint32_t Instancing = 0x20; + constexpr uint32_t Texture = 0x10; + constexpr uint32_t Instancing = 0x20; constexpr uint32_t Specular = 0x100; // enable optional specular/specularMap feature @@ -200,24 +194,21 @@ namespace DirectX constexpr uint32_t BiasedVertexNormals = 0x10000; // compressed vertex normals need x2 bias - } - + } // namespace EffectFlags //------------------------------------------------------------------------------ // Built-in shader supports optional texture mapping, vertex coloring, directional lighting, and fog. class BasicEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog { public: - DIRECTX_TOOLKIT_API BasicEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription); + DIRECTX_TOOLKIT_API + BasicEffect(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription); - DIRECTX_TOOLKIT_API BasicEffect(BasicEffect&&) noexcept; - DIRECTX_TOOLKIT_API BasicEffect& operator= (BasicEffect&&) noexcept; + DIRECTX_TOOLKIT_API BasicEffect(BasicEffect&&) noexcept; + DIRECTX_TOOLKIT_API BasicEffect& operator=(BasicEffect&&) noexcept; - BasicEffect(BasicEffect const&) = delete; - BasicEffect& operator= (BasicEffect const&) = delete; + BasicEffect(BasicEffect const&) = delete; + BasicEffect& operator=(BasicEffect const&) = delete; DIRECTX_TOOLKIT_API ~BasicEffect() override; @@ -234,15 +225,15 @@ namespace DirectX DIRECTX_TOOLKIT_API void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetEmissiveColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetSpecularColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetSpecularPower(float value); - DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetSpecularPower(float value); + DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); // Light settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; - DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override; @@ -250,12 +241,13 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetFogColor(FXMVECTOR value) override; // Texture setting. - DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); private: // Private implementation. @@ -264,22 +256,20 @@ namespace DirectX std::unique_ptr pImpl; }; - // Built-in shader supports per-pixel alpha testing. class AlphaTestEffect : public IEffect, public IEffectMatrices, public IEffectFog { public: - DIRECTX_TOOLKIT_API AlphaTestEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - D3D12_COMPARISON_FUNC alphaFunction = D3D12_COMPARISON_FUNC_GREATER); + DIRECTX_TOOLKIT_API AlphaTestEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + D3D12_COMPARISON_FUNC alphaFunction = D3D12_COMPARISON_FUNC_GREATER); - DIRECTX_TOOLKIT_API AlphaTestEffect(AlphaTestEffect&&) noexcept; - DIRECTX_TOOLKIT_API AlphaTestEffect& operator= (AlphaTestEffect&&) noexcept; + DIRECTX_TOOLKIT_API AlphaTestEffect(AlphaTestEffect&&) noexcept; + DIRECTX_TOOLKIT_API AlphaTestEffect& operator=(AlphaTestEffect&&) noexcept; - AlphaTestEffect(AlphaTestEffect const&) = delete; - AlphaTestEffect& operator= (AlphaTestEffect const&) = delete; + AlphaTestEffect(AlphaTestEffect const&) = delete; + AlphaTestEffect& operator=(AlphaTestEffect const&) = delete; DIRECTX_TOOLKIT_API ~AlphaTestEffect() override; @@ -294,16 +284,17 @@ namespace DirectX // Material settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetFogColor(FXMVECTOR value) override; // Texture setting. - DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); // Alpha test settings. DIRECTX_TOOLKIT_API void __cdecl SetReferenceAlpha(int value); @@ -315,21 +306,18 @@ namespace DirectX std::unique_ptr pImpl; }; - // Built-in shader supports two layer multitexturing (eg. for lightmaps or detail textures). class DualTextureEffect : public IEffect, public IEffectMatrices, public IEffectFog { public: - DIRECTX_TOOLKIT_API DualTextureEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription); + DIRECTX_TOOLKIT_API + DualTextureEffect(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription); - DIRECTX_TOOLKIT_API DualTextureEffect(DualTextureEffect&&) noexcept; - DIRECTX_TOOLKIT_API DualTextureEffect& operator= (DualTextureEffect&&) noexcept; + DIRECTX_TOOLKIT_API DualTextureEffect(DualTextureEffect&&) noexcept; + DIRECTX_TOOLKIT_API DualTextureEffect& operator=(DualTextureEffect&&) noexcept; - DualTextureEffect(DualTextureEffect const&) = delete; - DualTextureEffect& operator= (DualTextureEffect const&) = delete; + DualTextureEffect(DualTextureEffect const&) = delete; + DualTextureEffect& operator=(DualTextureEffect const&) = delete; DIRECTX_TOOLKIT_API ~DualTextureEffect() override; @@ -344,17 +332,19 @@ namespace DirectX // Material settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetFogColor(FXMVECTOR value) override; // Texture settings. - DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); - DIRECTX_TOOLKIT_API void __cdecl SetTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); private: // Private implementation. @@ -363,29 +353,27 @@ namespace DirectX std::unique_ptr pImpl; }; - // Built-in shader supports cubic environment mapping. class EnvironmentMapEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog { public: enum Mapping : uint32_t { - Mapping_Cube = 0, // Cubic environment map - Mapping_Sphere, // Spherical environment map - Mapping_DualParabola, // Dual-parabola environment map (requires Feature Level 10.0) + Mapping_Cube = 0, // Cubic environment map + Mapping_Sphere, // Spherical environment map + Mapping_DualParabola, // Dual-parabola environment map (requires Feature Level 10.0) }; - DIRECTX_TOOLKIT_API EnvironmentMapEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - Mapping mapping = Mapping_Cube); + DIRECTX_TOOLKIT_API EnvironmentMapEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + Mapping mapping = Mapping_Cube); - DIRECTX_TOOLKIT_API EnvironmentMapEffect(EnvironmentMapEffect&&) noexcept; - DIRECTX_TOOLKIT_API EnvironmentMapEffect& operator= (EnvironmentMapEffect&&) noexcept; + DIRECTX_TOOLKIT_API EnvironmentMapEffect(EnvironmentMapEffect&&) noexcept; + DIRECTX_TOOLKIT_API EnvironmentMapEffect& operator=(EnvironmentMapEffect&&) noexcept; - EnvironmentMapEffect(EnvironmentMapEffect const&) = delete; - EnvironmentMapEffect& operator= (EnvironmentMapEffect const&) = delete; + EnvironmentMapEffect(EnvironmentMapEffect const&) = delete; + EnvironmentMapEffect& operator=(EnvironmentMapEffect const&) = delete; DIRECTX_TOOLKIT_API ~EnvironmentMapEffect() override; @@ -401,21 +389,21 @@ namespace DirectX // Material settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetEmissiveColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); // Light settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; - DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetFogColor(FXMVECTOR value) override; // Texture setting. @@ -425,7 +413,7 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetEnvironmentMap(D3D12_GPU_DESCRIPTOR_HANDLE texture, D3D12_GPU_DESCRIPTOR_HANDLE sampler); DIRECTX_TOOLKIT_API void __cdecl SetEnvironmentMapAmount(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetEnvironmentMapSpecular(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetFresnelFactor(float value); + DIRECTX_TOOLKIT_API void __cdecl SetFresnelFactor(float value); private: // Private implementation. @@ -437,21 +425,18 @@ namespace DirectX DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override; }; - // Built-in shader supports skinned animation. class SkinnedEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog, public IEffectSkinning { public: - DIRECTX_TOOLKIT_API SkinnedEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription); + DIRECTX_TOOLKIT_API + SkinnedEffect(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription); - DIRECTX_TOOLKIT_API SkinnedEffect(SkinnedEffect&&) noexcept; - DIRECTX_TOOLKIT_API SkinnedEffect& operator= (SkinnedEffect&&) noexcept; + DIRECTX_TOOLKIT_API SkinnedEffect(SkinnedEffect&&) noexcept; + DIRECTX_TOOLKIT_API SkinnedEffect& operator=(SkinnedEffect&&) noexcept; - SkinnedEffect(SkinnedEffect const&) = delete; - SkinnedEffect& operator= (SkinnedEffect const&) = delete; + SkinnedEffect(SkinnedEffect const&) = delete; + SkinnedEffect& operator=(SkinnedEffect const&) = delete; DIRECTX_TOOLKIT_API ~SkinnedEffect() override; @@ -468,15 +453,15 @@ namespace DirectX DIRECTX_TOOLKIT_API void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetEmissiveColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetSpecularColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetSpecularPower(float value); - DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetSpecularPower(float value); + DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); // Light settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; - DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override; @@ -484,12 +469,13 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetFogColor(FXMVECTOR value) override; // Texture setting. - DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); // Animation settings. DIRECTX_TOOLKIT_API void __cdecl SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) override; @@ -502,24 +488,22 @@ namespace DirectX std::unique_ptr pImpl; }; - //------------------------------------------------------------------------------ // Built-in shader extends BasicEffect with normal map and optional specular map class NormalMapEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog { public: - DIRECTX_TOOLKIT_API inline NormalMapEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) : - NormalMapEffect(device, effectFlags, pipelineDescription, false) + DIRECTX_TOOLKIT_API inline NormalMapEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription) + : NormalMapEffect(device, effectFlags, pipelineDescription, false) {} - DIRECTX_TOOLKIT_API NormalMapEffect(NormalMapEffect&&) noexcept; - DIRECTX_TOOLKIT_API NormalMapEffect& operator= (NormalMapEffect&&) noexcept; + DIRECTX_TOOLKIT_API NormalMapEffect(NormalMapEffect&&) noexcept; + DIRECTX_TOOLKIT_API NormalMapEffect& operator=(NormalMapEffect&&) noexcept; - NormalMapEffect(NormalMapEffect const&) = delete; - NormalMapEffect& operator= (NormalMapEffect const&) = delete; + NormalMapEffect(NormalMapEffect const&) = delete; + NormalMapEffect& operator=(NormalMapEffect const&) = delete; DIRECTX_TOOLKIT_API ~NormalMapEffect() override; @@ -536,15 +520,15 @@ namespace DirectX DIRECTX_TOOLKIT_API void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetEmissiveColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetSpecularColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetSpecularPower(float value); - DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetSpecularPower(float value); + DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); // Light settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; - DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override; @@ -552,12 +536,13 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetFogColor(FXMVECTOR value) override; // Texture settings - albedo, normal and specular intensity. - DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); DIRECTX_TOOLKIT_API void __cdecl SetNormalTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor); DIRECTX_TOOLKIT_API void __cdecl SetSpecularTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor); @@ -567,28 +552,26 @@ namespace DirectX std::unique_ptr pImpl; - DIRECTX_TOOLKIT_API NormalMapEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - bool skinningEnabled); + DIRECTX_TOOLKIT_API NormalMapEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + bool skinningEnabled); }; class DIRECTX_TOOLKIT_API SkinnedNormalMapEffect : public NormalMapEffect, public IEffectSkinning { public: - SkinnedNormalMapEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) : - NormalMapEffect(device, effectFlags, pipelineDescription, true) + SkinnedNormalMapEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription) + : NormalMapEffect(device, effectFlags, pipelineDescription, true) {} - SkinnedNormalMapEffect(SkinnedNormalMapEffect&&) = default; - SkinnedNormalMapEffect& operator= (SkinnedNormalMapEffect&&) = default; + SkinnedNormalMapEffect(SkinnedNormalMapEffect&&) = default; + SkinnedNormalMapEffect& operator=(SkinnedNormalMapEffect&&) = default; - SkinnedNormalMapEffect(SkinnedNormalMapEffect const&) = delete; - SkinnedNormalMapEffect& operator= (SkinnedNormalMapEffect const&) = delete; + SkinnedNormalMapEffect(SkinnedNormalMapEffect const&) = delete; + SkinnedNormalMapEffect& operator=(SkinnedNormalMapEffect const&) = delete; ~SkinnedNormalMapEffect() override; @@ -597,24 +580,22 @@ namespace DirectX void __cdecl ResetBoneTransforms() override; }; - //------------------------------------------------------------------------------ // Built-in shader for Physically-Based Rendering (Roughness/Metalness) with Image-based lighting class PBREffect : public IEffect, public IEffectMatrices, public IEffectLights { public: - DIRECTX_TOOLKIT_API inline PBREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) : - PBREffect(device, effectFlags, pipelineDescription, false) + DIRECTX_TOOLKIT_API inline PBREffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription) + : PBREffect(device, effectFlags, pipelineDescription, false) {} - DIRECTX_TOOLKIT_API PBREffect(PBREffect&&) noexcept; - DIRECTX_TOOLKIT_API PBREffect& operator= (PBREffect&&) noexcept; + DIRECTX_TOOLKIT_API PBREffect(PBREffect&&) noexcept; + DIRECTX_TOOLKIT_API PBREffect& operator=(PBREffect&&) noexcept; - PBREffect(PBREffect const&) = delete; - PBREffect& operator= (PBREffect const&) = delete; + PBREffect(PBREffect const&) = delete; + PBREffect& operator=(PBREffect const&) = delete; DIRECTX_TOOLKIT_API ~PBREffect() override; @@ -628,36 +609,35 @@ namespace DirectX DIRECTX_TOOLKIT_API void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override; // Light settings. - DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // PBR Settings. - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetConstantAlbedo(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetConstantMetallic(float value); - DIRECTX_TOOLKIT_API void __cdecl SetConstantRoughness(float value); + DIRECTX_TOOLKIT_API void __cdecl SetConstantMetallic(float value); + DIRECTX_TOOLKIT_API void __cdecl SetConstantRoughness(float value); // Texture settings. - DIRECTX_TOOLKIT_API void __cdecl SetAlbedoTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetAlbedoTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); DIRECTX_TOOLKIT_API void __cdecl SetNormalTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor); DIRECTX_TOOLKIT_API void __cdecl SetRMATexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor); DIRECTX_TOOLKIT_API void __cdecl SetEmissiveTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor); - DIRECTX_TOOLKIT_API void __cdecl SetSurfaceTextures( - D3D12_GPU_DESCRIPTOR_HANDLE albedo, - D3D12_GPU_DESCRIPTOR_HANDLE normal, - D3D12_GPU_DESCRIPTOR_HANDLE roughnessMetallicAmbientOcclusion, - D3D12_GPU_DESCRIPTOR_HANDLE sampler); + DIRECTX_TOOLKIT_API void __cdecl SetSurfaceTextures(D3D12_GPU_DESCRIPTOR_HANDLE albedo, + D3D12_GPU_DESCRIPTOR_HANDLE normal, + D3D12_GPU_DESCRIPTOR_HANDLE roughnessMetallicAmbientOcclusion, + D3D12_GPU_DESCRIPTOR_HANDLE sampler); - DIRECTX_TOOLKIT_API void __cdecl SetIBLTextures( - D3D12_GPU_DESCRIPTOR_HANDLE radiance, - int numRadianceMips, - D3D12_GPU_DESCRIPTOR_HANDLE irradiance, - D3D12_GPU_DESCRIPTOR_HANDLE sampler); + DIRECTX_TOOLKIT_API void __cdecl SetIBLTextures(D3D12_GPU_DESCRIPTOR_HANDLE radiance, + int numRadianceMips, + D3D12_GPU_DESCRIPTOR_HANDLE irradiance, + D3D12_GPU_DESCRIPTOR_HANDLE sampler); // Render target size, required for velocity buffer output. DIRECTX_TOOLKIT_API void __cdecl SetRenderTargetSizeInPixels(int width, int height); @@ -668,11 +648,10 @@ namespace DirectX std::unique_ptr pImpl; - DIRECTX_TOOLKIT_API PBREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - bool skinningEnabled); + DIRECTX_TOOLKIT_API PBREffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + bool skinningEnabled); private: // Unsupported interface methods. @@ -683,18 +662,15 @@ namespace DirectX class DIRECTX_TOOLKIT_API SkinnedPBREffect : public PBREffect, public IEffectSkinning { public: - SkinnedPBREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) : - PBREffect(device, effectFlags, pipelineDescription, true) + SkinnedPBREffect(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription) + : PBREffect(device, effectFlags, pipelineDescription, true) {} - SkinnedPBREffect(SkinnedPBREffect&&) = default; - SkinnedPBREffect& operator= (SkinnedPBREffect&&) = default; + SkinnedPBREffect(SkinnedPBREffect&&) = default; + SkinnedPBREffect& operator=(SkinnedPBREffect&&) = default; - SkinnedPBREffect(SkinnedPBREffect const&) = delete; - SkinnedPBREffect& operator= (SkinnedPBREffect const&) = delete; + SkinnedPBREffect(SkinnedPBREffect const&) = delete; + SkinnedPBREffect& operator=(SkinnedPBREffect const&) = delete; ~SkinnedPBREffect() override; @@ -703,7 +679,6 @@ namespace DirectX void __cdecl ResetBoneTransforms() override; }; - //------------------------------------------------------------------------------ // Built-in shader for debug visualization of normals, tangents, etc. class DebugEffect : public IEffect, public IEffectMatrices @@ -711,23 +686,22 @@ namespace DirectX public: enum Mode : uint32_t { - Mode_Default = 0, // Hemispherical ambient lighting - Mode_Normals, // RGB normals - Mode_Tangents, // RGB tangents - Mode_BiTangents, // RGB bi-tangents + Mode_Default = 0, // Hemispherical ambient lighting + Mode_Normals, // RGB normals + Mode_Tangents, // RGB tangents + Mode_BiTangents, // RGB bi-tangents }; - DIRECTX_TOOLKIT_API DebugEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - Mode debugMode = Mode_Default); + DIRECTX_TOOLKIT_API DebugEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + Mode debugMode = Mode_Default); - DIRECTX_TOOLKIT_API DebugEffect(DebugEffect&&) noexcept; - DIRECTX_TOOLKIT_API DebugEffect& operator= (DebugEffect&&) noexcept; + DIRECTX_TOOLKIT_API DebugEffect(DebugEffect&&) noexcept; + DIRECTX_TOOLKIT_API DebugEffect& operator=(DebugEffect&&) noexcept; - DebugEffect(DebugEffect const&) = delete; - DebugEffect& operator= (DebugEffect const&) = delete; + DebugEffect(DebugEffect const&) = delete; + DebugEffect& operator=(DebugEffect const&) = delete; DIRECTX_TOOLKIT_API ~DebugEffect() override; @@ -742,7 +716,7 @@ namespace DirectX // Debug Settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetHemisphericalAmbientColor(FXMVECTOR upper, FXMVECTOR lower); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); private: // Private implementation. @@ -751,7 +725,6 @@ namespace DirectX std::unique_ptr pImpl; }; - //------------------------------------------------------------------------------ // Built-in shader for non-photorealistic rendering class NPREffect : public IEffect, public IEffectMatrices, public IEffectLights @@ -759,24 +732,23 @@ namespace DirectX public: enum Mode : uint32_t { - Mode_Cel = 0, // Cel (toon) shading - Mode_Gooch, // Gooch shading - Mode_MatCap, // Material Capture shading + Mode_Cel = 0, // Cel (toon) shading + Mode_Gooch, // Gooch shading + Mode_MatCap, // Material Capture shading }; - DIRECTX_TOOLKIT_API inline NPREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - Mode nprMode = Mode_Cel) : - NPREffect(device, effectFlags, pipelineDescription, nprMode, false) + DIRECTX_TOOLKIT_API inline NPREffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + Mode nprMode = Mode_Cel) + : NPREffect(device, effectFlags, pipelineDescription, nprMode, false) {} - DIRECTX_TOOLKIT_API NPREffect(NPREffect&&) noexcept; - DIRECTX_TOOLKIT_API NPREffect& operator= (NPREffect&&) noexcept; + DIRECTX_TOOLKIT_API NPREffect(NPREffect&&) noexcept; + DIRECTX_TOOLKIT_API NPREffect& operator=(NPREffect&&) noexcept; - NPREffect(NPREffect const&) = delete; - NPREffect& operator= (NPREffect const&) = delete; + NPREffect(NPREffect const&) = delete; + NPREffect& operator=(NPREffect const&) = delete; DIRECTX_TOOLKIT_API ~NPREffect() override; @@ -792,19 +764,20 @@ namespace DirectX // Material settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetSpecularColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetSpecularThreshold(float threshold, float smoothing); - DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); - DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); + DIRECTX_TOOLKIT_API void __cdecl SetSpecularThreshold(float threshold, float smoothing); + DIRECTX_TOOLKIT_API void __cdecl DisableSpecular(); + DIRECTX_TOOLKIT_API void __cdecl SetAlpha(float value); DIRECTX_TOOLKIT_API void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); // Light settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override; - DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; + DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; static constexpr int MaxDirectionalLights = 1; // Texture setting. - DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); // Cel shading setting. DIRECTX_TOOLKIT_API void __cdecl SetCelShaderBands(int bands); @@ -815,14 +788,15 @@ namespace DirectX // MatCap shading settings. DIRECTX_TOOLKIT_API void __cdecl SetMatCap(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor); - DIRECTX_TOOLKIT_API void __cdecl SetMatCap(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); + DIRECTX_TOOLKIT_API void __cdecl SetMatCap(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, + D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); // Rim lighting settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetRimLightingColor(FXMVECTOR value); - DIRECTX_TOOLKIT_API void __cdecl SetRimLightingPower(float power); - DIRECTX_TOOLKIT_API void __cdecl SetRimLightingIntensity(float strength); - DIRECTX_TOOLKIT_API void __cdecl SetRimLightingRange(float start, float end); - DIRECTX_TOOLKIT_API void __cdecl DisableRimLighting(); + DIRECTX_TOOLKIT_API void __cdecl SetRimLightingPower(float power); + DIRECTX_TOOLKIT_API void __cdecl SetRimLightingIntensity(float strength); + DIRECTX_TOOLKIT_API void __cdecl SetRimLightingRange(float start, float end); + DIRECTX_TOOLKIT_API void __cdecl DisableRimLighting(); protected: // Internal implementation. @@ -830,17 +804,16 @@ namespace DirectX std::unique_ptr pImpl; - DIRECTX_TOOLKIT_API NPREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - Mode nprMode, - bool skinningEnabled); + DIRECTX_TOOLKIT_API NPREffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + Mode nprMode, + bool skinningEnabled); private: // Unsupported interface methods. DIRECTX_TOOLKIT_API void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; - DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override; }; @@ -848,19 +821,18 @@ namespace DirectX class DIRECTX_TOOLKIT_API SkinnedNPREffect : public NPREffect, public IEffectSkinning { public: - SkinnedNPREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, + SkinnedNPREffect(_In_ ID3D12Device* device, + uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - Mode nprMode = Mode_Cel) : - NPREffect(device, effectFlags, pipelineDescription, nprMode, true) + Mode nprMode = Mode_Cel) + : NPREffect(device, effectFlags, pipelineDescription, nprMode, true) {} - SkinnedNPREffect(SkinnedNPREffect&&) = default; - SkinnedNPREffect& operator= (SkinnedNPREffect&&) = default; + SkinnedNPREffect(SkinnedNPREffect&&) = default; + SkinnedNPREffect& operator=(SkinnedNPREffect&&) = default; - SkinnedNPREffect(SkinnedNPREffect const&) = delete; - SkinnedNPREffect& operator= (SkinnedNPREffect const&) = delete; + SkinnedNPREffect(SkinnedNPREffect const&) = delete; + SkinnedNPREffect& operator=(SkinnedNPREffect const&) = delete; ~SkinnedNPREffect() override; @@ -872,7 +844,6 @@ namespace DirectX void __cdecl ResetBoneTransforms() override; }; - //------------------------------------------------------------------------------ // Abstract interface to factory texture resources class DIRECTX_TOOLKIT_API IEffectTextureFactory @@ -880,38 +851,35 @@ namespace DirectX public: virtual ~IEffectTextureFactory() = default; - IEffectTextureFactory(const IEffectTextureFactory&) = delete; + IEffectTextureFactory(const IEffectTextureFactory&) = delete; IEffectTextureFactory& operator=(const IEffectTextureFactory&) = delete; virtual size_t __cdecl CreateTexture(_In_z_ const wchar_t* name, int descriptorIndex) = 0; protected: - IEffectTextureFactory() = default; - IEffectTextureFactory(IEffectTextureFactory&&) = default; + IEffectTextureFactory() = default; + IEffectTextureFactory(IEffectTextureFactory&&) = default; IEffectTextureFactory& operator=(IEffectTextureFactory&&) = default; }; - // Factory for sharing texture resources class EffectTextureFactory : public IEffectTextureFactory { public: - DIRECTX_TOOLKIT_API EffectTextureFactory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - _In_ ID3D12DescriptorHeap* descriptorHeap) noexcept(false); - - DIRECTX_TOOLKIT_API EffectTextureFactory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - _In_ size_t numDescriptors, + DIRECTX_TOOLKIT_API EffectTextureFactory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + _In_ ID3D12DescriptorHeap* descriptorHeap) noexcept(false); + + DIRECTX_TOOLKIT_API EffectTextureFactory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + _In_ size_t numDescriptors, _In_ D3D12_DESCRIPTOR_HEAP_FLAGS descriptorHeapFlags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) noexcept(false); - DIRECTX_TOOLKIT_API EffectTextureFactory(EffectTextureFactory&&) noexcept; - DIRECTX_TOOLKIT_API EffectTextureFactory& operator= (EffectTextureFactory&&) noexcept; + DIRECTX_TOOLKIT_API EffectTextureFactory(EffectTextureFactory&&) noexcept; + DIRECTX_TOOLKIT_API EffectTextureFactory& operator=(EffectTextureFactory&&) noexcept; - EffectTextureFactory(EffectTextureFactory const&) = delete; - EffectTextureFactory& operator= (EffectTextureFactory const&) = delete; + EffectTextureFactory(EffectTextureFactory const&) = delete; + EffectTextureFactory& operator=(EffectTextureFactory const&) = delete; DIRECTX_TOOLKIT_API ~EffectTextureFactory() override; @@ -946,7 +914,6 @@ namespace DirectX std::unique_ptr pImpl; }; - //------------------------------------------------------------------------------ // Abstract interface to factory for sharing effects class DIRECTX_TOOLKIT_API IEffectFactory @@ -954,90 +921,86 @@ namespace DirectX public: virtual ~IEffectFactory() = default; - IEffectFactory(const IEffectFactory&) = delete; + IEffectFactory(const IEffectFactory&) = delete; IEffectFactory& operator=(const IEffectFactory&) = delete; struct DIRECTX_TOOLKIT_API EffectInfo { - std::wstring name; - bool perVertexColor; - bool enableSkinning; - bool enableDualTexture; - bool enableNormalMaps; - bool biasedVertexNormals; - float specularPower; - float alphaValue; - XMFLOAT3 ambientColor; - XMFLOAT3 diffuseColor; - XMFLOAT3 specularColor; - XMFLOAT3 emissiveColor; - int diffuseTextureIndex; - int specularTextureIndex; - int normalTextureIndex; - int emissiveTextureIndex; - int samplerIndex; - int samplerIndex2; + std::wstring name; + bool perVertexColor; + bool enableSkinning; + bool enableDualTexture; + bool enableNormalMaps; + bool biasedVertexNormals; + float specularPower; + float alphaValue; + XMFLOAT3 ambientColor; + XMFLOAT3 diffuseColor; + XMFLOAT3 specularColor; + XMFLOAT3 emissiveColor; + int diffuseTextureIndex; + int specularTextureIndex; + int normalTextureIndex; + int emissiveTextureIndex; + int samplerIndex; + int samplerIndex2; EffectInfo() noexcept - : perVertexColor(false) - , enableSkinning(false) - , enableDualTexture(false) - , enableNormalMaps(false) - , biasedVertexNormals(false) - , specularPower(0) - , alphaValue(0) - , ambientColor(0, 0, 0) - , diffuseColor(0, 0, 0) - , specularColor(0, 0, 0) - , emissiveColor(0, 0, 0) - , diffuseTextureIndex(-1) - , specularTextureIndex(-1) - , normalTextureIndex(-1) - , emissiveTextureIndex(-1) - , samplerIndex(-1) - , samplerIndex2(-1) + : perVertexColor(false), + enableSkinning(false), + enableDualTexture(false), + enableNormalMaps(false), + biasedVertexNormals(false), + specularPower(0), + alphaValue(0), + ambientColor(0, 0, 0), + diffuseColor(0, 0, 0), + specularColor(0, 0, 0), + emissiveColor(0, 0, 0), + diffuseTextureIndex(-1), + specularTextureIndex(-1), + normalTextureIndex(-1), + emissiveTextureIndex(-1), + samplerIndex(-1), + samplerIndex2(-1) {} }; - virtual std::shared_ptr __cdecl CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset = 0, - int samplerDescriptorOffset = 0) = 0; + virtual std::shared_ptr __cdecl CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset = 0, + int samplerDescriptorOffset = 0) + = 0; protected: - IEffectFactory() = default; - IEffectFactory(IEffectFactory&&) = default; + IEffectFactory() = default; + IEffectFactory(IEffectFactory&&) = default; IEffectFactory& operator=(IEffectFactory&&) = default; }; - // Factory for sharing effects class EffectFactory : public IEffectFactory { public: DIRECTX_TOOLKIT_API EffectFactory(_In_ ID3D12Device* device); - DIRECTX_TOOLKIT_API EffectFactory( - _In_ ID3D12DescriptorHeap* textureDescriptors, - _In_ ID3D12DescriptorHeap* samplerDescriptors); + DIRECTX_TOOLKIT_API EffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors); - DIRECTX_TOOLKIT_API EffectFactory(EffectFactory&&) noexcept; - DIRECTX_TOOLKIT_API EffectFactory& operator= (EffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API EffectFactory(EffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API EffectFactory& operator=(EffectFactory&&) noexcept; - EffectFactory(EffectFactory const&) = delete; - EffectFactory& operator= (EffectFactory const&) = delete; + EffectFactory(EffectFactory const&) = delete; + EffectFactory& operator=(EffectFactory const&) = delete; DIRECTX_TOOLKIT_API ~EffectFactory() override; // IEffectFactory methods. - DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset = 0, + DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset = 0, int samplerDescriptorOffset = 0) override; // Settings. @@ -1065,31 +1028,28 @@ namespace DirectX std::shared_ptr pImpl; }; - // Factory for Physically Based Rendering (PBR) class PBREffectFactory : public IEffectFactory { public: DIRECTX_TOOLKIT_API PBREffectFactory(_In_ ID3D12Device* device) noexcept(false); - DIRECTX_TOOLKIT_API PBREffectFactory( - _In_ ID3D12DescriptorHeap* textureDescriptors, - _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept(false); + DIRECTX_TOOLKIT_API PBREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, + _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept(false); - DIRECTX_TOOLKIT_API PBREffectFactory(PBREffectFactory&&) noexcept; - DIRECTX_TOOLKIT_API PBREffectFactory& operator= (PBREffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API PBREffectFactory(PBREffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API PBREffectFactory& operator=(PBREffectFactory&&) noexcept; - PBREffectFactory(PBREffectFactory const&) = delete; - PBREffectFactory& operator= (PBREffectFactory const&) = delete; + PBREffectFactory(PBREffectFactory const&) = delete; + PBREffectFactory& operator=(PBREffectFactory const&) = delete; DIRECTX_TOOLKIT_API ~PBREffectFactory() override; // IEffectFactory methods. - DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset = 0, + DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset = 0, int samplerDescriptorOffset = 0) override; // Settings. @@ -1109,31 +1069,28 @@ namespace DirectX std::shared_ptr pImpl; }; - // Factory for Non-Photorealistic Rendering (NPR) class NPREffectFactory : public IEffectFactory { public: DIRECTX_TOOLKIT_API NPREffectFactory(_In_ ID3D12Device* device); - DIRECTX_TOOLKIT_API NPREffectFactory( - _In_ ID3D12DescriptorHeap* textureDescriptors, - _In_ ID3D12DescriptorHeap* samplerDescriptors); + DIRECTX_TOOLKIT_API NPREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, + _In_ ID3D12DescriptorHeap* samplerDescriptors); - DIRECTX_TOOLKIT_API NPREffectFactory(NPREffectFactory&&) noexcept; - DIRECTX_TOOLKIT_API NPREffectFactory& operator= (NPREffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API NPREffectFactory(NPREffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API NPREffectFactory& operator=(NPREffectFactory&&) noexcept; - NPREffectFactory(NPREffectFactory const&) = delete; - NPREffectFactory& operator= (NPREffectFactory const&) = delete; + NPREffectFactory(NPREffectFactory const&) = delete; + NPREffectFactory& operator=(NPREffectFactory const&) = delete; DIRECTX_TOOLKIT_API ~NPREffectFactory() override; // IEffectFactory methods. - DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset = 0, + DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset = 0, int samplerDescriptorOffset = 0) override; // Settings. @@ -1158,8 +1115,8 @@ namespace DirectX std::shared_ptr pImpl; }; - } -} + } // namespace DX12 +} // namespace DirectX #if defined(DIRECTX_TOOLKIT_IMPORT) && defined(_MSC_VER) #pragma warning(pop) diff --git a/Inc/GamePad.h b/Inc/GamePad.h index ae2fe8af..9c2a54f5 100644 --- a/Inc/GamePad.h +++ b/Inc/GamePad.h @@ -29,12 +29,12 @@ #ifdef USING_GAMEINPUT #include #if defined(_MSC_VER) && (defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION)) -#pragma comment(lib,"gameinput.lib") +#pragma comment(lib, "gameinput.lib") #endif #elif defined(USING_WINDOWS_GAMING_INPUT) #ifdef _MSC_VER -#pragma comment(lib,"runtimeobject.lib") +#pragma comment(lib, "runtimeobject.lib") #endif #include @@ -43,7 +43,7 @@ #elif defined(USING_XINPUT) #ifdef _MSC_VER -#pragma comment(lib,"xinput.lib") +#pragma comment(lib, "xinput.lib") #endif #endif @@ -53,13 +53,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -78,7 +78,6 @@ #pragma warning(disable : 4251) #endif - namespace DirectX { class GamePad @@ -86,25 +85,25 @@ namespace DirectX public: DIRECTX_TOOLKIT_API GamePad() noexcept(false); - DIRECTX_TOOLKIT_API GamePad(GamePad&&) noexcept; - DIRECTX_TOOLKIT_API GamePad& operator= (GamePad&&) noexcept; + DIRECTX_TOOLKIT_API GamePad(GamePad&&) noexcept; + DIRECTX_TOOLKIT_API GamePad& operator=(GamePad&&) noexcept; - GamePad(GamePad const&) = delete; + GamePad(GamePad const&) = delete; GamePad& operator=(GamePad const&) = delete; DIRECTX_TOOLKIT_API virtual ~GamePad(); - #if defined(USING_GAMEINPUT) || defined(USING_WINDOWS_GAMING_INPUT) || defined(_XBOX_ONE) +#if defined(USING_GAMEINPUT) || defined(USING_WINDOWS_GAMING_INPUT) || defined(_XBOX_ONE) static constexpr int MAX_PLAYER_COUNT = 8; - #else +#else static constexpr int MAX_PLAYER_COUNT = 4; - #endif +#endif static constexpr int c_MostRecent = -1; - #ifdef USING_GAMEINPUT +#ifdef USING_GAMEINPUT static constexpr int c_MergedInput = -2; - #endif +#endif enum DeadZone : uint32_t { @@ -218,22 +217,28 @@ namespace DirectX GUITAR_ALTERNATE, DRUM_KIT, GUITAR_BASS = 11, - ARCADE_PAD = 19, + ARCADE_PAD = 19, }; - bool connected; - Type gamepadType; - #ifdef USING_GAMEINPUT + bool connected; + Type gamepadType; +#ifdef USING_GAMEINPUT APP_LOCAL_DEVICE_ID id; - #elif defined(USING_WINDOWS_GAMING_INPUT) - std::wstring id; - #else - uint64_t id; - #endif - uint16_t vid; - uint16_t pid; +#elif defined(USING_WINDOWS_GAMING_INPUT) + std::wstring id; +#else + uint64_t id; +#endif + uint16_t vid; + uint16_t pid; - Capabilities() noexcept : connected(false), gamepadType(UNKNOWN), id{}, vid(0), pid(0) {} + Capabilities() noexcept + : connected(false), + gamepadType(UNKNOWN), + id{}, + vid(0), + pid(0) + {} bool __cdecl IsConnected() const noexcept { return connected; } }; @@ -243,10 +248,10 @@ namespace DirectX public: enum ButtonState : uint32_t { - UP = 0, // Button is up - HELD = 1, // Button is held down - RELEASED = 2, // Button was just released - PRESSED = 3, // Buton was just pressed + UP = 0, // Button is up + HELD = 1, // Button is held down + RELEASED = 2, // Button was just released + PRESSED = 3, // Buton was just pressed }; ButtonState a; @@ -290,14 +295,14 @@ namespace DirectX ButtonState leftTrigger; ButtonState rightTrigger; - #ifdef _PREFAST_ - #pragma prefast(push) - #pragma prefast(disable : 26495, "Reset() performs the initialization") - #endif +#ifdef _PREFAST_ +#pragma prefast(push) +#pragma prefast(disable : 26495, "Reset() performs the initialization") +#endif ButtonStateTracker() noexcept { Reset(); } - #ifdef _PREFAST_ - #pragma prefast(pop) - #endif +#ifdef _PREFAST_ +#pragma prefast(pop) +#endif void __cdecl Update(const State& state) noexcept; @@ -310,42 +315,37 @@ namespace DirectX }; // Retrieve the current state of the gamepad of the associated player index - DIRECTX_TOOLKIT_API State __cdecl GetState( - int player, - DeadZone deadZoneMode = DEAD_ZONE_INDEPENDENT_AXES); + DIRECTX_TOOLKIT_API State __cdecl GetState(int player, DeadZone deadZoneMode = DEAD_ZONE_INDEPENDENT_AXES); // Retrieve the current capabilities of the gamepad of the associated player index DIRECTX_TOOLKIT_API Capabilities __cdecl GetCapabilities(int player); // Set the vibration motor speeds of the gamepad - DIRECTX_TOOLKIT_API bool __cdecl SetVibration( - int player, - float leftMotor, float rightMotor, - float leftTrigger = 0.f, float rightTrigger = 0.f) noexcept; + DIRECTX_TOOLKIT_API bool __cdecl + SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger = 0.f, float rightTrigger = 0.f) noexcept; // Handle suspending/resuming DIRECTX_TOOLKIT_API void __cdecl Suspend() noexcept; DIRECTX_TOOLKIT_API void __cdecl Resume() noexcept; - #ifdef USING_GAMEINPUT +#ifdef USING_GAMEINPUT DIRECTX_TOOLKIT_API void __cdecl RegisterEvents(void* ctrlChanged) noexcept; // Underlying device access - #if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION == 1) +#if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION == 1) using GameInputDevice_t = GameInput::v1::IGameInputDevice; - #elif defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION == 2) +#elif defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION == 2) using GameInputDevice_t = GameInput::v2::IGameInputDevice; - #elif defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION == 3) +#elif defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION == 3) using GameInputDevice_t = GameInput::v3::IGameInputDevice; - #else +#else using GameInputDevice_t = ::IGameInputDevice; - #endif +#endif - _Success_(return) - DIRECTX_TOOLKIT_API bool __cdecl GetDevice(int player, _Outptr_ GameInputDevice_t * *device) noexcept; - #elif defined(USING_WINDOWS_GAMING_INPUT) || defined(_XBOX_ONE) + _Success_(return) DIRECTX_TOOLKIT_API bool __cdecl GetDevice(int player, _Outptr_ GameInputDevice_t** device) noexcept; +#elif defined(USING_WINDOWS_GAMING_INPUT) || defined(_XBOX_ONE) DIRECTX_TOOLKIT_API void __cdecl RegisterEvents(void* ctrlChanged, void* userChanged) noexcept; - #endif +#endif // Singleton DIRECTX_TOOLKIT_API static GamePad& __cdecl Get(); @@ -356,7 +356,7 @@ namespace DirectX std::unique_ptr pImpl; }; -} +} // namespace DirectX #ifdef __clang__ #pragma clang diagnostic pop diff --git a/Inc/GeometricPrimitive.h b/Inc/GeometricPrimitive.h index ca595a2e..195bd9b5 100644 --- a/Inc/GeometricPrimitive.h +++ b/Inc/GeometricPrimitive.h @@ -19,13 +19,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -34,7 +34,6 @@ #endif #endif - namespace DirectX { class ResourceUploadBatch; @@ -46,66 +45,123 @@ namespace DirectX class GeometricPrimitive { public: - GeometricPrimitive(GeometricPrimitive&&) = default; - GeometricPrimitive& operator= (GeometricPrimitive&&) = default; + GeometricPrimitive(GeometricPrimitive&&) = default; + GeometricPrimitive& operator=(GeometricPrimitive&&) = default; - GeometricPrimitive(GeometricPrimitive const&) = delete; - GeometricPrimitive& operator= (GeometricPrimitive const&) = delete; + GeometricPrimitive(GeometricPrimitive const&) = delete; + GeometricPrimitive& operator=(GeometricPrimitive const&) = delete; DIRECTX_TOOLKIT_API virtual ~GeometricPrimitive(); - using VertexType = VertexPositionNormalTexture; + using VertexType = VertexPositionNormalTexture; using VertexCollection = std::vector; - using IndexCollection = std::vector; + using IndexCollection = std::vector; // Factory methods. - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCube(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateBox(const XMFLOAT3& size, bool rhcoords = true, bool invertn = false, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateSphere(float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateGeoSphere(float diameter = 1, size_t tessellation = 3, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCylinder(float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCone(float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTorus(float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTetrahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateOctahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateDodecahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateIcosahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTeapot(float size = 1, size_t tessellation = 8, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCustom(const VertexCollection& vertices, const IndexCollection& indices, _In_opt_ ID3D12Device* device = nullptr); - - DIRECTX_TOOLKIT_API static void __cdecl CreateCube(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateBox(VertexCollection& vertices, IndexCollection& indices, const XMFLOAT3& size, bool rhcoords = true, bool invertn = false); - DIRECTX_TOOLKIT_API static void __cdecl CreateSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false); - DIRECTX_TOOLKIT_API static void __cdecl CreateGeoSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 3, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateCylinder(VertexCollection& vertices, IndexCollection& indices, float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateCone(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateTorus(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateTetrahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateOctahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateDodecahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateIcosahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); - DIRECTX_TOOLKIT_API static void __cdecl CreateTeapot(VertexCollection& vertices, IndexCollection& indices, float size = 1, size_t tessellation = 8, bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateCube(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateBox(const XMFLOAT3& size, bool rhcoords = true, bool invertn = false, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateSphere(float diameter = 1, + size_t tessellation = 16, + bool rhcoords = true, + bool invertn = false, + _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateGeoSphere(float diameter = 1, size_t tessellation = 3, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCylinder(float height = 1, + float diameter = 1, + size_t tessellation = 32, + bool rhcoords = true, + _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCone(float diameter = 1, + float height = 1, + size_t tessellation = 32, + bool rhcoords = true, + _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTorus(float diameter = 1, + float thickness = 0.333f, + size_t tessellation = 32, + bool rhcoords = true, + _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateTetrahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateOctahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateDodecahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateIcosahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateTeapot(float size = 1, size_t tessellation = 8, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateCustom(const VertexCollection& vertices, const IndexCollection& indices, _In_opt_ ID3D12Device* device = nullptr); + + DIRECTX_TOOLKIT_API static void __cdecl + CreateCube(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl CreateBox(VertexCollection& vertices, + IndexCollection& indices, + const XMFLOAT3& size, + bool rhcoords = true, + bool invertn = false); + DIRECTX_TOOLKIT_API static void __cdecl CreateSphere(VertexCollection& vertices, + IndexCollection& indices, + float diameter = 1, + size_t tessellation = 16, + bool rhcoords = true, + bool invertn = false); + DIRECTX_TOOLKIT_API static void __cdecl CreateGeoSphere(VertexCollection& vertices, + IndexCollection& indices, + float diameter = 1, + size_t tessellation = 3, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl CreateCylinder(VertexCollection& vertices, + IndexCollection& indices, + float height = 1, + float diameter = 1, + size_t tessellation = 32, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl CreateCone(VertexCollection& vertices, + IndexCollection& indices, + float diameter = 1, + float height = 1, + size_t tessellation = 32, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl CreateTorus(VertexCollection& vertices, + IndexCollection& indices, + float diameter = 1, + float thickness = 0.333f, + size_t tessellation = 32, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl + CreateTetrahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl + CreateOctahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl + CreateDodecahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl + CreateIcosahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static void __cdecl CreateTeapot(VertexCollection& vertices, + IndexCollection& indices, + float size = 1, + size_t tessellation = 8, + bool rhcoords = true); // Load VB/IB resources for static geometry. - DIRECTX_TOOLKIT_API void __cdecl LoadStaticBuffers( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch); + DIRECTX_TOOLKIT_API void __cdecl LoadStaticBuffers(_In_ ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch); // Transition VB/IB resources for static geometry. - DIRECTX_TOOLKIT_API void __cdecl Transition( - _In_ ID3D12GraphicsCommandList* commandList, - D3D12_RESOURCE_STATES stateBeforeVB, - D3D12_RESOURCE_STATES stateAfterVB, - D3D12_RESOURCE_STATES stateBeforeIB, - D3D12_RESOURCE_STATES stateAfterIB); + DIRECTX_TOOLKIT_API void __cdecl Transition(_In_ ID3D12GraphicsCommandList* commandList, + D3D12_RESOURCE_STATES stateBeforeVB, + D3D12_RESOURCE_STATES stateAfterVB, + D3D12_RESOURCE_STATES stateBeforeIB, + D3D12_RESOURCE_STATES stateAfterIB); // Draw the primitive. DIRECTX_TOOLKIT_API void __cdecl Draw(_In_ ID3D12GraphicsCommandList* commandList) const; - DIRECTX_TOOLKIT_API void __cdecl DrawInstanced( - _In_ ID3D12GraphicsCommandList* commandList, - uint32_t instanceCount, - uint32_t startInstanceLocation = 0) const; + DIRECTX_TOOLKIT_API void __cdecl + DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation = 0) const; private: DIRECTX_TOOLKIT_API GeometricPrimitive() noexcept(false); @@ -115,5 +171,5 @@ namespace DirectX std::unique_ptr pImpl; }; - } -} + } // namespace DX12 +} // namespace DirectX diff --git a/Inc/GraphicsMemory.h b/Inc/GraphicsMemory.h index 4e509c9c..a3993ebc 100644 --- a/Inc/GraphicsMemory.h +++ b/Inc/GraphicsMemory.h @@ -37,13 +37,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -57,40 +57,38 @@ #pragma warning(disable : 4251) #endif - namespace DirectX { class LinearAllocatorPage; inline namespace DX12 { - // Works a little like a smart pointer. The memory will only be fenced by the GPU once the pointer - // has been invalidated or the user explicitly marks it for fencing. + // Works a little like a smart pointer. The memory will only be fenced by the GPU once the pointer + // has been invalidated or the user explicitly marks it for fencing. class DIRECTX_TOOLKIT_API GraphicsResource { public: GraphicsResource() noexcept; - GraphicsResource( - _In_ LinearAllocatorPage* page, - _In_ D3D12_GPU_VIRTUAL_ADDRESS gpuAddress, - _In_ ID3D12Resource* resource, - _In_ void* memory, - _In_ size_t offset, - _In_ size_t size) noexcept; + GraphicsResource(_In_ LinearAllocatorPage* page, + _In_ D3D12_GPU_VIRTUAL_ADDRESS gpuAddress, + _In_ ID3D12Resource* resource, + _In_ void* memory, + _In_ size_t offset, + _In_ size_t size) noexcept; GraphicsResource(GraphicsResource&& other) noexcept; - GraphicsResource&& operator= (GraphicsResource&&) noexcept; + GraphicsResource&& operator=(GraphicsResource&&) noexcept; - GraphicsResource(const GraphicsResource&) = delete; - GraphicsResource& operator= (const GraphicsResource&) = delete; + GraphicsResource(const GraphicsResource&) = delete; + GraphicsResource& operator=(const GraphicsResource&) = delete; ~GraphicsResource(); D3D12_GPU_VIRTUAL_ADDRESS GpuAddress() const noexcept { return mGpuAddress; } - ID3D12Resource* Resource() const noexcept { return mResource; } - void* Memory() const noexcept { return mMemory; } - size_t ResourceOffset() const noexcept { return mBufferOffset; } - size_t Size() const noexcept { return mSize; } + ID3D12Resource* Resource() const noexcept { return mResource; } + void* Memory() const noexcept { return mMemory; } + size_t ResourceOffset() const noexcept { return mBufferOffset; } + size_t Size() const noexcept { return mSize; } explicit operator bool() const noexcept { return mResource != nullptr; } @@ -99,12 +97,12 @@ namespace DirectX void __cdecl Reset(GraphicsResource&&) noexcept; private: - LinearAllocatorPage* mPage; - D3D12_GPU_VIRTUAL_ADDRESS mGpuAddress; - ID3D12Resource* mResource; - void* mMemory; - size_t mBufferOffset; - size_t mSize; + LinearAllocatorPage* mPage; + D3D12_GPU_VIRTUAL_ADDRESS mGpuAddress; + ID3D12Resource* mResource; + void* mMemory; + size_t mBufferOffset; + size_t mSize; }; class DIRECTX_TOOLKIT_API SharedGraphicsResource @@ -113,29 +111,35 @@ namespace DirectX SharedGraphicsResource() noexcept; SharedGraphicsResource(SharedGraphicsResource&&) noexcept; - SharedGraphicsResource&& operator= (SharedGraphicsResource&&) noexcept; + SharedGraphicsResource&& operator=(SharedGraphicsResource&&) noexcept; SharedGraphicsResource(GraphicsResource&&); - SharedGraphicsResource&& operator= (GraphicsResource&&); + SharedGraphicsResource&& operator=(GraphicsResource&&); SharedGraphicsResource(const SharedGraphicsResource&) noexcept; - SharedGraphicsResource& operator= (const SharedGraphicsResource&) noexcept; + SharedGraphicsResource& operator=(const SharedGraphicsResource&) noexcept; - SharedGraphicsResource(const GraphicsResource&) = delete; - SharedGraphicsResource& operator= (const GraphicsResource&) = delete; + SharedGraphicsResource(const GraphicsResource&) = delete; + SharedGraphicsResource& operator=(const GraphicsResource&) = delete; ~SharedGraphicsResource(); D3D12_GPU_VIRTUAL_ADDRESS GpuAddress() const noexcept { return mSharedResource->GpuAddress(); } - ID3D12Resource* Resource() const noexcept { return mSharedResource->Resource(); } - void* Memory() const noexcept { return mSharedResource->Memory(); } - size_t ResourceOffset() const noexcept { return mSharedResource->ResourceOffset(); } - size_t Size() const noexcept { return mSharedResource->Size(); } + ID3D12Resource* Resource() const noexcept { return mSharedResource->Resource(); } + void* Memory() const noexcept { return mSharedResource->Memory(); } + size_t ResourceOffset() const noexcept { return mSharedResource->ResourceOffset(); } + size_t Size() const noexcept { return mSharedResource->Size(); } explicit operator bool() const noexcept { return mSharedResource != nullptr; } - bool operator == (const SharedGraphicsResource& other) const noexcept { return mSharedResource.get() == other.mSharedResource.get(); } - bool operator != (const SharedGraphicsResource& other) const noexcept { return mSharedResource.get() != other.mSharedResource.get(); } + bool operator==(const SharedGraphicsResource& other) const noexcept + { + return mSharedResource.get() == other.mSharedResource.get(); + } + bool operator!=(const SharedGraphicsResource& other) const noexcept + { + return mSharedResource.get() != other.mSharedResource.get(); + } // Clear the pointer. Using operator -> will produce bad results. void __cdecl Reset() noexcept; @@ -150,12 +154,12 @@ namespace DirectX //------------------------------------------------------------------------------ struct GraphicsMemoryStatistics { - size_t committedMemory; // Bytes of memory currently committed/in-flight - size_t totalMemory; // Total bytes of memory used by the allocators - size_t totalPages; // Total page count - size_t peakCommitedMemory; // Peak commited memory value since last reset - size_t peakTotalMemory; // Peak total bytes - size_t peakTotalPages; // Peak total page count + size_t committedMemory; // Bytes of memory currently committed/in-flight + size_t totalMemory; // Total bytes of memory used by the allocators + size_t totalPages; // Total page count + size_t peakCommitedMemory; // Peak commited memory value since last reset + size_t peakTotalMemory; // Peak total bytes + size_t peakTotalPages; // Peak total page count }; //------------------------------------------------------------------------------ @@ -175,10 +179,10 @@ namespace DirectX DIRECTX_TOOLKIT_API explicit GraphicsMemory(_In_ ID3D12Device* device); - DIRECTX_TOOLKIT_API GraphicsMemory(GraphicsMemory&&) noexcept; - DIRECTX_TOOLKIT_API GraphicsMemory& operator= (GraphicsMemory&&) noexcept; + DIRECTX_TOOLKIT_API GraphicsMemory(GraphicsMemory&&) noexcept; + DIRECTX_TOOLKIT_API GraphicsMemory& operator=(GraphicsMemory&&) noexcept; - GraphicsMemory(GraphicsMemory const&) = delete; + GraphicsMemory(GraphicsMemory const&) = delete; GraphicsMemory& operator=(GraphicsMemory const&) = delete; DIRECTX_TOOLKIT_API virtual ~GraphicsMemory(); @@ -189,27 +193,29 @@ namespace DirectX DIRECTX_TOOLKIT_API inline GraphicsResource __cdecl Allocate(size_t size, size_t alignment = 16, uint32_t tag = TAG_GENERIC) { auto alloc = AllocateImpl(size, alignment); - #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS +#ifdef USING_PIX_CUSTOM_MEMORY_EVENTS std::ignore = ReportCustomMemoryAlloc(alloc.Memory(), alloc.Size(), tag); - #else +#else UNREFERENCED_PARAMETER(tag); - #endif +#endif return alloc; } // Version of Allocate that aligns to D3D12 constant buffer requirements - template GraphicsResource AllocateConstant() + template + GraphicsResource AllocateConstant() { - constexpr size_t alignment = D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT; + constexpr size_t alignment = D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT; constexpr size_t alignedSize = (sizeof(T) + alignment - 1) & ~(alignment - 1); - auto alloc = AllocateImpl(alignedSize, alignment); - #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS - // This cast is needed to capture the type information in the PDB + auto alloc = AllocateImpl(alignedSize, alignment); +#ifdef USING_PIX_CUSTOM_MEMORY_EVENTS + // This cast is needed to capture the type information in the PDB std::ignore = reinterpret_cast(ReportCustomMemoryAlloc(alloc.Memory(), alloc.Size(), TAG_CONSTANT)); - #endif +#endif return alloc; } - template GraphicsResource AllocateConstant(const T& setData) + template + GraphicsResource AllocateConstant(const T& setData) { GraphicsResource alloc = AllocateConstant(); memcpy(alloc.Memory(), &setData, sizeof(T)); @@ -228,7 +234,7 @@ namespace DirectX // Memory statistics DIRECTX_TOOLKIT_API GraphicsMemoryStatistics __cdecl GetStatistics(); - DIRECTX_TOOLKIT_API void __cdecl ResetStatistics(); + DIRECTX_TOOLKIT_API void __cdecl ResetStatistics(); // Properties DIRECTX_TOOLKIT_API ID3D12Device* __cdecl GetDevice() const noexcept; @@ -243,15 +249,16 @@ namespace DirectX DIRECTX_TOOLKIT_API GraphicsResource __cdecl AllocateImpl(size_t size, size_t alignment); - #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS - // The declspec is required to ensure the proper information is captured in the PDB - DIRECTX_TOOLKIT_API __declspec(allocator) static void* __cdecl ReportCustomMemoryAlloc(void* pMem, size_t size, UINT64 metadata); - #endif +#ifdef USING_PIX_CUSTOM_MEMORY_EVENTS + // The declspec is required to ensure the proper information is captured in the PDB + DIRECTX_TOOLKIT_API + __declspec(allocator) static void* __cdecl ReportCustomMemoryAlloc(void* pMem, size_t size, UINT64 metadata); +#endif std::unique_ptr pImpl; }; - } -} + } // namespace DX12 +} // namespace DirectX #if defined(DIRECTX_TOOLKIT_IMPORT) && defined(_MSC_VER) #pragma warning(pop) diff --git a/Inc/Keyboard.h b/Inc/Keyboard.h index 55395bda..aebfd640 100644 --- a/Inc/Keyboard.h +++ b/Inc/Keyboard.h @@ -27,7 +27,7 @@ #ifdef USING_GAMEINPUT #include #if defined(_MSC_VER) && (defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION)) -#pragma comment(lib,"gameinput.lib") +#pragma comment(lib, "gameinput.lib") #endif #endif @@ -35,19 +35,31 @@ #include #ifdef USING_COREWINDOW -namespace ABI { namespace Windows { namespace UI { namespace Core { struct ICoreWindow; } } } } +namespace ABI +{ + namespace Windows + { + namespace UI + { + namespace Core + { + struct ICoreWindow; + } + } // namespace UI + } // namespace Windows +} // namespace ABI #endif #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -61,7 +73,6 @@ namespace ABI { namespace Windows { namespace UI { namespace Core { struct ICore #pragma clang diagnostic ignored "-Wunknown-pragmas" #endif - namespace DirectX { class Keyboard @@ -69,10 +80,10 @@ namespace DirectX public: DIRECTX_TOOLKIT_API Keyboard() noexcept(false); - DIRECTX_TOOLKIT_API Keyboard(Keyboard&&) noexcept; - DIRECTX_TOOLKIT_API Keyboard& operator= (Keyboard&&) noexcept; + DIRECTX_TOOLKIT_API Keyboard(Keyboard&&) noexcept; + DIRECTX_TOOLKIT_API Keyboard& operator=(Keyboard&&) noexcept; - Keyboard(Keyboard const&) = delete; + Keyboard(Keyboard const&) = delete; Keyboard& operator=(Keyboard const&) = delete; DIRECTX_TOOLKIT_API virtual ~Keyboard(); @@ -82,163 +93,163 @@ namespace DirectX None = 0, Back = 0x8, - Tab = 0x9, + Tab = 0x9, Enter = 0xd, - Pause = 0x13, + Pause = 0x13, CapsLock = 0x14, - Kana = 0x15, - ImeOn = 0x16, + Kana = 0x15, + ImeOn = 0x16, Kanji = 0x19, - ImeOff = 0x1a, - Escape = 0x1b, - ImeConvert = 0x1c, + ImeOff = 0x1a, + Escape = 0x1b, + ImeConvert = 0x1c, ImeNoConvert = 0x1d, - Space = 0x20, - PageUp = 0x21, - PageDown = 0x22, - End = 0x23, - Home = 0x24, - Left = 0x25, - Up = 0x26, - Right = 0x27, - Down = 0x28, - Select = 0x29, - Print = 0x2a, - Execute = 0x2b, + Space = 0x20, + PageUp = 0x21, + PageDown = 0x22, + End = 0x23, + Home = 0x24, + Left = 0x25, + Up = 0x26, + Right = 0x27, + Down = 0x28, + Select = 0x29, + Print = 0x2a, + Execute = 0x2b, PrintScreen = 0x2c, - Insert = 0x2d, - Delete = 0x2e, - Help = 0x2f, - D0 = 0x30, - D1 = 0x31, - D2 = 0x32, - D3 = 0x33, - D4 = 0x34, - D5 = 0x35, - D6 = 0x36, - D7 = 0x37, - D8 = 0x38, - D9 = 0x39, - - A = 0x41, - B = 0x42, - C = 0x43, - D = 0x44, - E = 0x45, - F = 0x46, - G = 0x47, - H = 0x48, - I = 0x49, - J = 0x4a, - K = 0x4b, - L = 0x4c, - M = 0x4d, - N = 0x4e, - O = 0x4f, - P = 0x50, - Q = 0x51, - R = 0x52, - S = 0x53, - T = 0x54, - U = 0x55, - V = 0x56, - W = 0x57, - X = 0x58, - Y = 0x59, - Z = 0x5a, - LeftWindows = 0x5b, + Insert = 0x2d, + Delete = 0x2e, + Help = 0x2f, + D0 = 0x30, + D1 = 0x31, + D2 = 0x32, + D3 = 0x33, + D4 = 0x34, + D5 = 0x35, + D6 = 0x36, + D7 = 0x37, + D8 = 0x38, + D9 = 0x39, + + A = 0x41, + B = 0x42, + C = 0x43, + D = 0x44, + E = 0x45, + F = 0x46, + G = 0x47, + H = 0x48, + I = 0x49, + J = 0x4a, + K = 0x4b, + L = 0x4c, + M = 0x4d, + N = 0x4e, + O = 0x4f, + P = 0x50, + Q = 0x51, + R = 0x52, + S = 0x53, + T = 0x54, + U = 0x55, + V = 0x56, + W = 0x57, + X = 0x58, + Y = 0x59, + Z = 0x5a, + LeftWindows = 0x5b, RightWindows = 0x5c, - Apps = 0x5d, - - Sleep = 0x5f, - NumPad0 = 0x60, - NumPad1 = 0x61, - NumPad2 = 0x62, - NumPad3 = 0x63, - NumPad4 = 0x64, - NumPad5 = 0x65, - NumPad6 = 0x66, - NumPad7 = 0x67, - NumPad8 = 0x68, - NumPad9 = 0x69, - Multiply = 0x6a, - Add = 0x6b, + Apps = 0x5d, + + Sleep = 0x5f, + NumPad0 = 0x60, + NumPad1 = 0x61, + NumPad2 = 0x62, + NumPad3 = 0x63, + NumPad4 = 0x64, + NumPad5 = 0x65, + NumPad6 = 0x66, + NumPad7 = 0x67, + NumPad8 = 0x68, + NumPad9 = 0x69, + Multiply = 0x6a, + Add = 0x6b, Separator = 0x6c, - Subtract = 0x6d, + Subtract = 0x6d, Decimal = 0x6e, - Divide = 0x6f, - F1 = 0x70, - F2 = 0x71, - F3 = 0x72, - F4 = 0x73, - F5 = 0x74, - F6 = 0x75, - F7 = 0x76, - F8 = 0x77, - F9 = 0x78, - F10 = 0x79, - F11 = 0x7a, - F12 = 0x7b, - F13 = 0x7c, - F14 = 0x7d, - F15 = 0x7e, - F16 = 0x7f, - F17 = 0x80, - F18 = 0x81, - F19 = 0x82, - F20 = 0x83, - F21 = 0x84, - F22 = 0x85, - F23 = 0x86, - F24 = 0x87, + Divide = 0x6f, + F1 = 0x70, + F2 = 0x71, + F3 = 0x72, + F4 = 0x73, + F5 = 0x74, + F6 = 0x75, + F7 = 0x76, + F8 = 0x77, + F9 = 0x78, + F10 = 0x79, + F11 = 0x7a, + F12 = 0x7b, + F13 = 0x7c, + F14 = 0x7d, + F15 = 0x7e, + F16 = 0x7f, + F17 = 0x80, + F18 = 0x81, + F19 = 0x82, + F20 = 0x83, + F21 = 0x84, + F22 = 0x85, + F23 = 0x86, + F24 = 0x87, NumLock = 0x90, - Scroll = 0x91, - - LeftShift = 0xa0, - RightShift = 0xa1, - LeftControl = 0xa2, - RightControl = 0xa3, - LeftAlt = 0xa4, - RightAlt = 0xa5, - BrowserBack = 0xa6, - BrowserForward = 0xa7, - BrowserRefresh = 0xa8, - BrowserStop = 0xa9, - BrowserSearch = 0xaa, - BrowserFavorites = 0xab, - BrowserHome = 0xac, - VolumeMute = 0xad, - VolumeDown = 0xae, - VolumeUp = 0xaf, - MediaNextTrack = 0xb0, + Scroll = 0x91, + + LeftShift = 0xa0, + RightShift = 0xa1, + LeftControl = 0xa2, + RightControl = 0xa3, + LeftAlt = 0xa4, + RightAlt = 0xa5, + BrowserBack = 0xa6, + BrowserForward = 0xa7, + BrowserRefresh = 0xa8, + BrowserStop = 0xa9, + BrowserSearch = 0xaa, + BrowserFavorites = 0xab, + BrowserHome = 0xac, + VolumeMute = 0xad, + VolumeDown = 0xae, + VolumeUp = 0xaf, + MediaNextTrack = 0xb0, MediaPreviousTrack = 0xb1, - MediaStop = 0xb2, - MediaPlayPause = 0xb3, - LaunchMail = 0xb4, - SelectMedia = 0xb5, + MediaStop = 0xb2, + MediaPlayPause = 0xb3, + LaunchMail = 0xb4, + SelectMedia = 0xb5, LaunchApplication1 = 0xb6, LaunchApplication2 = 0xb7, OemSemicolon = 0xba, - OemPlus = 0xbb, - OemComma = 0xbc, - OemMinus = 0xbd, - OemPeriod = 0xbe, - OemQuestion = 0xbf, - OemTilde = 0xc0, - - OemOpenBrackets = 0xdb, - OemPipe = 0xdc, + OemPlus = 0xbb, + OemComma = 0xbc, + OemMinus = 0xbd, + OemPeriod = 0xbe, + OemQuestion = 0xbf, + OemTilde = 0xc0, + + OemOpenBrackets = 0xdb, + OemPipe = 0xdc, OemCloseBrackets = 0xdd, - OemQuotes = 0xde, - Oem8 = 0xdf, + OemQuotes = 0xde, + Oem8 = 0xdf, OemBackslash = 0xe2, @@ -248,217 +259,217 @@ namespace DirectX OemAuto = 0xf3, OemEnlW = 0xf4, - Attn = 0xf6, - Crsel = 0xf7, - Exsel = 0xf8, + Attn = 0xf6, + Crsel = 0xf7, + Exsel = 0xf8, EraseEof = 0xf9, - Play = 0xfa, - Zoom = 0xfb, + Play = 0xfa, + Zoom = 0xfb, - Pa1 = 0xfd, + Pa1 = 0xfd, OemClear = 0xfe, }; struct DIRECTX_TOOLKIT_API State { bool Reserved0 : 8; - bool Back : 1; // VK_BACK, 0x8 - bool Tab : 1; // VK_TAB, 0x9 + bool Back : 1; // VK_BACK, 0x8 + bool Tab : 1; // VK_TAB, 0x9 bool Reserved1 : 3; - bool Enter : 1; // VK_RETURN, 0xD + bool Enter : 1; // VK_RETURN, 0xD bool Reserved2 : 2; bool Reserved3 : 3; - bool Pause : 1; // VK_PAUSE, 0x13 - bool CapsLock : 1; // VK_CAPITAL, 0x14 - bool Kana : 1; // VK_KANA, 0x15 - bool ImeOn : 1; // VK_IME_ON, 0x16 + bool Pause : 1; // VK_PAUSE, 0x13 + bool CapsLock : 1; // VK_CAPITAL, 0x14 + bool Kana : 1; // VK_KANA, 0x15 + bool ImeOn : 1; // VK_IME_ON, 0x16 bool Reserved4 : 1; bool Reserved5 : 1; - bool Kanji : 1; // VK_KANJI, 0x19 - bool ImeOff : 1; // VK_IME_OFF, 0X1A - bool Escape : 1; // VK_ESCAPE, 0x1B - bool ImeConvert : 1; // VK_CONVERT, 0x1C - bool ImeNoConvert : 1; // VK_NONCONVERT, 0x1D + bool Kanji : 1; // VK_KANJI, 0x19 + bool ImeOff : 1; // VK_IME_OFF, 0X1A + bool Escape : 1; // VK_ESCAPE, 0x1B + bool ImeConvert : 1; // VK_CONVERT, 0x1C + bool ImeNoConvert : 1; // VK_NONCONVERT, 0x1D bool Reserved7 : 2; - bool Space : 1; // VK_SPACE, 0x20 - bool PageUp : 1; // VK_PRIOR, 0x21 - bool PageDown : 1; // VK_NEXT, 0x22 - bool End : 1; // VK_END, 0x23 - bool Home : 1; // VK_HOME, 0x24 - bool Left : 1; // VK_LEFT, 0x25 - bool Up : 1; // VK_UP, 0x26 - bool Right : 1; // VK_RIGHT, 0x27 - bool Down : 1; // VK_DOWN, 0x28 - bool Select : 1; // VK_SELECT, 0x29 - bool Print : 1; // VK_PRINT, 0x2A - bool Execute : 1; // VK_EXECUTE, 0x2B - bool PrintScreen : 1; // VK_SNAPSHOT, 0x2C - bool Insert : 1; // VK_INSERT, 0x2D - bool Delete : 1; // VK_DELETE, 0x2E - bool Help : 1; // VK_HELP, 0x2F - bool D0 : 1; // 0x30 - bool D1 : 1; // 0x31 - bool D2 : 1; // 0x32 - bool D3 : 1; // 0x33 - bool D4 : 1; // 0x34 - bool D5 : 1; // 0x35 - bool D6 : 1; // 0x36 - bool D7 : 1; // 0x37 - bool D8 : 1; // 0x38 - bool D9 : 1; // 0x39 + bool Space : 1; // VK_SPACE, 0x20 + bool PageUp : 1; // VK_PRIOR, 0x21 + bool PageDown : 1; // VK_NEXT, 0x22 + bool End : 1; // VK_END, 0x23 + bool Home : 1; // VK_HOME, 0x24 + bool Left : 1; // VK_LEFT, 0x25 + bool Up : 1; // VK_UP, 0x26 + bool Right : 1; // VK_RIGHT, 0x27 + bool Down : 1; // VK_DOWN, 0x28 + bool Select : 1; // VK_SELECT, 0x29 + bool Print : 1; // VK_PRINT, 0x2A + bool Execute : 1; // VK_EXECUTE, 0x2B + bool PrintScreen : 1; // VK_SNAPSHOT, 0x2C + bool Insert : 1; // VK_INSERT, 0x2D + bool Delete : 1; // VK_DELETE, 0x2E + bool Help : 1; // VK_HELP, 0x2F + bool D0 : 1; // 0x30 + bool D1 : 1; // 0x31 + bool D2 : 1; // 0x32 + bool D3 : 1; // 0x33 + bool D4 : 1; // 0x34 + bool D5 : 1; // 0x35 + bool D6 : 1; // 0x36 + bool D7 : 1; // 0x37 + bool D8 : 1; // 0x38 + bool D9 : 1; // 0x39 bool Reserved8 : 6; bool Reserved9 : 1; - bool A : 1; // 0x41 - bool B : 1; // 0x42 - bool C : 1; // 0x43 - bool D : 1; // 0x44 - bool E : 1; // 0x45 - bool F : 1; // 0x46 - bool G : 1; // 0x47 - bool H : 1; // 0x48 - bool I : 1; // 0x49 - bool J : 1; // 0x4A - bool K : 1; // 0x4B - bool L : 1; // 0x4C - bool M : 1; // 0x4D - bool N : 1; // 0x4E - bool O : 1; // 0x4F - bool P : 1; // 0x50 - bool Q : 1; // 0x51 - bool R : 1; // 0x52 - bool S : 1; // 0x53 - bool T : 1; // 0x54 - bool U : 1; // 0x55 - bool V : 1; // 0x56 - bool W : 1; // 0x57 - bool X : 1; // 0x58 - bool Y : 1; // 0x59 - bool Z : 1; // 0x5A - bool LeftWindows : 1; // VK_LWIN, 0x5B - bool RightWindows : 1; // VK_RWIN, 0x5C - bool Apps : 1; // VK_APPS, 0x5D + bool A : 1; // 0x41 + bool B : 1; // 0x42 + bool C : 1; // 0x43 + bool D : 1; // 0x44 + bool E : 1; // 0x45 + bool F : 1; // 0x46 + bool G : 1; // 0x47 + bool H : 1; // 0x48 + bool I : 1; // 0x49 + bool J : 1; // 0x4A + bool K : 1; // 0x4B + bool L : 1; // 0x4C + bool M : 1; // 0x4D + bool N : 1; // 0x4E + bool O : 1; // 0x4F + bool P : 1; // 0x50 + bool Q : 1; // 0x51 + bool R : 1; // 0x52 + bool S : 1; // 0x53 + bool T : 1; // 0x54 + bool U : 1; // 0x55 + bool V : 1; // 0x56 + bool W : 1; // 0x57 + bool X : 1; // 0x58 + bool Y : 1; // 0x59 + bool Z : 1; // 0x5A + bool LeftWindows : 1; // VK_LWIN, 0x5B + bool RightWindows : 1; // VK_RWIN, 0x5C + bool Apps : 1; // VK_APPS, 0x5D bool Reserved10 : 1; - bool Sleep : 1; // VK_SLEEP, 0x5F - bool NumPad0 : 1; // VK_NUMPAD0, 0x60 - bool NumPad1 : 1; // VK_NUMPAD1, 0x61 - bool NumPad2 : 1; // VK_NUMPAD2, 0x62 - bool NumPad3 : 1; // VK_NUMPAD3, 0x63 - bool NumPad4 : 1; // VK_NUMPAD4, 0x64 - bool NumPad5 : 1; // VK_NUMPAD5, 0x65 - bool NumPad6 : 1; // VK_NUMPAD6, 0x66 - bool NumPad7 : 1; // VK_NUMPAD7, 0x67 - bool NumPad8 : 1; // VK_NUMPAD8, 0x68 - bool NumPad9 : 1; // VK_NUMPAD9, 0x69 - bool Multiply : 1; // VK_MULTIPLY, 0x6A - bool Add : 1; // VK_ADD, 0x6B - bool Separator : 1; // VK_SEPARATOR, 0x6C - bool Subtract : 1; // VK_SUBTRACT, 0x6D - bool Decimal : 1; // VK_DECIMANL, 0x6E - bool Divide : 1; // VK_DIVIDE, 0x6F - bool F1 : 1; // VK_F1, 0x70 - bool F2 : 1; // VK_F2, 0x71 - bool F3 : 1; // VK_F3, 0x72 - bool F4 : 1; // VK_F4, 0x73 - bool F5 : 1; // VK_F5, 0x74 - bool F6 : 1; // VK_F6, 0x75 - bool F7 : 1; // VK_F7, 0x76 - bool F8 : 1; // VK_F8, 0x77 - bool F9 : 1; // VK_F9, 0x78 - bool F10 : 1; // VK_F10, 0x79 - bool F11 : 1; // VK_F11, 0x7A - bool F12 : 1; // VK_F12, 0x7B - bool F13 : 1; // VK_F13, 0x7C - bool F14 : 1; // VK_F14, 0x7D - bool F15 : 1; // VK_F15, 0x7E - bool F16 : 1; // VK_F16, 0x7F - bool F17 : 1; // VK_F17, 0x80 - bool F18 : 1; // VK_F18, 0x81 - bool F19 : 1; // VK_F19, 0x82 - bool F20 : 1; // VK_F20, 0x83 - bool F21 : 1; // VK_F21, 0x84 - bool F22 : 1; // VK_F22, 0x85 - bool F23 : 1; // VK_F23, 0x86 - bool F24 : 1; // VK_F24, 0x87 + bool Sleep : 1; // VK_SLEEP, 0x5F + bool NumPad0 : 1; // VK_NUMPAD0, 0x60 + bool NumPad1 : 1; // VK_NUMPAD1, 0x61 + bool NumPad2 : 1; // VK_NUMPAD2, 0x62 + bool NumPad3 : 1; // VK_NUMPAD3, 0x63 + bool NumPad4 : 1; // VK_NUMPAD4, 0x64 + bool NumPad5 : 1; // VK_NUMPAD5, 0x65 + bool NumPad6 : 1; // VK_NUMPAD6, 0x66 + bool NumPad7 : 1; // VK_NUMPAD7, 0x67 + bool NumPad8 : 1; // VK_NUMPAD8, 0x68 + bool NumPad9 : 1; // VK_NUMPAD9, 0x69 + bool Multiply : 1; // VK_MULTIPLY, 0x6A + bool Add : 1; // VK_ADD, 0x6B + bool Separator : 1; // VK_SEPARATOR, 0x6C + bool Subtract : 1; // VK_SUBTRACT, 0x6D + bool Decimal : 1; // VK_DECIMANL, 0x6E + bool Divide : 1; // VK_DIVIDE, 0x6F + bool F1 : 1; // VK_F1, 0x70 + bool F2 : 1; // VK_F2, 0x71 + bool F3 : 1; // VK_F3, 0x72 + bool F4 : 1; // VK_F4, 0x73 + bool F5 : 1; // VK_F5, 0x74 + bool F6 : 1; // VK_F6, 0x75 + bool F7 : 1; // VK_F7, 0x76 + bool F8 : 1; // VK_F8, 0x77 + bool F9 : 1; // VK_F9, 0x78 + bool F10 : 1; // VK_F10, 0x79 + bool F11 : 1; // VK_F11, 0x7A + bool F12 : 1; // VK_F12, 0x7B + bool F13 : 1; // VK_F13, 0x7C + bool F14 : 1; // VK_F14, 0x7D + bool F15 : 1; // VK_F15, 0x7E + bool F16 : 1; // VK_F16, 0x7F + bool F17 : 1; // VK_F17, 0x80 + bool F18 : 1; // VK_F18, 0x81 + bool F19 : 1; // VK_F19, 0x82 + bool F20 : 1; // VK_F20, 0x83 + bool F21 : 1; // VK_F21, 0x84 + bool F22 : 1; // VK_F22, 0x85 + bool F23 : 1; // VK_F23, 0x86 + bool F24 : 1; // VK_F24, 0x87 bool Reserved11 : 8; - bool NumLock : 1; // VK_NUMLOCK, 0x90 - bool Scroll : 1; // VK_SCROLL, 0x91 + bool NumLock : 1; // VK_NUMLOCK, 0x90 + bool Scroll : 1; // VK_SCROLL, 0x91 bool Reserved12 : 6; bool Reserved13 : 8; - bool LeftShift : 1; // VK_LSHIFT, 0xA0 - bool RightShift : 1; // VK_RSHIFT, 0xA1 - bool LeftControl : 1; // VK_LCONTROL, 0xA2 - bool RightControl : 1; // VK_RCONTROL, 0xA3 - bool LeftAlt : 1; // VK_LMENU, 0xA4 - bool RightAlt : 1; // VK_RMENU, 0xA5 - bool BrowserBack : 1; // VK_BROWSER_BACK, 0xA6 - bool BrowserForward : 1; // VK_BROWSER_FORWARD, 0xA7 - bool BrowserRefresh : 1; // VK_BROWSER_REFRESH, 0xA8 - bool BrowserStop : 1; // VK_BROWSER_STOP, 0xA9 - bool BrowserSearch : 1; // VK_BROWSER_SEARCH, 0xAA - bool BrowserFavorites : 1; // VK_BROWSER_FAVORITES, 0xAB - bool BrowserHome : 1; // VK_BROWSER_HOME, 0xAC - bool VolumeMute : 1; // VK_VOLUME_MUTE, 0xAD - bool VolumeDown : 1; // VK_VOLUME_DOWN, 0xAE - bool VolumeUp : 1; // VK_VOLUME_UP, 0xAF - bool MediaNextTrack : 1; // VK_MEDIA_NEXT_TRACK, 0xB0 - bool MediaPreviousTrack : 1;// VK_MEDIA_PREV_TRACK, 0xB1 - bool MediaStop : 1; // VK_MEDIA_STOP, 0xB2 - bool MediaPlayPause : 1; // VK_MEDIA_PLAY_PAUSE, 0xB3 - bool LaunchMail : 1; // VK_LAUNCH_MAIL, 0xB4 - bool SelectMedia : 1; // VK_LAUNCH_MEDIA_SELECT, 0xB5 - bool LaunchApplication1 : 1;// VK_LAUNCH_APP1, 0xB6 - bool LaunchApplication2 : 1;// VK_LAUNCH_APP2, 0xB7 + bool LeftShift : 1; // VK_LSHIFT, 0xA0 + bool RightShift : 1; // VK_RSHIFT, 0xA1 + bool LeftControl : 1; // VK_LCONTROL, 0xA2 + bool RightControl : 1; // VK_RCONTROL, 0xA3 + bool LeftAlt : 1; // VK_LMENU, 0xA4 + bool RightAlt : 1; // VK_RMENU, 0xA5 + bool BrowserBack : 1; // VK_BROWSER_BACK, 0xA6 + bool BrowserForward : 1; // VK_BROWSER_FORWARD, 0xA7 + bool BrowserRefresh : 1; // VK_BROWSER_REFRESH, 0xA8 + bool BrowserStop : 1; // VK_BROWSER_STOP, 0xA9 + bool BrowserSearch : 1; // VK_BROWSER_SEARCH, 0xAA + bool BrowserFavorites : 1; // VK_BROWSER_FAVORITES, 0xAB + bool BrowserHome : 1; // VK_BROWSER_HOME, 0xAC + bool VolumeMute : 1; // VK_VOLUME_MUTE, 0xAD + bool VolumeDown : 1; // VK_VOLUME_DOWN, 0xAE + bool VolumeUp : 1; // VK_VOLUME_UP, 0xAF + bool MediaNextTrack : 1; // VK_MEDIA_NEXT_TRACK, 0xB0 + bool MediaPreviousTrack : 1; // VK_MEDIA_PREV_TRACK, 0xB1 + bool MediaStop : 1; // VK_MEDIA_STOP, 0xB2 + bool MediaPlayPause : 1; // VK_MEDIA_PLAY_PAUSE, 0xB3 + bool LaunchMail : 1; // VK_LAUNCH_MAIL, 0xB4 + bool SelectMedia : 1; // VK_LAUNCH_MEDIA_SELECT, 0xB5 + bool LaunchApplication1 : 1; // VK_LAUNCH_APP1, 0xB6 + bool LaunchApplication2 : 1; // VK_LAUNCH_APP2, 0xB7 bool Reserved14 : 2; - bool OemSemicolon : 1; // VK_OEM_1, 0xBA - bool OemPlus : 1; // VK_OEM_PLUS, 0xBB - bool OemComma : 1; // VK_OEM_COMMA, 0xBC - bool OemMinus : 1; // VK_OEM_MINUS, 0xBD - bool OemPeriod : 1; // VK_OEM_PERIOD, 0xBE - bool OemQuestion : 1; // VK_OEM_2, 0xBF - bool OemTilde : 1; // VK_OEM_3, 0xC0 + bool OemSemicolon : 1; // VK_OEM_1, 0xBA + bool OemPlus : 1; // VK_OEM_PLUS, 0xBB + bool OemComma : 1; // VK_OEM_COMMA, 0xBC + bool OemMinus : 1; // VK_OEM_MINUS, 0xBD + bool OemPeriod : 1; // VK_OEM_PERIOD, 0xBE + bool OemQuestion : 1; // VK_OEM_2, 0xBF + bool OemTilde : 1; // VK_OEM_3, 0xC0 bool Reserved15 : 7; bool Reserved16 : 8; bool Reserved17 : 8; bool Reserved18 : 3; - bool OemOpenBrackets : 1; // VK_OEM_4, 0xDB - bool OemPipe : 1; // VK_OEM_5, 0xDC - bool OemCloseBrackets : 1; // VK_OEM_6, 0xDD - bool OemQuotes : 1; // VK_OEM_7, 0xDE - bool Oem8 : 1; // VK_OEM_8, 0xDF + bool OemOpenBrackets : 1; // VK_OEM_4, 0xDB + bool OemPipe : 1; // VK_OEM_5, 0xDC + bool OemCloseBrackets : 1; // VK_OEM_6, 0xDD + bool OemQuotes : 1; // VK_OEM_7, 0xDE + bool Oem8 : 1; // VK_OEM_8, 0xDF bool Reserved19 : 2; - bool OemBackslash : 1; // VK_OEM_102, 0xE2 + bool OemBackslash : 1; // VK_OEM_102, 0xE2 bool Reserved20 : 2; - bool ProcessKey : 1; // VK_PROCESSKEY, 0xE5 + bool ProcessKey : 1; // VK_PROCESSKEY, 0xE5 bool Reserved21 : 2; bool Reserved22 : 8; bool Reserved23 : 2; - bool OemCopy : 1; // 0XF2 - bool OemAuto : 1; // 0xF3 - bool OemEnlW : 1; // 0xF4 + bool OemCopy : 1; // 0XF2 + bool OemAuto : 1; // 0xF3 + bool OemEnlW : 1; // 0xF4 bool Reserved24 : 1; - bool Attn : 1; // VK_ATTN, 0xF6 - bool Crsel : 1; // VK_CRSEL, 0xF7 - bool Exsel : 1; // VK_EXSEL, 0xF8 - bool EraseEof : 1; // VK_EREOF, 0xF9 - bool Play : 1; // VK_PLAY, 0xFA - bool Zoom : 1; // VK_ZOOM, 0xFB + bool Attn : 1; // VK_ATTN, 0xF6 + bool Crsel : 1; // VK_CRSEL, 0xF7 + bool Exsel : 1; // VK_EXSEL, 0xF8 + bool EraseEof : 1; // VK_EREOF, 0xF9 + bool Play : 1; // VK_PLAY, 0xFA + bool Zoom : 1; // VK_ZOOM, 0xFB bool Reserved25 : 1; - bool Pa1 : 1; // VK_PA1, 0xFD - bool OemClear : 1; // VK_OEM_CLEAR, 0xFE + bool Pa1 : 1; // VK_PA1, 0xFD + bool OemClear : 1; // VK_OEM_CLEAR, 0xFE bool Reserved26 : 1; - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wunknown-warning-option" - #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" - #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-warning-option" +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" +#endif bool __cdecl IsKeyDown(Keys key) const noexcept { if (key <= 0xfe) { - auto ptr = reinterpret_cast(this); - const unsigned int bf = 1u << (key & 0x1f); + auto ptr = reinterpret_cast(this); + const unsigned int bf = 1u << (key & 0x1f); return (ptr[(key >> 5)] & bf) != 0; } return false; @@ -468,16 +479,16 @@ namespace DirectX { if (key <= 0xfe) { - auto ptr = reinterpret_cast(this); - const unsigned int bf = 1u << (key & 0x1f); + auto ptr = reinterpret_cast(this); + const unsigned int bf = 1u << (key & 0x1f); return (ptr[(key >> 5)] & bf) == 0; } return false; } - #ifdef __clang__ - #pragma clang diagnostic pop - #endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif }; class DIRECTX_TOOLKIT_API KeyboardStateTracker @@ -486,14 +497,14 @@ namespace DirectX State released; State pressed; - #ifdef _PREFAST_ - #pragma prefast(push) - #pragma prefast(disable : 26495, "Reset() performs the initialization") - #endif +#ifdef _PREFAST_ +#pragma prefast(push) +#pragma prefast(disable : 26495, "Reset() performs the initialization") +#endif KeyboardStateTracker() noexcept { Reset(); } - #ifdef _PREFAST_ - #pragma prefast(pop) - #endif +#ifdef _PREFAST_ +#pragma prefast(pop) +#endif void __cdecl Update(const State& state) noexcept; @@ -517,25 +528,25 @@ namespace DirectX // Feature detection DIRECTX_TOOLKIT_API bool __cdecl IsConnected() const; - #ifdef USING_COREWINDOW +#ifdef USING_COREWINDOW DIRECTX_TOOLKIT_API void __cdecl SetWindow(ABI::Windows::UI::Core::ICoreWindow* window); - #ifdef __cplusplus_winrt - inline void __cdecl SetWindow(Windows::UI::Core::CoreWindow^ window) +#ifdef __cplusplus_winrt + inline void __cdecl SetWindow(Windows::UI::Core::CoreWindow ^ window) { // See https://msdn.microsoft.com/en-us/library/hh755802.aspx SetWindow(reinterpret_cast(window)); } - #endif - #ifdef CPPWINRT_VERSION +#endif +#ifdef CPPWINRT_VERSION inline void __cdecl SetWindow(winrt::Windows::UI::Core::CoreWindow window) { // See https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/interop-winrt-abi SetWindow(reinterpret_cast(winrt::get_abi(window))); } - #endif - #elif defined(WM_USER) +#endif +#elif defined(WM_USER) DIRECTX_TOOLKIT_API static void __cdecl ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) noexcept; - #endif +#endif // Singleton DIRECTX_TOOLKIT_API static Keyboard& __cdecl Get(); @@ -546,7 +557,7 @@ namespace DirectX std::unique_ptr pImpl; }; -} +} // namespace DirectX #ifdef __clang__ #pragma clang diagnostic pop diff --git a/Inc/Model.h b/Inc/Model.h index aafcc579..8b3d98f8 100644 --- a/Inc/Model.h +++ b/Inc/Model.h @@ -48,13 +48,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -68,7 +68,6 @@ #pragma warning(disable : 4251) #endif - namespace DirectX { inline namespace DX12 @@ -81,39 +80,42 @@ namespace DirectX // Model loading options enum ModelLoaderFlags : uint32_t { - ModelLoader_Default = 0x0, + ModelLoader_Default = 0x0, ModelLoader_MaterialColorsSRGB = 0x1, - ModelLoader_AllowLargeModels = 0x2, - ModelLoader_IncludeBones = 0x4, - ModelLoader_DisableSkinning = 0x8, + ModelLoader_AllowLargeModels = 0x2, + ModelLoader_IncludeBones = 0x4, + ModelLoader_DisableSkinning = 0x8, }; //------------------------------------------------------------------------------ // Frame hierarchy for rigid body and skeletal animation struct DIRECTX_TOOLKIT_API ModelBone { - ModelBone() noexcept : - parentIndex(c_Invalid), - childIndex(c_Invalid), - siblingIndex(c_Invalid) + ModelBone() noexcept + : parentIndex(c_Invalid), + childIndex(c_Invalid), + siblingIndex(c_Invalid) {} - ModelBone(uint32_t parent, uint32_t child, uint32_t sibling) noexcept : - parentIndex(parent), - childIndex(child), - siblingIndex(sibling) + ModelBone(uint32_t parent, uint32_t child, uint32_t sibling) noexcept + : parentIndex(parent), + childIndex(child), + siblingIndex(sibling) {} - uint32_t parentIndex; - uint32_t childIndex; - uint32_t siblingIndex; - std::wstring name; + uint32_t parentIndex; + uint32_t childIndex; + uint32_t siblingIndex; + std::wstring name; using Collection = std::vector; static constexpr uint32_t c_Invalid = uint32_t(-1); - struct aligned_deleter { void operator()(void* p) noexcept { _aligned_free(p); } }; + struct aligned_deleter + { + void operator()(void* p) noexcept { _aligned_free(p); } + }; using TransformArray = std::unique_ptr; @@ -133,39 +135,40 @@ namespace DirectX public: ModelMeshPart(uint32_t partIndex) noexcept; - ModelMeshPart(ModelMeshPart&&) = default; - ModelMeshPart& operator= (ModelMeshPart&&) = default; + ModelMeshPart(ModelMeshPart&&) = default; + ModelMeshPart& operator=(ModelMeshPart&&) = default; - ModelMeshPart(ModelMeshPart const&) = default; - ModelMeshPart& operator= (ModelMeshPart const&) = default; + ModelMeshPart(ModelMeshPart const&) = default; + ModelMeshPart& operator=(ModelMeshPart const&) = default; virtual ~ModelMeshPart(); - using Collection = std::vector>; - using DrawCallback = std::function; + using Collection = std::vector>; + using DrawCallback = std::function; using InputLayoutCollection = std::vector; - uint32_t partIndex; // Unique index assigned per-part in a model. - uint32_t materialIndex; // Index of the material spec to use - uint32_t indexCount; - uint32_t startIndex; - int32_t vertexOffset; - uint32_t vertexStride; - uint32_t vertexCount; - uint32_t indexBufferSize; - uint32_t vertexBufferSize; - D3D_PRIMITIVE_TOPOLOGY primitiveType; - DXGI_FORMAT indexFormat; - SharedGraphicsResource indexBuffer; - SharedGraphicsResource vertexBuffer; - Microsoft::WRL::ComPtr staticIndexBuffer; - Microsoft::WRL::ComPtr staticVertexBuffer; - std::shared_ptr vbDecl; + uint32_t partIndex; // Unique index assigned per-part in a model. + uint32_t materialIndex; // Index of the material spec to use + uint32_t indexCount; + uint32_t startIndex; + int32_t vertexOffset; + uint32_t vertexStride; + uint32_t vertexCount; + uint32_t indexBufferSize; + uint32_t vertexBufferSize; + D3D_PRIMITIVE_TOPOLOGY primitiveType; + DXGI_FORMAT indexFormat; + SharedGraphicsResource indexBuffer; + SharedGraphicsResource vertexBuffer; + Microsoft::WRL::ComPtr staticIndexBuffer; + Microsoft::WRL::ComPtr staticVertexBuffer; + std::shared_ptr vbDecl; // Draw mesh part void __cdecl Draw(_In_ ID3D12GraphicsCommandList* commandList) const; - void __cdecl DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstance = 0) const; + void __cdecl + DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstance = 0) const; // // Utilities for drawing multiple mesh parts @@ -175,23 +178,21 @@ namespace DirectX static void __cdecl DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, const Collection& meshParts); // Draw the mesh with an effect - static void __cdecl DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, const Collection& meshParts, _In_ IEffect* effect); + static void __cdecl + DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, const Collection& meshParts, _In_ IEffect* effect); // Draw the mesh with a callback for each mesh part - static void __cdecl DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, const Collection& meshParts, DrawCallback callback); + static void __cdecl + DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, const Collection& meshParts, DrawCallback callback); // Draw the mesh with a range of effects that mesh parts will index into. // Effects can be any IEffect pointer type (including smart pointer). Value or reference types will not compile. // The iterator passed to this method should have random access capabilities for best performance. template - static void DrawMeshParts( - _In_ ID3D12GraphicsCommandList* commandList, - const Collection& meshParts, - TEffectIterator partEffects) + static void DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, const Collection& meshParts, TEffectIterator partEffects) { // This assert is here to prevent accidental use of containers that would cause undesirable performance penalties. - static_assert( - std::is_base_of::value, + static_assert(std::is_base_of::value, "Providing an iterator without random access capabilities -- such as from std::list -- is not supported."); for (const auto& it : meshParts) @@ -210,15 +211,13 @@ namespace DirectX } template - static void XM_CALLCONV DrawMeshParts( - _In_ ID3D12GraphicsCommandList* commandList, - const Collection& meshParts, - FXMMATRIX world, - TEffectIterator partEffects) + static void XM_CALLCONV DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, + const Collection& meshParts, + FXMMATRIX world, + TEffectIterator partEffects) { // This assert is here to prevent accidental use of containers that would cause undesirable performance penalties. - static_assert( - std::is_base_of::value, + static_assert(std::is_base_of::value, "Providing an iterator without random access capabilities -- such as from std::list -- is not supported."); for (const auto& it : meshParts) @@ -243,17 +242,15 @@ namespace DirectX } template - static void XM_CALLCONV DrawSkinnedMeshParts( - _In_ ID3D12GraphicsCommandList* commandList, - const ModelMesh& mesh, - const Collection& meshParts, - size_t nbones, - _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, - TEffectIterator partEffects); + static void XM_CALLCONV DrawSkinnedMeshParts(_In_ ID3D12GraphicsCommandList* commandList, + const ModelMesh& mesh, + const Collection& meshParts, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + TEffectIterator partEffects); }; - //------------------------------------------------------------------------------ // A mesh consists of one or more model mesh parts class DIRECTX_TOOLKIT_API ModelMesh @@ -261,21 +258,21 @@ namespace DirectX public: ModelMesh() noexcept; - ModelMesh(ModelMesh&&) = default; - ModelMesh& operator= (ModelMesh&&) = default; + ModelMesh(ModelMesh&&) = default; + ModelMesh& operator=(ModelMesh&&) = default; - ModelMesh(ModelMesh const&) = delete; - ModelMesh& operator= (ModelMesh const&) = delete; + ModelMesh(ModelMesh const&) = delete; + ModelMesh& operator=(ModelMesh const&) = delete; virtual ~ModelMesh(); - BoundingSphere boundingSphere; - BoundingBox boundingBox; - ModelMeshPart::Collection opaqueMeshParts; - ModelMeshPart::Collection alphaMeshParts; - uint32_t boneIndex; - std::vector boneInfluences; - std::wstring name; + BoundingSphere boundingSphere; + BoundingBox boundingBox; + ModelMeshPart::Collection opaqueMeshParts; + ModelMeshPart::Collection alphaMeshParts; + uint32_t boneIndex; + std::vector boneInfluences; + std::wstring name; using Collection = std::vector>; @@ -306,12 +303,11 @@ namespace DirectX // Draw rigid-body with bones. template - void XM_CALLCONV DrawOpaque( - _In_ ID3D12GraphicsCommandList* commandList, - size_t nbones, - _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, - TEffectIterator effects) const + void XM_CALLCONV DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + TEffectIterator effects) const { assert(nbones > 0 && boneTransforms != nullptr); XMMATRIX local; @@ -328,12 +324,11 @@ namespace DirectX } template - void XM_CALLCONV DrawAlpha( - _In_ ID3D12GraphicsCommandList* commandList, - size_t nbones, - _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, - TEffectIterator effects) const + void XM_CALLCONV DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + TEffectIterator effects) const { assert(nbones > 0 && boneTransforms != nullptr); XMMATRIX local; @@ -351,31 +346,38 @@ namespace DirectX // Draw using skinning given bone transform array. template - void XM_CALLCONV DrawSkinnedOpaque( - _In_ ID3D12GraphicsCommandList* commandList, - size_t nbones, - _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, - TEffectIterator effects) const + void XM_CALLCONV DrawSkinnedOpaque(_In_ ID3D12GraphicsCommandList* commandList, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + TEffectIterator effects) const { - ModelMeshPart::DrawSkinnedMeshParts(commandList, *this, opaqueMeshParts, - nbones, boneTransforms, world, effects); + ModelMeshPart::DrawSkinnedMeshParts(commandList, + *this, + opaqueMeshParts, + nbones, + boneTransforms, + world, + effects); } template - void XM_CALLCONV DrawSkinnedAlpha( - _In_ ID3D12GraphicsCommandList* commandList, - size_t nbones, - _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, - TEffectIterator effects) const + void XM_CALLCONV DrawSkinnedAlpha(_In_ ID3D12GraphicsCommandList* commandList, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + TEffectIterator effects) const { - ModelMeshPart::DrawSkinnedMeshParts(commandList, *this, alphaMeshParts, - nbones, boneTransforms, world, effects); + ModelMeshPart::DrawSkinnedMeshParts(commandList, + *this, + alphaMeshParts, + nbones, + boneTransforms, + world, + effects); } }; - //------------------------------------------------------------------------------ // A model consists of one or more meshes class DIRECTX_TOOLKIT_API Model @@ -383,18 +385,18 @@ namespace DirectX public: Model() noexcept; - Model(Model&&) = default; - Model& operator= (Model&&) = default; + Model(Model&&) = default; + Model& operator=(Model&&) = default; Model(Model const& other); - Model& operator= (Model const& rhs); + Model& operator=(Model const& rhs); virtual ~Model(); - using EffectCollection = std::vector>; - using ModelMaterialInfo = IEffectFactory::EffectInfo; + using EffectCollection = std::vector>; + using ModelMaterialInfo = IEffectFactory::EffectInfo; using ModelMaterialInfoCollection = std::vector; - using TextureCollection = std::vector; + using TextureCollection = std::vector; // The Model::Draw* functions use variadic templates and perfect-forwarding in order to support future // overloads to the ModelMesh::Draw* family of functions. This means that a new ModelMesh overload can be @@ -402,7 +404,8 @@ namespace DirectX // overload will be selected by the compiler depending on the arguments you provide to the Model method. // Draw all the meshes in the model. - template void DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const + template + void DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { // Draw opaque parts for (const auto& it : meshes) @@ -414,7 +417,8 @@ namespace DirectX } } - template void DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const + template + void DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { // Draw alpha parts for (const auto& it : meshes) @@ -426,14 +430,16 @@ namespace DirectX } } - template void Draw(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const + template + void Draw(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { DrawOpaque(commandList, args...); DrawAlpha(commandList, std::forward(args)...); } // Draw mesh using skinning given bone transform array. - template void DrawSkinnedOpaque(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const + template + void DrawSkinnedOpaque(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { // Draw opaque parts for (const auto& it : meshes) @@ -445,7 +451,8 @@ namespace DirectX } } - template void DrawSkinnedAlpha(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const + template + void DrawSkinnedAlpha(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { // Draw alpha parts for (const auto& it : meshes) @@ -457,7 +464,8 @@ namespace DirectX } } - template void DrawSkinned(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const + template + void DrawSkinned(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { DrawSkinnedOpaque(commandList, args...); DrawSkinnedAlpha(commandList, std::forward(args)...); @@ -467,117 +475,103 @@ namespace DirectX int __cdecl LoadTextures(IEffectTextureFactory& texFactory, int destinationDescriptorOffset = 0) const; // Load texture resources into a new Effect Texture Factory - std::unique_ptr __cdecl LoadTextures( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - _In_opt_z_ const wchar_t* texturesPath = nullptr, + std::unique_ptr __cdecl LoadTextures(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + _In_opt_z_ const wchar_t* texturesPath = nullptr, D3D12_DESCRIPTOR_HEAP_FLAGS flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) const; // Load VB/IB resources for static geometry - void __cdecl LoadStaticBuffers( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - bool keepMemory = false); + void __cdecl LoadStaticBuffers(_In_ ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch, bool keepMemory = false); // Create effects using the default effect factory - EffectCollection __cdecl CreateEffects( - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - _In_ ID3D12DescriptorHeap* textureDescriptorHeap, - _In_ ID3D12DescriptorHeap* samplerDescriptorHeap, - int textureDescriptorOffset = 0, - int samplerDescriptorOffset = 0) const; + EffectCollection __cdecl CreateEffects(const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + _In_ ID3D12DescriptorHeap* textureDescriptorHeap, + _In_ ID3D12DescriptorHeap* samplerDescriptorHeap, + int textureDescriptorOffset = 0, + int samplerDescriptorOffset = 0) const; // Create effects using a custom effect factory - EffectCollection __cdecl CreateEffects( - IEffectFactory& fxFactory, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - int textureDescriptorOffset = 0, - int samplerDescriptorOffset = 0) const; + EffectCollection __cdecl CreateEffects(IEffectFactory& fxFactory, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + int textureDescriptorOffset = 0, + int samplerDescriptorOffset = 0) const; // Compute bone positions based on heirarchy and transform matrices - void __cdecl CopyAbsoluteBoneTransformsTo( - size_t nbones, - _Out_writes_(nbones) XMMATRIX* boneTransforms) const; + void __cdecl CopyAbsoluteBoneTransformsTo(size_t nbones, _Out_writes_(nbones) XMMATRIX* boneTransforms) const; - void __cdecl CopyAbsoluteBoneTransforms( - size_t nbones, - _In_reads_(nbones) const XMMATRIX* inBoneTransforms, - _Out_writes_(nbones) XMMATRIX* outBoneTransforms) const; + void __cdecl CopyAbsoluteBoneTransforms(size_t nbones, + _In_reads_(nbones) const XMMATRIX* inBoneTransforms, + _Out_writes_(nbones) XMMATRIX* outBoneTransforms) const; // Set bone matrices to a set of relative tansforms - void __cdecl CopyBoneTransformsFrom( - size_t nbones, - _In_reads_(nbones) const XMMATRIX* boneTransforms); + void __cdecl CopyBoneTransformsFrom(size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms); // Copies the relative bone matrices to a transform array - void __cdecl CopyBoneTransformsTo( - size_t nbones, - _Out_writes_(nbones) XMMATRIX* boneTransforms) const; + void __cdecl CopyBoneTransformsTo(size_t nbones, _Out_writes_(nbones) XMMATRIX* boneTransforms) const; // Loads a model from a Visual Studio Starter Kit .CMO file - static std::unique_ptr __cdecl CreateFromCMO( - _In_opt_ ID3D12Device* device, - _In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize, - ModelLoaderFlags flags = ModelLoader_Default, - _Out_opt_ size_t* animsOffset = nullptr); - static std::unique_ptr __cdecl CreateFromCMO( - _In_opt_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - ModelLoaderFlags flags = ModelLoader_Default, - _Out_opt_ size_t* animsOffset = nullptr); + static std::unique_ptr __cdecl CreateFromCMO(_In_opt_ ID3D12Device* device, + _In_reads_bytes_(dataSize) const uint8_t* meshData, + _In_ size_t dataSize, + ModelLoaderFlags flags = ModelLoader_Default, + _Out_opt_ size_t* animsOffset = nullptr); + static std::unique_ptr __cdecl CreateFromCMO(_In_opt_ ID3D12Device* device, + _In_z_ const wchar_t* szFileName, + ModelLoaderFlags flags = ModelLoader_Default, + _Out_opt_ size_t* animsOffset = nullptr); // Loads a model from a DirectX SDK .SDKMESH file - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_opt_ ID3D12Device* device, - _In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize, - ModelLoaderFlags flags = ModelLoader_Default); - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_opt_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - ModelLoaderFlags flags = ModelLoader_Default); + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_opt_ ID3D12Device* device, + _In_reads_bytes_(dataSize) const uint8_t* meshData, + _In_ size_t dataSize, + ModelLoaderFlags flags = ModelLoader_Default); + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_opt_ ID3D12Device* device, + _In_z_ const wchar_t* szFileName, + ModelLoaderFlags flags = ModelLoader_Default); // Loads a model from a .VBO file - static std::unique_ptr __cdecl CreateFromVBO( - _In_opt_ ID3D12Device* device, - _In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize, - ModelLoaderFlags flags = ModelLoader_Default); - static std::unique_ptr __cdecl CreateFromVBO( - _In_opt_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - ModelLoaderFlags flags = ModelLoader_Default); - - #ifdef __cpp_lib_byte - static std::unique_ptr __cdecl CreateFromCMO( - _In_opt_ ID3D12Device* device, - _In_reads_bytes_(dataSize) const std::byte* meshData, _In_ size_t dataSize, - ModelLoaderFlags flags = ModelLoader_Default, - _Out_opt_ size_t* animsOffset = nullptr) + static std::unique_ptr __cdecl CreateFromVBO(_In_opt_ ID3D12Device* device, + _In_reads_bytes_(dataSize) const uint8_t* meshData, + _In_ size_t dataSize, + ModelLoaderFlags flags = ModelLoader_Default); + static std::unique_ptr __cdecl + CreateFromVBO(_In_opt_ ID3D12Device* device, _In_z_ const wchar_t* szFileName, ModelLoaderFlags flags = ModelLoader_Default); + +#ifdef __cpp_lib_byte + static std::unique_ptr __cdecl CreateFromCMO(_In_opt_ ID3D12Device* device, + _In_reads_bytes_(dataSize) const std::byte* meshData, + _In_ size_t dataSize, + ModelLoaderFlags flags = ModelLoader_Default, + _Out_opt_ size_t* animsOffset = nullptr) { return CreateFromCMO(device, reinterpret_cast(meshData), dataSize, flags, animsOffset); } - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_opt_ ID3D12Device* device, - _In_reads_bytes_(dataSize) const std::byte* meshData, _In_ size_t dataSize, - ModelLoaderFlags flags = ModelLoader_Default) + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_opt_ ID3D12Device* device, + _In_reads_bytes_(dataSize) const std::byte* meshData, + _In_ size_t dataSize, + ModelLoaderFlags flags = ModelLoader_Default) { return CreateFromSDKMESH(device, reinterpret_cast(meshData), dataSize, flags); } - static std::unique_ptr __cdecl CreateFromVBO( - _In_opt_ ID3D12Device* device, - _In_reads_bytes_(dataSize) const std::byte* meshData, _In_ size_t dataSize, - ModelLoaderFlags flags = ModelLoader_Default) + static std::unique_ptr __cdecl CreateFromVBO(_In_opt_ ID3D12Device* device, + _In_reads_bytes_(dataSize) const std::byte* meshData, + _In_ size_t dataSize, + ModelLoaderFlags flags = ModelLoader_Default) { return CreateFromVBO(device, reinterpret_cast(meshData), dataSize, flags); } - #endif // __cpp_lib_byte +#endif // __cpp_lib_byte // Utility function for getting a GPU descriptor for a mesh part/material index. If there is no texture the // descriptor will be zero. - D3D12_GPU_DESCRIPTOR_HANDLE __cdecl GetGpuTextureHandleForMaterialIndex(uint32_t materialIndex, _In_ ID3D12DescriptorHeap* heap, _In_ size_t descriptorSize, _In_ size_t descriptorOffset) const + D3D12_GPU_DESCRIPTOR_HANDLE __cdecl GetGpuTextureHandleForMaterialIndex(uint32_t materialIndex, + _In_ ID3D12DescriptorHeap* heap, + _In_ size_t descriptorSize, + _In_ size_t descriptorOffset) const { D3D12_GPU_DESCRIPTOR_HANDLE handle = {}; @@ -588,11 +582,11 @@ namespace DirectX if (textureIndex == -1) return handle; - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) handle = heap->GetGPUDescriptorHandleForHeapStart(); - #else +#else std::ignore = heap->GetGPUDescriptorHandleForHeapStart(&handle); - #endif +#endif handle.ptr += static_cast(descriptorSize * (UINT64(textureIndex) + UINT64(descriptorOffset))); return handle; @@ -600,84 +594,71 @@ namespace DirectX // Utility function for updating the matrices in a list of effects. This will SetWorld, SetView and SetProjection // on any effect in the list that derives from IEffectMatrices. - static void XM_CALLCONV UpdateEffectMatrices( - EffectCollection& effects, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX proj); + static void XM_CALLCONV UpdateEffectMatrices(EffectCollection& effects, FXMMATRIX world, CXMMATRIX view, CXMMATRIX proj); // Utility function to transition VB/IB resources for static geometry. - void __cdecl Transition( - _In_ ID3D12GraphicsCommandList* commandList, - D3D12_RESOURCE_STATES stateBeforeVB, - D3D12_RESOURCE_STATES stateAfterVB, - D3D12_RESOURCE_STATES stateBeforeIB, - D3D12_RESOURCE_STATES stateAfterIB); - - ModelMesh::Collection meshes; - ModelMaterialInfoCollection materials; - TextureCollection textureNames; - ModelBone::Collection bones; - ModelBone::TransformArray boneMatrices; - ModelBone::TransformArray invBindPoseMatrices; - std::wstring name; - - #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) - - std::unique_ptr __cdecl LoadTextures( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - _In_opt_z_ const __wchar_t* texturesPath = nullptr, + void __cdecl Transition(_In_ ID3D12GraphicsCommandList* commandList, + D3D12_RESOURCE_STATES stateBeforeVB, + D3D12_RESOURCE_STATES stateAfterVB, + D3D12_RESOURCE_STATES stateBeforeIB, + D3D12_RESOURCE_STATES stateAfterIB); + + ModelMesh::Collection meshes; + ModelMaterialInfoCollection materials; + TextureCollection textureNames; + ModelBone::Collection bones; + ModelBone::TransformArray boneMatrices; + ModelBone::TransformArray invBindPoseMatrices; + std::wstring name; + +#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) + + std::unique_ptr __cdecl LoadTextures(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + _In_opt_z_ const __wchar_t* texturesPath = nullptr, D3D12_DESCRIPTOR_HEAP_FLAGS flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) const; - static std::unique_ptr __cdecl CreateFromCMO( - _In_opt_ ID3D12Device* device, - _In_z_ const __wchar_t* szFileName, - ModelLoaderFlags flags = ModelLoader_Default, - _Out_opt_ size_t* animsOffset = nullptr); + static std::unique_ptr __cdecl CreateFromCMO(_In_opt_ ID3D12Device* device, + _In_z_ const __wchar_t* szFileName, + ModelLoaderFlags flags = ModelLoader_Default, + _Out_opt_ size_t* animsOffset = nullptr); - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_opt_ ID3D12Device* device, - _In_z_ const __wchar_t* szFileName, - ModelLoaderFlags flags = ModelLoader_Default); + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_opt_ ID3D12Device* device, + _In_z_ const __wchar_t* szFileName, + ModelLoaderFlags flags = ModelLoader_Default); - static std::unique_ptr __cdecl CreateFromVBO( - _In_opt_ ID3D12Device* device, - _In_z_ const __wchar_t* szFileName, - ModelLoaderFlags flags = ModelLoader_Default); + static std::unique_ptr __cdecl + CreateFromVBO(_In_opt_ ID3D12Device* device, _In_z_ const __wchar_t* szFileName, ModelLoaderFlags flags = ModelLoader_Default); - #endif // !_NATIVE_WCHAR_T_DEFINED +#endif // !_NATIVE_WCHAR_T_DEFINED private: - std::shared_ptr __cdecl CreateEffectForMeshPart( - IEffectFactory& fxFactory, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - int textureDescriptorOffset, - int samplerDescriptorOffset, - _In_ const ModelMeshPart* part) const; - - void __cdecl ComputeAbsolute(uint32_t index, - CXMMATRIX local, size_t nbones, + std::shared_ptr __cdecl CreateEffectForMeshPart(IEffectFactory& fxFactory, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + int textureDescriptorOffset, + int samplerDescriptorOffset, + _In_ const ModelMeshPart* part) const; + + void __cdecl ComputeAbsolute(uint32_t index, + CXMMATRIX local, + size_t nbones, _In_reads_(nbones) const XMMATRIX* inBoneTransforms, - _Inout_updates_(nbones) XMMATRIX* outBoneTransforms, - size_t& visited) const; + _Inout_updates_(nbones) XMMATRIX* outBoneTransforms, + size_t& visited) const; }; - template - void XM_CALLCONV ModelMeshPart::DrawSkinnedMeshParts( - _In_ ID3D12GraphicsCommandList* commandList, - const ModelMesh& mesh, - const ModelMeshPart::Collection& meshParts, - size_t nbones, - _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, - TEffectIterator partEffects) + void XM_CALLCONV ModelMeshPart::DrawSkinnedMeshParts(_In_ ID3D12GraphicsCommandList* commandList, + const ModelMesh& mesh, + const ModelMeshPart::Collection& meshParts, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + TEffectIterator partEffects) { // This assert is here to prevent accidental use of containers that would cause undesirable performance penalties. - static_assert( - std::is_base_of::value, + static_assert(std::is_base_of::value, "Providing an iterator without random access capabilities -- such as from std::list -- is not supported."); assert(nbones > 0 && boneTransforms != nullptr); @@ -740,8 +721,8 @@ namespace DirectX else if (imatrices) { // Fallback for if we encounter a non-skinning effect in the model - XMMATRIX bm = (mesh.boneIndex != ModelBone::c_Invalid && mesh.boneIndex < nbones) - ? boneTransforms[mesh.boneIndex] : XMMatrixIdentity(); + XMMATRIX bm = (mesh.boneIndex != ModelBone::c_Invalid && mesh.boneIndex < nbones) ? boneTransforms[mesh.boneIndex] : + XMMatrixIdentity(); imatrices->SetWorld(XMMatrixMultiply(bm, world)); } @@ -752,18 +733,18 @@ namespace DirectX } } - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec" - #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec" +#endif DEFINE_ENUM_FLAG_OPERATORS(ModelLoaderFlags) - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - } -} +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + } // namespace DX12 +} // namespace DirectX #if defined(DIRECTX_TOOLKIT_IMPORT) && defined(_MSC_VER) #pragma warning(pop) diff --git a/Inc/Mouse.h b/Inc/Mouse.h index 5151c802..8cda7cac 100644 --- a/Inc/Mouse.h +++ b/Inc/Mouse.h @@ -27,7 +27,7 @@ #ifdef USING_GAMEINPUT #include #if defined(_MSC_VER) && (defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION)) -#pragma comment(lib,"gameinput.lib") +#pragma comment(lib, "gameinput.lib") #endif #endif @@ -35,19 +35,31 @@ #include #ifdef USING_COREWINDOW -namespace ABI { namespace Windows { namespace UI { namespace Core { struct ICoreWindow; } } } } +namespace ABI +{ + namespace Windows + { + namespace UI + { + namespace Core + { + struct ICoreWindow; + } + } // namespace UI + } // namespace Windows +} // namespace ABI #endif #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -61,7 +73,6 @@ namespace ABI { namespace Windows { namespace UI { namespace Core { struct ICore #pragma clang diagnostic ignored "-Wunknown-pragmas" #endif - namespace DirectX { class Mouse @@ -69,10 +80,10 @@ namespace DirectX public: DIRECTX_TOOLKIT_API Mouse() noexcept(false); - DIRECTX_TOOLKIT_API Mouse(Mouse&&) noexcept; - DIRECTX_TOOLKIT_API Mouse& operator= (Mouse&&) noexcept; + DIRECTX_TOOLKIT_API Mouse(Mouse&&) noexcept; + DIRECTX_TOOLKIT_API Mouse& operator=(Mouse&&) noexcept; - Mouse(Mouse const&) = delete; + Mouse(Mouse const&) = delete; Mouse& operator=(Mouse const&) = delete; DIRECTX_TOOLKIT_API virtual ~Mouse(); @@ -85,15 +96,15 @@ namespace DirectX struct State { - bool leftButton; - bool middleButton; - bool rightButton; - bool xButton1; - bool xButton2; - int x; - int y; - int scrollWheelValue; - Mode positionMode; + bool leftButton; + bool middleButton; + bool rightButton; + bool xButton1; + bool xButton2; + int x; + int y; + int scrollWheelValue; + Mode positionMode; }; class DIRECTX_TOOLKIT_API ButtonStateTracker @@ -101,10 +112,10 @@ namespace DirectX public: enum ButtonState : uint32_t { - UP = 0, // Button is up - HELD = 1, // Button is held down - RELEASED = 2, // Button was just released - PRESSED = 3, // Buton was just pressed + UP = 0, // Button is up + HELD = 1, // Button is held down + RELEASED = 2, // Button was just released + PRESSED = 3, // Buton was just pressed }; ButtonState leftButton; @@ -113,14 +124,14 @@ namespace DirectX ButtonState xButton1; ButtonState xButton2; - #ifdef _PREFAST_ - #pragma prefast(push) - #pragma prefast(disable : 26495, "Reset() performs the initialization") - #endif +#ifdef _PREFAST_ +#pragma prefast(push) +#pragma prefast(disable : 26495, "Reset() performs the initialization") +#endif ButtonStateTracker() noexcept { Reset(); } - #ifdef _PREFAST_ - #pragma prefast(pop) - #endif +#ifdef _PREFAST_ +#pragma prefast(pop) +#endif void __cdecl Update(const State& state) noexcept; @@ -151,32 +162,32 @@ namespace DirectX DIRECTX_TOOLKIT_API bool __cdecl IsVisible() const noexcept; DIRECTX_TOOLKIT_API void __cdecl SetVisible(bool visible); - #ifdef USING_COREWINDOW +#ifdef USING_COREWINDOW DIRECTX_TOOLKIT_API void __cdecl SetWindow(ABI::Windows::UI::Core::ICoreWindow* window); - #ifdef __cplusplus_winrt - inline void __cdecl SetWindow(Windows::UI::Core::CoreWindow^ window) +#ifdef __cplusplus_winrt + inline void __cdecl SetWindow(Windows::UI::Core::CoreWindow ^ window) { // See https://msdn.microsoft.com/en-us/library/hh755802.aspx SetWindow(reinterpret_cast(window)); } - #endif - #ifdef CPPWINRT_VERSION +#endif +#ifdef CPPWINRT_VERSION inline void __cdecl SetWindow(winrt::Windows::UI::Core::CoreWindow window) { // See https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/interop-winrt-abi SetWindow(reinterpret_cast(winrt::get_abi(window))); } - #endif +#endif DIRECTX_TOOLKIT_API static void __cdecl SetDpi(float dpi); - #elif defined(WM_USER) - DIRECTX_TOOLKIT_API void __cdecl SetWindow(HWND window); +#elif defined(WM_USER) + DIRECTX_TOOLKIT_API void __cdecl SetWindow(HWND window); DIRECTX_TOOLKIT_API static void __cdecl ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam); - #ifdef _GAMING_XBOX +#ifdef _GAMING_XBOX DIRECTX_TOOLKIT_API static void __cdecl SetResolution(float scale); - #endif - #endif +#endif +#endif // Singleton DIRECTX_TOOLKIT_API static Mouse& __cdecl Get(); @@ -187,7 +198,7 @@ namespace DirectX std::unique_ptr pImpl; }; -} +} // namespace DirectX #ifdef __clang__ #pragma clang diagnostic pop diff --git a/Inc/PostProcess.h b/Inc/PostProcess.h index bf2cfad8..90db8500 100644 --- a/Inc/PostProcess.h +++ b/Inc/PostProcess.h @@ -30,13 +30,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -45,7 +45,6 @@ #endif #endif - namespace DirectX { inline namespace DX12 @@ -57,18 +56,17 @@ namespace DirectX public: virtual ~IPostProcess() = default; - IPostProcess(const IPostProcess&) = delete; + IPostProcess(const IPostProcess&) = delete; IPostProcess& operator=(const IPostProcess&) = delete; virtual void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) = 0; protected: - IPostProcess() = default; - IPostProcess(IPostProcess&&) = default; + IPostProcess() = default; + IPostProcess(IPostProcess&&) = default; IPostProcess& operator=(IPostProcess&&) = default; }; - //------------------------------------------------------------------------------ // Basic post-process class BasicPostProcess : public IPostProcess @@ -87,16 +85,13 @@ namespace DirectX Effect_Max }; - DIRECTX_TOOLKIT_API BasicPostProcess( - _In_ ID3D12Device* device, - const RenderTargetState& rtState, - Effect fx); + DIRECTX_TOOLKIT_API BasicPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx); - DIRECTX_TOOLKIT_API BasicPostProcess(BasicPostProcess&&) noexcept; - DIRECTX_TOOLKIT_API BasicPostProcess& operator= (BasicPostProcess&&) noexcept; + DIRECTX_TOOLKIT_API BasicPostProcess(BasicPostProcess&&) noexcept; + DIRECTX_TOOLKIT_API BasicPostProcess& operator=(BasicPostProcess&&) noexcept; - BasicPostProcess(BasicPostProcess const&) = delete; - BasicPostProcess& operator= (BasicPostProcess const&) = delete; + BasicPostProcess(BasicPostProcess const&) = delete; + BasicPostProcess& operator=(BasicPostProcess const&) = delete; DIRECTX_TOOLKIT_API ~BasicPostProcess() override; @@ -122,7 +117,6 @@ namespace DirectX std::unique_ptr pImpl; }; - //------------------------------------------------------------------------------ // Dual-texure post-process class DualPostProcess : public IPostProcess @@ -135,16 +129,13 @@ namespace DirectX Effect_Max }; - DIRECTX_TOOLKIT_API DualPostProcess( - _In_ ID3D12Device* device, - const RenderTargetState& rtState, - Effect fx); + DIRECTX_TOOLKIT_API DualPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx); - DIRECTX_TOOLKIT_API DualPostProcess(DualPostProcess&&) noexcept; - DIRECTX_TOOLKIT_API DualPostProcess& operator= (DualPostProcess&&) noexcept; + DIRECTX_TOOLKIT_API DualPostProcess(DualPostProcess&&) noexcept; + DIRECTX_TOOLKIT_API DualPostProcess& operator=(DualPostProcess&&) noexcept; - DualPostProcess(DualPostProcess const&) = delete; - DualPostProcess& operator= (DualPostProcess const&) = delete; + DualPostProcess(DualPostProcess const&) = delete; + DualPostProcess& operator=(DualPostProcess const&) = delete; DIRECTX_TOOLKIT_API ~DualPostProcess() override; @@ -159,7 +150,8 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetMergeParameters(float weight1, float weight2); // Sets parameters for BloomCombine - DIRECTX_TOOLKIT_API void __cdecl SetBloomCombineParameters(float bloom, float base, float bloomSaturation, float baseSaturation); + DIRECTX_TOOLKIT_API void __cdecl + SetBloomCombineParameters(float bloom, float base, float bloomSaturation, float baseSaturation); private: // Private implementation. @@ -168,7 +160,6 @@ namespace DirectX std::unique_ptr pImpl; }; - //------------------------------------------------------------------------------ // Tone-map post-process class ToneMapPostProcess : public IPostProcess @@ -177,9 +168,9 @@ namespace DirectX // Tone-mapping operator enum Operator : uint32_t { - None, // Pass-through - Saturate, // Clamp [0,1] - Reinhard, // x/(1+x) + None, // Pass-through + Saturate, // Clamp [0,1] + Reinhard, // x/(1+x) ACESFilmic, Operator_Max }; @@ -187,9 +178,9 @@ namespace DirectX // Electro-Optical Transfer Function (EOTF) enum TransferFunction : uint32_t { - Linear, // Pass-through - SRGB, // sRGB (Rec.709 and approximate sRGB display curve) - ST2084, // HDR10 (Rec.2020 color primaries and ST.2084 display curve) + Linear, // Pass-through + SRGB, // sRGB (Rec.709 and approximate sRGB display curve) + ST2084, // HDR10 (Rec.2020 color primaries and ST.2084 display curve) TransferFunction_Max }; @@ -201,20 +192,21 @@ namespace DirectX HDTV_to_DCI_P3_D65, // Rec.709 to DCI-P3-D65 (a.k.a Display P3 or P3D65) }; - DIRECTX_TOOLKIT_API ToneMapPostProcess( - _In_ ID3D12Device* device, - const RenderTargetState& rtState, - Operator op, TransferFunction func - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) - , bool mrt = false - #endif + DIRECTX_TOOLKIT_API ToneMapPostProcess(_In_ ID3D12Device* device, + const RenderTargetState& rtState, + Operator op, + TransferFunction func +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) + , + bool mrt = false +#endif ); - DIRECTX_TOOLKIT_API ToneMapPostProcess(ToneMapPostProcess&&) noexcept; - DIRECTX_TOOLKIT_API ToneMapPostProcess& operator= (ToneMapPostProcess&&) noexcept; + DIRECTX_TOOLKIT_API ToneMapPostProcess(ToneMapPostProcess&&) noexcept; + DIRECTX_TOOLKIT_API ToneMapPostProcess& operator=(ToneMapPostProcess&&) noexcept; - ToneMapPostProcess(ToneMapPostProcess const&) = delete; - ToneMapPostProcess& operator= (ToneMapPostProcess const&) = delete; + ToneMapPostProcess(ToneMapPostProcess const&) = delete; + ToneMapPostProcess& operator=(ToneMapPostProcess const&) = delete; DIRECTX_TOOLKIT_API ~ToneMapPostProcess() override; @@ -240,5 +232,5 @@ namespace DirectX std::unique_ptr pImpl; }; - } -} + } // namespace DX12 +} // namespace DirectX diff --git a/Inc/PrimitiveBatch.h b/Inc/PrimitiveBatch.h index 0a503714..95af3619 100644 --- a/Inc/PrimitiveBatch.h +++ b/Inc/PrimitiveBatch.h @@ -29,13 +29,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -44,7 +44,6 @@ #endif #endif - namespace DirectX { inline namespace DX12 @@ -57,11 +56,11 @@ namespace DirectX protected: DIRECTX_TOOLKIT_API PrimitiveBatchBase(_In_ ID3D12Device* device, size_t maxIndices, size_t maxVertices, size_t vertexSize); - DIRECTX_TOOLKIT_API PrimitiveBatchBase(PrimitiveBatchBase&&) noexcept; - DIRECTX_TOOLKIT_API PrimitiveBatchBase& operator= (PrimitiveBatchBase&&) noexcept; + DIRECTX_TOOLKIT_API PrimitiveBatchBase(PrimitiveBatchBase&&) noexcept; + DIRECTX_TOOLKIT_API PrimitiveBatchBase& operator=(PrimitiveBatchBase&&) noexcept; - PrimitiveBatchBase(PrimitiveBatchBase const&) = delete; - PrimitiveBatchBase& operator= (PrimitiveBatchBase const&) = delete; + PrimitiveBatchBase(PrimitiveBatchBase const&) = delete; + PrimitiveBatchBase& operator=(PrimitiveBatchBase const&) = delete; DIRECTX_TOOLKIT_API virtual ~PrimitiveBatchBase(); @@ -72,11 +71,12 @@ namespace DirectX protected: // Internal, untyped drawing method. - DIRECTX_TOOLKIT_API void __cdecl Draw( - D3D_PRIMITIVE_TOPOLOGY topology, - bool isIndexed, _In_opt_count_(indexCount) uint16_t const* indices, size_t indexCount, - size_t vertexCount, - _Outptr_ void** pMappedVertices); + DIRECTX_TOOLKIT_API void __cdecl Draw(D3D_PRIMITIVE_TOPOLOGY topology, + bool isIndexed, + _In_opt_count_(indexCount) uint16_t const* indices, + size_t indexCount, + size_t vertexCount, + _Outptr_ void** pMappedVertices); private: // Private implementation. @@ -84,7 +84,7 @@ namespace DirectX std::unique_ptr pImpl; }; - } + } // namespace Private // Template makes the API typesafe, eg. PrimitiveBatch. template @@ -93,23 +93,20 @@ namespace DirectX static constexpr size_t DefaultBatchSize = 4096; public: - explicit PrimitiveBatch( - _In_ ID3D12Device* device, - size_t maxIndices = DefaultBatchSize * 3, - size_t maxVertices = DefaultBatchSize) + explicit PrimitiveBatch(_In_ ID3D12Device* device, + size_t maxIndices = DefaultBatchSize * 3, + size_t maxVertices = DefaultBatchSize) : PrimitiveBatchBase(device, maxIndices, maxVertices, sizeof(TVertex)) {} - PrimitiveBatch(PrimitiveBatch&&) = default; - PrimitiveBatch& operator= (PrimitiveBatch&&) = default; + PrimitiveBatch(PrimitiveBatch&&) = default; + PrimitiveBatch& operator=(PrimitiveBatch&&) = default; - PrimitiveBatch(PrimitiveBatch const&) = delete; - PrimitiveBatch& operator= (PrimitiveBatch const&) = delete; + PrimitiveBatch(PrimitiveBatch const&) = delete; + PrimitiveBatch& operator=(PrimitiveBatch const&) = delete; // Similar to the D3D9 API DrawPrimitiveUP. - void Draw( - D3D_PRIMITIVE_TOPOLOGY topology, - _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount) + void Draw(D3D_PRIMITIVE_TOPOLOGY topology, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount) { void* mappedVertices; @@ -118,12 +115,12 @@ namespace DirectX memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex)); } - // Similar to the D3D9 API DrawIndexedPrimitiveUP. - void DrawIndexed( - D3D_PRIMITIVE_TOPOLOGY topology, - _In_reads_(indexCount) uint16_t const* indices, size_t indexCount, - _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount) + void DrawIndexed(D3D_PRIMITIVE_TOPOLOGY topology, + _In_reads_(indexCount) uint16_t const* indices, + size_t indexCount, + _In_reads_(vertexCount) TVertex const* vertices, + size_t vertexCount) { void* mappedVertices; @@ -132,10 +129,7 @@ namespace DirectX memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex)); } - - void DrawLine( - TVertex const& v1, - TVertex const& v2) + void DrawLine(TVertex const& v1, TVertex const& v2) { TVertex* mappedVertices; @@ -145,33 +139,34 @@ namespace DirectX mappedVertices[1] = v2; } - - void DrawTriangle( - TVertex const& v1, - TVertex const& v2, - TVertex const& v3) + void DrawTriangle(TVertex const& v1, TVertex const& v2, TVertex const& v3) { TVertex* mappedVertices; - PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, false, nullptr, 0, 3, reinterpret_cast(&mappedVertices)); + PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + false, + nullptr, + 0, + 3, + reinterpret_cast(&mappedVertices)); mappedVertices[0] = v1; mappedVertices[1] = v2; mappedVertices[2] = v3; } - - void DrawQuad( - TVertex const& v1, - TVertex const& v2, - TVertex const& v3, - TVertex const& v4) + void DrawQuad(TVertex const& v1, TVertex const& v2, TVertex const& v3, TVertex const& v4) { static const uint16_t quadIndices[] = { 0, 1, 2, 0, 2, 3 }; TVertex* mappedVertices; - PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, true, quadIndices, 6, 4, reinterpret_cast(&mappedVertices)); + PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + true, + quadIndices, + 6, + 4, + reinterpret_cast(&mappedVertices)); mappedVertices[0] = v1; mappedVertices[1] = v2; @@ -179,5 +174,5 @@ namespace DirectX mappedVertices[3] = v4; } }; - } -} + } // namespace DX12 +} // namespace DirectX diff --git a/Inc/RenderTargetState.h b/Inc/RenderTargetState.h index 84ecca0a..1df9567c 100644 --- a/Inc/RenderTargetState.h +++ b/Inc/RenderTargetState.h @@ -28,13 +28,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -43,7 +43,6 @@ #endif #endif - namespace DirectX { // Encapsulates all render target state when creating pipeline state objects @@ -51,89 +50,82 @@ namespace DirectX { public: RenderTargetState() noexcept - : sampleMask(~0U) - , numRenderTargets(0) - , rtvFormats{} - , dsvFormat(DXGI_FORMAT_UNKNOWN) - , sampleDesc{} - , nodeMask(0) + : sampleMask(~0U), + numRenderTargets(0), + rtvFormats{}, + dsvFormat(DXGI_FORMAT_UNKNOWN), + sampleDesc{}, + nodeMask(0) {} - RenderTargetState(const RenderTargetState&) = default; + RenderTargetState(const RenderTargetState&) = default; RenderTargetState& operator=(const RenderTargetState&) = default; - RenderTargetState(RenderTargetState&&) = default; + RenderTargetState(RenderTargetState&&) = default; RenderTargetState& operator=(RenderTargetState&&) = default; // Single render target convenience constructor - RenderTargetState( - _In_ DXGI_FORMAT rtFormat, - _In_ DXGI_FORMAT dsFormat) noexcept - : sampleMask(UINT_MAX) - , numRenderTargets(1) - , rtvFormats{} - , dsvFormat(dsFormat) - , sampleDesc{} - , nodeMask(0) + RenderTargetState(_In_ DXGI_FORMAT rtFormat, _In_ DXGI_FORMAT dsFormat) noexcept + : sampleMask(UINT_MAX), + numRenderTargets(1), + rtvFormats{}, + dsvFormat(dsFormat), + sampleDesc{}, + nodeMask(0) { sampleDesc.Count = 1; - rtvFormats[0] = rtFormat; + rtvFormats[0] = rtFormat; } // MSAA single render target convenience constructor - RenderTargetState( - _In_ DXGI_FORMAT rtFormat, - _In_ DXGI_FORMAT dsFormat, - _In_ uint32_t sampleCount, - _In_ uint32_t quality = 0) noexcept - : sampleMask(UINT_MAX) - , numRenderTargets(1) - , rtvFormats{} - , dsvFormat(dsFormat) - , sampleDesc{ sampleCount, quality } - , nodeMask(0) + RenderTargetState(_In_ DXGI_FORMAT rtFormat, + _In_ DXGI_FORMAT dsFormat, + _In_ uint32_t sampleCount, + _In_ uint32_t quality = 0) noexcept + : sampleMask(UINT_MAX), + numRenderTargets(1), + rtvFormats{}, + dsvFormat(dsFormat), + sampleDesc{ sampleCount, quality }, + nodeMask(0) { rtvFormats[0] = rtFormat; } // Convenience constructors converting from DXGI_SWAPCHAIN_DESC - #if defined(__dxgi_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) - RenderTargetState( - _In_ const DXGI_SWAP_CHAIN_DESC* desc, - _In_ DXGI_FORMAT dsFormat) noexcept - : sampleMask(UINT_MAX) - , numRenderTargets(1) - , rtvFormats{} - , dsvFormat(dsFormat) - , sampleDesc{} - , nodeMask(0) +#if defined(__dxgi_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) + RenderTargetState(_In_ const DXGI_SWAP_CHAIN_DESC* desc, _In_ DXGI_FORMAT dsFormat) noexcept + : sampleMask(UINT_MAX), + numRenderTargets(1), + rtvFormats{}, + dsvFormat(dsFormat), + sampleDesc{}, + nodeMask(0) { rtvFormats[0] = desc->BufferDesc.Format; - sampleDesc = desc->SampleDesc; + sampleDesc = desc->SampleDesc; } - #endif +#endif - #if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) - RenderTargetState( - _In_ const DXGI_SWAP_CHAIN_DESC1* desc, - _In_ DXGI_FORMAT dsFormat) noexcept - : sampleMask(UINT_MAX) - , numRenderTargets(1) - , rtvFormats{} - , dsvFormat(dsFormat) - , sampleDesc{} - , nodeMask(0) +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) + RenderTargetState(_In_ const DXGI_SWAP_CHAIN_DESC1* desc, _In_ DXGI_FORMAT dsFormat) noexcept + : sampleMask(UINT_MAX), + numRenderTargets(1), + rtvFormats{}, + dsvFormat(dsFormat), + sampleDesc{}, + nodeMask(0) { rtvFormats[0] = desc->Format; - sampleDesc = desc->SampleDesc; + sampleDesc = desc->SampleDesc; } - #endif +#endif - uint32_t sampleMask; - uint32_t numRenderTargets; - DXGI_FORMAT rtvFormats[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; - DXGI_FORMAT dsvFormat; - DXGI_SAMPLE_DESC sampleDesc; - uint32_t nodeMask; + uint32_t sampleMask; + uint32_t numRenderTargets; + DXGI_FORMAT rtvFormats[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; + DXGI_FORMAT dsvFormat; + DXGI_SAMPLE_DESC sampleDesc; + uint32_t nodeMask; }; -} +} // namespace DirectX diff --git a/Inc/ResourceUploadBatch.h b/Inc/ResourceUploadBatch.h index 04f069d0..75dab82f 100644 --- a/Inc/ResourceUploadBatch.h +++ b/Inc/ResourceUploadBatch.h @@ -31,13 +31,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -46,7 +46,6 @@ #endif #endif - namespace DirectX { // Has a command list of it's own so it can upload at any time. @@ -55,11 +54,11 @@ namespace DirectX public: DIRECTX_TOOLKIT_API explicit ResourceUploadBatch(_In_ ID3D12Device* device) noexcept(false); - DIRECTX_TOOLKIT_API ResourceUploadBatch(ResourceUploadBatch&&) noexcept; - DIRECTX_TOOLKIT_API ResourceUploadBatch& operator= (ResourceUploadBatch&&) noexcept; + DIRECTX_TOOLKIT_API ResourceUploadBatch(ResourceUploadBatch&&) noexcept; + DIRECTX_TOOLKIT_API ResourceUploadBatch& operator=(ResourceUploadBatch&&) noexcept; - ResourceUploadBatch(ResourceUploadBatch const&) = delete; - ResourceUploadBatch& operator= (ResourceUploadBatch const&) = delete; + ResourceUploadBatch(ResourceUploadBatch const&) = delete; + ResourceUploadBatch& operator=(ResourceUploadBatch const&) = delete; DIRECTX_TOOLKIT_API virtual ~ResourceUploadBatch(); @@ -68,25 +67,20 @@ namespace DirectX // Asynchronously uploads a resource. The memory in subRes is copied. // The resource must be in the COPY_DEST state. - DIRECTX_TOOLKIT_API void __cdecl Upload( - _In_ ID3D12Resource* resource, - uint32_t subresourceIndexStart, + DIRECTX_TOOLKIT_API void __cdecl Upload(_In_ ID3D12Resource* resource, + uint32_t subresourceIndexStart, _In_reads_(numSubresources) const D3D12_SUBRESOURCE_DATA* subRes, - uint32_t numSubresources); + uint32_t numSubresources); - DIRECTX_TOOLKIT_API void __cdecl Upload( - _In_ ID3D12Resource* resource, - const SharedGraphicsResource& buffer); + DIRECTX_TOOLKIT_API void __cdecl Upload(_In_ ID3D12Resource* resource, const SharedGraphicsResource& buffer); // Asynchronously generate mips from a resource. // Resource must be in the PIXEL_SHADER_RESOURCE state DIRECTX_TOOLKIT_API void __cdecl GenerateMips(_In_ ID3D12Resource* resource); // Transition a resource once you're done with it - DIRECTX_TOOLKIT_API void __cdecl Transition( - _In_ ID3D12Resource* resource, - D3D12_RESOURCE_STATES stateBefore, - D3D12_RESOURCE_STATES stateAfter); + DIRECTX_TOOLKIT_API void __cdecl + Transition(_In_ ID3D12Resource* resource, D3D12_RESOURCE_STATES stateBefore, D3D12_RESOURCE_STATES stateAfter); // Submits all the uploads to the driver. // No more uploads can happen after this call until Begin is called again. @@ -102,4 +96,4 @@ namespace DirectX std::unique_ptr pImpl; }; -} +} // namespace DirectX diff --git a/Inc/ScreenGrab.h b/Inc/ScreenGrab.h index dce2a34c..24277884 100644 --- a/Inc/ScreenGrab.h +++ b/Inc/ScreenGrab.h @@ -36,19 +36,19 @@ #endif #ifdef _MSC_VER -#pragma comment(lib,"uuid.lib") +#pragma comment(lib, "uuid.lib") #endif #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -57,26 +57,23 @@ #endif #endif - namespace DirectX { DIRECTX_TOOLKIT_API - HRESULT __cdecl SaveDDSTextureToFile( - _In_ ID3D12CommandQueue* pCommandQueue, - _In_ ID3D12Resource* pSource, - _In_z_ const wchar_t* fileName, - D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET) noexcept; + HRESULT __cdecl SaveDDSTextureToFile(_In_ ID3D12CommandQueue* pCommandQueue, + _In_ ID3D12Resource* pSource, + _In_z_ const wchar_t* fileName, + D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl SaveWICTextureToFile( - _In_ ID3D12CommandQueue* pCommandQ, - _In_ ID3D12Resource* pSource, - REFGUID guidContainerFormat, - _In_z_ const wchar_t* fileName, - D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET, - _In_opt_ const GUID* targetFormat = nullptr, - _In_ std::function setCustomProps = nullptr, - bool forceSRGB = false); -} + HRESULT __cdecl SaveWICTextureToFile(_In_ ID3D12CommandQueue* pCommandQ, + _In_ ID3D12Resource* pSource, + REFGUID guidContainerFormat, + _In_z_ const wchar_t* fileName, + D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET, + _In_opt_ const GUID* targetFormat = nullptr, + _In_ std::function setCustomProps = nullptr, + bool forceSRGB = false); +} // namespace DirectX diff --git a/Inc/SimpleMath.h b/Inc/SimpleMath.h index d0d85657..6fa6e9b2 100644 --- a/Inc/SimpleMath.h +++ b/Inc/SimpleMath.h @@ -31,13 +31,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -58,7 +58,6 @@ #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" #endif - namespace DirectX { namespace SimpleMath @@ -79,34 +78,79 @@ namespace DirectX long height; // Creators - Rectangle() noexcept : x(0), y(0), width(0), height(0) {} - constexpr Rectangle(long ix, long iy, long iw, long ih) noexcept : x(ix), y(iy), width(iw), height(ih) {} - explicit Rectangle(const RECT& rct) noexcept : x(rct.left), y(rct.top), width(rct.right - rct.left), height(rct.bottom - rct.top) {} + Rectangle() noexcept + : x(0), + y(0), + width(0), + height(0) + {} + constexpr Rectangle(long ix, long iy, long iw, long ih) noexcept + : x(ix), + y(iy), + width(iw), + height(ih) + {} + explicit Rectangle(const RECT& rct) noexcept + : x(rct.left), + y(rct.top), + width(rct.right - rct.left), + height(rct.bottom - rct.top) + {} - Rectangle(const Rectangle&) = default; + Rectangle(const Rectangle&) = default; Rectangle& operator=(const Rectangle&) = default; - Rectangle(Rectangle&&) = default; + Rectangle(Rectangle&&) = default; Rectangle& operator=(Rectangle&&) = default; - operator RECT() noexcept { RECT rct; rct.left = x; rct.top = y; rct.right = (x + width); rct.bottom = (y + height); return rct; } - #ifdef __cplusplus_winrt - operator Windows::Foundation::Rect() noexcept { return Windows::Foundation::Rect(float(x), float(y), float(width), float(height)); } - #endif + operator RECT() noexcept + { + RECT rct; + rct.left = x; + rct.top = y; + rct.right = (x + width); + rct.bottom = (y + height); + return rct; + } +#ifdef __cplusplus_winrt + operator Windows::Foundation::Rect() noexcept + { + return Windows::Foundation::Rect(float(x), float(y), float(width), float(height)); + } +#endif // Comparison operators - #if (__cplusplus >= 202002L) - bool operator == (const Rectangle&) const = default; - auto operator <=> (const Rectangle&) const = default; - #else - bool operator == (const Rectangle& r) const noexcept { return (x == r.x) && (y == r.y) && (width == r.width) && (height == r.height); } - bool operator != (const Rectangle& r) const noexcept { return (x != r.x) || (y != r.y) || (width != r.width) || (height != r.height); } - #endif - bool operator == (const RECT& rct) const noexcept { return (x == rct.left) && (y == rct.top) && (width == (rct.right - rct.left)) && (height == (rct.bottom - rct.top)); } - bool operator != (const RECT& rct) const noexcept { return (x != rct.left) || (y != rct.top) || (width != (rct.right - rct.left)) || (height != (rct.bottom - rct.top)); } +#if (__cplusplus >= 202002L) + bool operator==(const Rectangle&) const = default; + auto operator<= > (const Rectangle&) const = default; +#else + bool operator==(const Rectangle& r) const noexcept + { + return (x == r.x) && (y == r.y) && (width == r.width) && (height == r.height); + } + bool operator!=(const Rectangle& r) const noexcept + { + return (x != r.x) || (y != r.y) || (width != r.width) || (height != r.height); + } +#endif + bool operator==(const RECT& rct) const noexcept + { + return (x == rct.left) && (y == rct.top) && (width == (rct.right - rct.left)) && (height == (rct.bottom - rct.top)); + } + bool operator!=(const RECT& rct) const noexcept + { + return (x != rct.left) || (y != rct.top) || (width != (rct.right - rct.left)) || (height != (rct.bottom - rct.top)); + } // Assignment operators - Rectangle& operator=(_In_ const RECT& rct) noexcept { x = rct.left; y = rct.top; width = (rct.right - rct.left); height = (rct.bottom - rct.top); return *this; } + Rectangle& operator=(_In_ const RECT& rct) noexcept + { + x = rct.left; + y = rct.top; + width = (rct.right - rct.left); + height = (rct.bottom - rct.top); + return *this; + } // Rectangle operations Vector2 Location() const noexcept; @@ -116,59 +160,121 @@ namespace DirectX bool Contains(long ix, long iy) const noexcept { return (x <= ix) && (ix < (x + width)) && (y <= iy) && (iy < (y + height)); } bool Contains(const Vector2& point) const noexcept; - bool Contains(const Rectangle& r) const noexcept { return (x <= r.x) && ((r.x + r.width) <= (x + width)) && (y <= r.y) && ((r.y + r.height) <= (y + height)); } - bool Contains(const RECT& rct) const noexcept { return (x <= rct.left) && (rct.right <= (x + width)) && (y <= rct.top) && (rct.bottom <= (y + height)); } + bool Contains(const Rectangle& r) const noexcept + { + return (x <= r.x) && ((r.x + r.width) <= (x + width)) && (y <= r.y) && ((r.y + r.height) <= (y + height)); + } + bool Contains(const RECT& rct) const noexcept + { + return (x <= rct.left) && (rct.right <= (x + width)) && (y <= rct.top) && (rct.bottom <= (y + height)); + } void Inflate(long horizAmount, long vertAmount) noexcept; - bool Intersects(const Rectangle& r) const noexcept { return (r.x < (x + width)) && (x < (r.x + r.width)) && (r.y < (y + height)) && (y < (r.y + r.height)); } - bool Intersects(const RECT& rct) const noexcept { return (rct.left < (x + width)) && (x < rct.right) && (rct.top < (y + height)) && (y < rct.bottom); } - - void Offset(long ox, long oy) noexcept { x += ox; y += oy; } + bool Intersects(const Rectangle& r) const noexcept + { + return (r.x < (x + width)) && (x < (r.x + r.width)) && (r.y < (y + height)) && (y < (r.y + r.height)); + } + bool Intersects(const RECT& rct) const noexcept + { + return (rct.left < (x + width)) && (x < rct.right) && (rct.top < (y + height)) && (y < rct.bottom); + } + + void Offset(long ox, long oy) noexcept + { + x += ox; + y += oy; + } // Static functions static Rectangle Intersect(const Rectangle& ra, const Rectangle& rb) noexcept; - static RECT Intersect(const RECT& rcta, const RECT& rctb) noexcept; + static RECT Intersect(const RECT& rcta, const RECT& rctb) noexcept; static Rectangle Union(const Rectangle& ra, const Rectangle& rb) noexcept; - static RECT Union(const RECT& rcta, const RECT& rctb) noexcept; + static RECT Union(const RECT& rcta, const RECT& rctb) noexcept; }; //------------------------------------------------------------------------------ // 2D vector struct DIRECTX_TOOLKIT_API Vector2 : public XMFLOAT2 { - Vector2() noexcept : XMFLOAT2(0.f, 0.f) {} - constexpr explicit Vector2(float ix) noexcept : XMFLOAT2(ix, ix) {} - constexpr Vector2(float ix, float iy) noexcept : XMFLOAT2(ix, iy) {} - explicit Vector2(_In_reads_(2) const float *pArray) noexcept : XMFLOAT2(pArray) {} + Vector2() noexcept + : XMFLOAT2(0.f, 0.f) + {} + constexpr explicit Vector2(float ix) noexcept + : XMFLOAT2(ix, ix) + {} + constexpr Vector2(float ix, float iy) noexcept + : XMFLOAT2(ix, iy) + {} + explicit Vector2(_In_reads_(2) const float* pArray) noexcept + : XMFLOAT2(pArray) + {} Vector2(FXMVECTOR V) noexcept { XMStoreFloat2(this, V); } - Vector2(const XMFLOAT2& V) noexcept { this->x = V.x; this->y = V.y; } - explicit Vector2(const XMVECTORF32& F) noexcept { this->x = F.f[0]; this->y = F.f[1]; } - - Vector2(const Vector2&) = default; + Vector2(const XMFLOAT2& V) noexcept + { + this->x = V.x; + this->y = V.y; + } + explicit Vector2(const XMVECTORF32& F) noexcept + { + this->x = F.f[0]; + this->y = F.f[1]; + } + + Vector2(const Vector2&) = default; Vector2& operator=(const Vector2&) = default; - Vector2(Vector2&&) = default; + Vector2(Vector2&&) = default; Vector2& operator=(Vector2&&) = default; operator XMVECTOR() const noexcept { return XMLoadFloat2(this); } // Comparison operators - bool operator == (const Vector2& V) const noexcept { return ((x == V.x) && (y == V.y)); } - bool operator != (const Vector2& V) const noexcept { return ((x != V.x) || (y != V.y)); } + bool operator==(const Vector2& V) const noexcept { return ((x == V.x) && (y == V.y)); } + bool operator!=(const Vector2& V) const noexcept { return ((x != V.x) || (y != V.y)); } // Assignment operators - Vector2& operator= (const XMVECTORF32& F) noexcept { x = F.f[0]; y = F.f[1]; return *this; } - Vector2& operator+= (const Vector2& V) noexcept { x += V.x; y += V.y; return *this; } - Vector2& operator-= (const Vector2& V) noexcept { x -= V.x; y -= V.y; return *this; } - Vector2& operator*= (const Vector2& V) noexcept { x *= V.x; y *= V.y; return *this; } - Vector2& operator*= (float S) noexcept { x *= S; y *= S; return *this; } - Vector2& operator/= (float S) noexcept { x /= S; y /= S; return *this; } + Vector2& operator=(const XMVECTORF32& F) noexcept + { + x = F.f[0]; + y = F.f[1]; + return *this; + } + Vector2& operator+=(const Vector2& V) noexcept + { + x += V.x; + y += V.y; + return *this; + } + Vector2& operator-=(const Vector2& V) noexcept + { + x -= V.x; + y -= V.y; + return *this; + } + Vector2& operator*=(const Vector2& V) noexcept + { + x *= V.x; + y *= V.y; + return *this; + } + Vector2& operator*=(float S) noexcept + { + x *= S; + y *= S; + return *this; + } + Vector2& operator/=(float S) noexcept + { + x /= S; + y /= S; + return *this; + } // Unary operators - Vector2 operator+ () const noexcept { return *this; } - Vector2 operator- () const noexcept { return Vector2(-x, -y); } + Vector2 operator+() const noexcept { return *this; } + Vector2 operator-() const noexcept { return Vector2(-x, -y); } // Vector operations bool InBounds(const Vector2& Bounds) const noexcept; @@ -176,9 +282,13 @@ namespace DirectX float Length() const noexcept { return std::sqrt((x * x) + (y * y)); } float LengthSquared() const noexcept { return (x * x) + (y * y); } - float Dot(const Vector2& V) const noexcept { return (x * V.x) + (y * V.y); } - void Cross(const Vector2& V, Vector2& result) const noexcept { result.x = result.y = (x * V.y) - (y * V.x); } - Vector2 Cross(const Vector2& V) const noexcept { float c = (x * V.y) - (y * V.x); return Vector2(c, c); } + float Dot(const Vector2& V) const noexcept { return (x * V.x) + (y * V.y); } + void Cross(const Vector2& V, Vector2& result) const noexcept { result.x = result.y = (x * V.y) - (y * V.x); } + Vector2 Cross(const Vector2& V) const noexcept + { + float c = (x * V.y) - (y * V.x); + return Vector2(c, c); + } void Normalize() noexcept; void Normalize(Vector2& result) const noexcept; @@ -190,46 +300,57 @@ namespace DirectX static float Distance(const Vector2& v1, const Vector2& v2) noexcept; static float DistanceSquared(const Vector2& v1, const Vector2& v2) noexcept; - static void Min(const Vector2& v1, const Vector2& v2, Vector2& result) noexcept; + static void Min(const Vector2& v1, const Vector2& v2, Vector2& result) noexcept; static Vector2 Min(const Vector2& v1, const Vector2& v2) noexcept; - static void Max(const Vector2& v1, const Vector2& v2, Vector2& result) noexcept; + static void Max(const Vector2& v1, const Vector2& v2, Vector2& result) noexcept; static Vector2 Max(const Vector2& v1, const Vector2& v2) noexcept; - static void Lerp(const Vector2& v1, const Vector2& v2, float t, Vector2& result) noexcept; + static void Lerp(const Vector2& v1, const Vector2& v2, float t, Vector2& result) noexcept; static Vector2 Lerp(const Vector2& v1, const Vector2& v2, float t) noexcept; - static void SmoothStep(const Vector2& v1, const Vector2& v2, float t, Vector2& result) noexcept; + static void SmoothStep(const Vector2& v1, const Vector2& v2, float t, Vector2& result) noexcept; static Vector2 SmoothStep(const Vector2& v1, const Vector2& v2, float t) noexcept; - static void Barycentric(const Vector2& v1, const Vector2& v2, const Vector2& v3, float f, float g, Vector2& result) noexcept; + static void Barycentric(const Vector2& v1, const Vector2& v2, const Vector2& v3, float f, float g, Vector2& result) noexcept; static Vector2 Barycentric(const Vector2& v1, const Vector2& v2, const Vector2& v3, float f, float g) noexcept; - static void CatmullRom(const Vector2& v1, const Vector2& v2, const Vector2& v3, const Vector2& v4, float t, Vector2& result) noexcept; + static void + CatmullRom(const Vector2& v1, const Vector2& v2, const Vector2& v3, const Vector2& v4, float t, Vector2& result) noexcept; static Vector2 CatmullRom(const Vector2& v1, const Vector2& v2, const Vector2& v3, const Vector2& v4, float t) noexcept; - static void Hermite(const Vector2& v1, const Vector2& t1, const Vector2& v2, const Vector2& t2, float t, Vector2& result) noexcept; + static void + Hermite(const Vector2& v1, const Vector2& t1, const Vector2& v2, const Vector2& t2, float t, Vector2& result) noexcept; static Vector2 Hermite(const Vector2& v1, const Vector2& t1, const Vector2& v2, const Vector2& t2, float t) noexcept; - static void Reflect(const Vector2& ivec, const Vector2& nvec, Vector2& result) noexcept; + static void Reflect(const Vector2& ivec, const Vector2& nvec, Vector2& result) noexcept; static Vector2 Reflect(const Vector2& ivec, const Vector2& nvec) noexcept; - static void Refract(const Vector2& ivec, const Vector2& nvec, float refractionIndex, Vector2& result) noexcept; + static void Refract(const Vector2& ivec, const Vector2& nvec, float refractionIndex, Vector2& result) noexcept; static Vector2 Refract(const Vector2& ivec, const Vector2& nvec, float refractionIndex) noexcept; - static void Transform(const Vector2& v, const Quaternion& quat, Vector2& result) noexcept; + static void Transform(const Vector2& v, const Quaternion& quat, Vector2& result) noexcept; static Vector2 Transform(const Vector2& v, const Quaternion& quat) noexcept; - static void Transform(const Vector2& v, const Matrix& m, Vector2& result) noexcept; + static void Transform(const Vector2& v, const Matrix& m, Vector2& result) noexcept; static Vector2 Transform(const Vector2& v, const Matrix& m) noexcept; - static void Transform(_In_reads_(count) const Vector2* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector2* resultArray) noexcept; + static void Transform(_In_reads_(count) const Vector2* varray, + size_t count, + const Matrix& m, + _Out_writes_(count) Vector2* resultArray) noexcept; static void Transform(const Vector2& v, const Matrix& m, Vector4& result) noexcept; - static void Transform(_In_reads_(count) const Vector2* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector4* resultArray) noexcept; + static void Transform(_In_reads_(count) const Vector2* varray, + size_t count, + const Matrix& m, + _Out_writes_(count) Vector4* resultArray) noexcept; - static void TransformNormal(const Vector2& v, const Matrix& m, Vector2& result) noexcept; + static void TransformNormal(const Vector2& v, const Matrix& m, Vector2& result) noexcept; static Vector2 TransformNormal(const Vector2& v, const Matrix& m) noexcept; - static void TransformNormal(_In_reads_(count) const Vector2* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector2* resultArray) noexcept; + static void TransformNormal(_In_reads_(count) const Vector2* varray, + size_t count, + const Matrix& m, + _Out_writes_(count) Vector2* resultArray) noexcept; // Constants static const Vector2 Zero; @@ -239,50 +360,128 @@ namespace DirectX }; // Binary operators - DIRECTX_TOOLKIT_API inline Vector2 operator+ (const Vector2& V1, const Vector2& V2) noexcept { return Vector2(V1.x + V2.x, V1.y + V2.y); } - DIRECTX_TOOLKIT_API inline Vector2 operator- (const Vector2& V1, const Vector2& V2) noexcept { return Vector2(V1.x - V2.x, V1.y - V2.y); } - DIRECTX_TOOLKIT_API inline Vector2 operator* (const Vector2& V1, const Vector2& V2) noexcept { return Vector2(V1.x * V2.x, V1.y * V2.y); } - DIRECTX_TOOLKIT_API inline Vector2 operator* (const Vector2& V, float S) noexcept { return Vector2(V.x * S, V.y * S); } - DIRECTX_TOOLKIT_API inline Vector2 operator* (float S, const Vector2& V) noexcept { return Vector2(S * V.x, S * V.y); } - DIRECTX_TOOLKIT_API inline Vector2 operator/ (const Vector2& V1, const Vector2& V2) noexcept { return Vector2(V1.x / V2.x, V1.y / V2.y); } - DIRECTX_TOOLKIT_API inline Vector2 operator/ (const Vector2& V, float S) noexcept { return Vector2(V.x / S, V.y / S); } - DIRECTX_TOOLKIT_API inline Vector2 operator/ (float S, const Vector2& V) noexcept { return Vector2(S / V.x, S / V.y); }; + DIRECTX_TOOLKIT_API inline Vector2 operator+(const Vector2& V1, const Vector2& V2) noexcept + { + return Vector2(V1.x + V2.x, V1.y + V2.y); + } + DIRECTX_TOOLKIT_API inline Vector2 operator-(const Vector2& V1, const Vector2& V2) noexcept + { + return Vector2(V1.x - V2.x, V1.y - V2.y); + } + DIRECTX_TOOLKIT_API inline Vector2 operator*(const Vector2& V1, const Vector2& V2) noexcept + { + return Vector2(V1.x * V2.x, V1.y * V2.y); + } + DIRECTX_TOOLKIT_API inline Vector2 operator*(const Vector2& V, float S) noexcept + { + return Vector2(V.x * S, V.y * S); + } + DIRECTX_TOOLKIT_API inline Vector2 operator*(float S, const Vector2& V) noexcept + { + return Vector2(S * V.x, S * V.y); + } + DIRECTX_TOOLKIT_API inline Vector2 operator/(const Vector2& V1, const Vector2& V2) noexcept + { + return Vector2(V1.x / V2.x, V1.y / V2.y); + } + DIRECTX_TOOLKIT_API inline Vector2 operator/(const Vector2& V, float S) noexcept + { + return Vector2(V.x / S, V.y / S); + } + DIRECTX_TOOLKIT_API inline Vector2 operator/(float S, const Vector2& V) noexcept + { + return Vector2(S / V.x, S / V.y); + }; //------------------------------------------------------------------------------ // 3D vector struct DIRECTX_TOOLKIT_API Vector3 : public XMFLOAT3 { - Vector3() noexcept : XMFLOAT3(0.f, 0.f, 0.f) {} - constexpr explicit Vector3(float ix) noexcept : XMFLOAT3(ix, ix, ix) {} - constexpr Vector3(float ix, float iy, float iz) noexcept : XMFLOAT3(ix, iy, iz) {} - explicit Vector3(_In_reads_(3) const float *pArray) noexcept : XMFLOAT3(pArray) {} + Vector3() noexcept + : XMFLOAT3(0.f, 0.f, 0.f) + {} + constexpr explicit Vector3(float ix) noexcept + : XMFLOAT3(ix, ix, ix) + {} + constexpr Vector3(float ix, float iy, float iz) noexcept + : XMFLOAT3(ix, iy, iz) + {} + explicit Vector3(_In_reads_(3) const float* pArray) noexcept + : XMFLOAT3(pArray) + {} Vector3(FXMVECTOR V) noexcept { XMStoreFloat3(this, V); } - Vector3(const XMFLOAT3& V) noexcept { this->x = V.x; this->y = V.y; this->z = V.z; } - explicit Vector3(const XMVECTORF32& F) noexcept { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; } - - Vector3(const Vector3&) = default; + Vector3(const XMFLOAT3& V) noexcept + { + this->x = V.x; + this->y = V.y; + this->z = V.z; + } + explicit Vector3(const XMVECTORF32& F) noexcept + { + this->x = F.f[0]; + this->y = F.f[1]; + this->z = F.f[2]; + } + + Vector3(const Vector3&) = default; Vector3& operator=(const Vector3&) = default; - Vector3(Vector3&&) = default; + Vector3(Vector3&&) = default; Vector3& operator=(Vector3&&) = default; operator XMVECTOR() const noexcept { return XMLoadFloat3(this); } // Comparison operators - bool operator == (const Vector3& V) const noexcept { return ((x == V.x) && (y == V.y) && (z == V.z)); } - bool operator != (const Vector3& V) const noexcept { return ((x != V.x) || (y != V.y) || (z != V.z)); } + bool operator==(const Vector3& V) const noexcept { return ((x == V.x) && (y == V.y) && (z == V.z)); } + bool operator!=(const Vector3& V) const noexcept { return ((x != V.x) || (y != V.y) || (z != V.z)); } // Assignment operators - Vector3& operator= (const XMVECTORF32& F) noexcept { x = F.f[0]; y = F.f[1]; z = F.f[2]; return *this; } - Vector3& operator+= (const Vector3& V) noexcept { x += V.x; y += V.y; z += V.z; return *this; } - Vector3& operator-= (const Vector3& V) noexcept { x -= V.x; y -= V.y; z -= V.z; return *this; } - Vector3& operator*= (const Vector3& V) noexcept { x *= V.x; y *= V.y; z *= V.z; return *this; } - Vector3& operator*= (float S) noexcept { x *= S; y *= S; z *= S; return *this; } - Vector3& operator/= (float S) noexcept { x /= S; y /= S; z /= S; return *this; } + Vector3& operator=(const XMVECTORF32& F) noexcept + { + x = F.f[0]; + y = F.f[1]; + z = F.f[2]; + return *this; + } + Vector3& operator+=(const Vector3& V) noexcept + { + x += V.x; + y += V.y; + z += V.z; + return *this; + } + Vector3& operator-=(const Vector3& V) noexcept + { + x -= V.x; + y -= V.y; + z -= V.z; + return *this; + } + Vector3& operator*=(const Vector3& V) noexcept + { + x *= V.x; + y *= V.y; + z *= V.z; + return *this; + } + Vector3& operator*=(float S) noexcept + { + x *= S; + y *= S; + z *= S; + return *this; + } + Vector3& operator/=(float S) noexcept + { + x /= S; + y /= S; + z /= S; + return *this; + } // Unary operators - Vector3 operator+ () const noexcept { return *this; } - Vector3 operator- () const noexcept { return Vector3(-x, -y, -z); } + Vector3 operator+() const noexcept { return *this; } + Vector3 operator-() const noexcept { return Vector3(-x, -y, -z); } // Vector operations bool InBounds(const Vector3& Bounds) const noexcept; @@ -291,7 +490,12 @@ namespace DirectX float LengthSquared() const noexcept { return (x * x) + (y * y) + (z * z); } float Dot(const Vector3& V) const noexcept { return (x * V.x) + (y * V.y) + (z * V.z); } - void Cross(const Vector3& V, Vector3& result) const noexcept { result.x = y * V.z - z * V.y; result.y = z * V.x - x * V.z; result.z = x * V.y - y * V.x; } + void Cross(const Vector3& V, Vector3& result) const noexcept + { + result.x = y * V.z - z * V.y; + result.y = z * V.x - x * V.z; + result.z = x * V.y - y * V.x; + } Vector3 Cross(const Vector3& V) const noexcept { return Vector3(y * V.z - z * V.y, z * V.x - x * V.z, x * V.y - y * V.x); } void Normalize() noexcept; @@ -304,46 +508,57 @@ namespace DirectX static float Distance(const Vector3& v1, const Vector3& v2) noexcept; static float DistanceSquared(const Vector3& v1, const Vector3& v2) noexcept; - static void Min(const Vector3& v1, const Vector3& v2, Vector3& result) noexcept; + static void Min(const Vector3& v1, const Vector3& v2, Vector3& result) noexcept; static Vector3 Min(const Vector3& v1, const Vector3& v2) noexcept; - static void Max(const Vector3& v1, const Vector3& v2, Vector3& result) noexcept; + static void Max(const Vector3& v1, const Vector3& v2, Vector3& result) noexcept; static Vector3 Max(const Vector3& v1, const Vector3& v2) noexcept; - static void Lerp(const Vector3& v1, const Vector3& v2, float t, Vector3& result) noexcept; + static void Lerp(const Vector3& v1, const Vector3& v2, float t, Vector3& result) noexcept; static Vector3 Lerp(const Vector3& v1, const Vector3& v2, float t) noexcept; - static void SmoothStep(const Vector3& v1, const Vector3& v2, float t, Vector3& result) noexcept; + static void SmoothStep(const Vector3& v1, const Vector3& v2, float t, Vector3& result) noexcept; static Vector3 SmoothStep(const Vector3& v1, const Vector3& v2, float t) noexcept; - static void Barycentric(const Vector3& v1, const Vector3& v2, const Vector3& v3, float f, float g, Vector3& result) noexcept; + static void Barycentric(const Vector3& v1, const Vector3& v2, const Vector3& v3, float f, float g, Vector3& result) noexcept; static Vector3 Barycentric(const Vector3& v1, const Vector3& v2, const Vector3& v3, float f, float g) noexcept; - static void CatmullRom(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float t, Vector3& result) noexcept; + static void + CatmullRom(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float t, Vector3& result) noexcept; static Vector3 CatmullRom(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float t) noexcept; - static void Hermite(const Vector3& v1, const Vector3& t1, const Vector3& v2, const Vector3& t2, float t, Vector3& result) noexcept; + static void + Hermite(const Vector3& v1, const Vector3& t1, const Vector3& v2, const Vector3& t2, float t, Vector3& result) noexcept; static Vector3 Hermite(const Vector3& v1, const Vector3& t1, const Vector3& v2, const Vector3& t2, float t) noexcept; - static void Reflect(const Vector3& ivec, const Vector3& nvec, Vector3& result) noexcept; + static void Reflect(const Vector3& ivec, const Vector3& nvec, Vector3& result) noexcept; static Vector3 Reflect(const Vector3& ivec, const Vector3& nvec) noexcept; - static void Refract(const Vector3& ivec, const Vector3& nvec, float refractionIndex, Vector3& result) noexcept; + static void Refract(const Vector3& ivec, const Vector3& nvec, float refractionIndex, Vector3& result) noexcept; static Vector3 Refract(const Vector3& ivec, const Vector3& nvec, float refractionIndex) noexcept; - static void Transform(const Vector3& v, const Quaternion& quat, Vector3& result) noexcept; + static void Transform(const Vector3& v, const Quaternion& quat, Vector3& result) noexcept; static Vector3 Transform(const Vector3& v, const Quaternion& quat) noexcept; - static void Transform(const Vector3& v, const Matrix& m, Vector3& result) noexcept; + static void Transform(const Vector3& v, const Matrix& m, Vector3& result) noexcept; static Vector3 Transform(const Vector3& v, const Matrix& m) noexcept; - static void Transform(_In_reads_(count) const Vector3* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector3* resultArray) noexcept; + static void Transform(_In_reads_(count) const Vector3* varray, + size_t count, + const Matrix& m, + _Out_writes_(count) Vector3* resultArray) noexcept; static void Transform(const Vector3& v, const Matrix& m, Vector4& result) noexcept; - static void Transform(_In_reads_(count) const Vector3* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector4* resultArray) noexcept; + static void Transform(_In_reads_(count) const Vector3* varray, + size_t count, + const Matrix& m, + _Out_writes_(count) Vector4* resultArray) noexcept; - static void TransformNormal(const Vector3& v, const Matrix& m, Vector3& result) noexcept; + static void TransformNormal(const Vector3& v, const Matrix& m, Vector3& result) noexcept; static Vector3 TransformNormal(const Vector3& v, const Matrix& m) noexcept; - static void TransformNormal(_In_reads_(count) const Vector3* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector3* resultArray) noexcept; + static void TransformNormal(_In_reads_(count) const Vector3* varray, + size_t count, + const Matrix& m, + _Out_writes_(count) Vector3* resultArray) noexcept; // Constants static const Vector3 Zero; @@ -360,50 +575,101 @@ namespace DirectX }; // Binary operators - DIRECTX_TOOLKIT_API inline Vector3 operator+ (const Vector3& V1, const Vector3& V2) noexcept { return Vector3(V1.x + V2.x, V1.y + V2.y, V1.z + V2.z); } - DIRECTX_TOOLKIT_API inline Vector3 operator- (const Vector3& V1, const Vector3& V2) noexcept { return Vector3(V1.x - V2.x, V1.y - V2.y, V1.z - V2.z); } - DIRECTX_TOOLKIT_API inline Vector3 operator* (const Vector3& V1, const Vector3& V2) noexcept { return Vector3(V1.x * V2.x, V1.y * V2.y, V1.z * V2.z); } - DIRECTX_TOOLKIT_API inline Vector3 operator* (const Vector3& V, float S) noexcept { return Vector3(V.x * S, V.y * S, V.z * S); } - DIRECTX_TOOLKIT_API inline Vector3 operator* (float S, const Vector3& V) noexcept { return Vector3(S * V.x, S * V.y, S * V.z); } - DIRECTX_TOOLKIT_API inline Vector3 operator/ (const Vector3& V1, const Vector3& V2) noexcept { return Vector3(V1.x / V2.x, V1.y / V2.y, V1.z / V2.z); } - DIRECTX_TOOLKIT_API inline Vector3 operator/ (const Vector3& V, float S) noexcept { return Vector3(V.x / S, V.y / S, V.z / S); } - DIRECTX_TOOLKIT_API inline Vector3 operator/ (float S, const Vector3& V) noexcept { return Vector3(S / V.x, S / V.y, S / V.z); } + DIRECTX_TOOLKIT_API inline Vector3 operator+(const Vector3& V1, const Vector3& V2) noexcept + { + return Vector3(V1.x + V2.x, V1.y + V2.y, V1.z + V2.z); + } + DIRECTX_TOOLKIT_API inline Vector3 operator-(const Vector3& V1, const Vector3& V2) noexcept + { + return Vector3(V1.x - V2.x, V1.y - V2.y, V1.z - V2.z); + } + DIRECTX_TOOLKIT_API inline Vector3 operator*(const Vector3& V1, const Vector3& V2) noexcept + { + return Vector3(V1.x * V2.x, V1.y * V2.y, V1.z * V2.z); + } + DIRECTX_TOOLKIT_API inline Vector3 operator*(const Vector3& V, float S) noexcept + { + return Vector3(V.x * S, V.y * S, V.z * S); + } + DIRECTX_TOOLKIT_API inline Vector3 operator*(float S, const Vector3& V) noexcept + { + return Vector3(S * V.x, S * V.y, S * V.z); + } + DIRECTX_TOOLKIT_API inline Vector3 operator/(const Vector3& V1, const Vector3& V2) noexcept + { + return Vector3(V1.x / V2.x, V1.y / V2.y, V1.z / V2.z); + } + DIRECTX_TOOLKIT_API inline Vector3 operator/(const Vector3& V, float S) noexcept + { + return Vector3(V.x / S, V.y / S, V.z / S); + } + DIRECTX_TOOLKIT_API inline Vector3 operator/(float S, const Vector3& V) noexcept + { + return Vector3(S / V.x, S / V.y, S / V.z); + } //------------------------------------------------------------------------------ // 4D vector struct DIRECTX_TOOLKIT_API Vector4 : public XMFLOAT4 { - Vector4() noexcept : XMFLOAT4(0.f, 0.f, 0.f, 0.f) {} - constexpr explicit Vector4(float ix) noexcept : XMFLOAT4(ix, ix, ix, ix) {} - constexpr Vector4(float ix, float iy, float iz, float iw) noexcept : XMFLOAT4(ix, iy, iz, iw) {} - explicit Vector4(_In_reads_(4) const float *pArray) noexcept : XMFLOAT4(pArray) {} + Vector4() noexcept + : XMFLOAT4(0.f, 0.f, 0.f, 0.f) + {} + constexpr explicit Vector4(float ix) noexcept + : XMFLOAT4(ix, ix, ix, ix) + {} + constexpr Vector4(float ix, float iy, float iz, float iw) noexcept + : XMFLOAT4(ix, iy, iz, iw) + {} + explicit Vector4(_In_reads_(4) const float* pArray) noexcept + : XMFLOAT4(pArray) + {} Vector4(FXMVECTOR V) noexcept { XMStoreFloat4(this, V); } - Vector4(const XMFLOAT4& V) noexcept { this->x = V.x; this->y = V.y; this->z = V.z; this->w = V.w; } - explicit Vector4(const XMVECTORF32& F) noexcept { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } - - Vector4(const Vector4&) = default; + Vector4(const XMFLOAT4& V) noexcept + { + this->x = V.x; + this->y = V.y; + this->z = V.z; + this->w = V.w; + } + explicit Vector4(const XMVECTORF32& F) noexcept + { + this->x = F.f[0]; + this->y = F.f[1]; + this->z = F.f[2]; + this->w = F.f[3]; + } + + Vector4(const Vector4&) = default; Vector4& operator=(const Vector4&) = default; - Vector4(Vector4&&) = default; + Vector4(Vector4&&) = default; Vector4& operator=(Vector4&&) = default; operator XMVECTOR() const noexcept { return XMLoadFloat4(this); } // Comparison operators - bool operator == (const Vector4& V) const noexcept; - bool operator != (const Vector4& V) const noexcept; + bool operator==(const Vector4& V) const noexcept; + bool operator!=(const Vector4& V) const noexcept; // Assignment operators - Vector4& operator= (const XMVECTORF32& F) noexcept { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } - Vector4& operator+= (const Vector4& V) noexcept; - Vector4& operator-= (const Vector4& V) noexcept; - Vector4& operator*= (const Vector4& V) noexcept; - Vector4& operator*= (float S) noexcept; - Vector4& operator/= (float S) noexcept; + Vector4& operator=(const XMVECTORF32& F) noexcept + { + x = F.f[0]; + y = F.f[1]; + z = F.f[2]; + w = F.f[3]; + return *this; + } + Vector4& operator+=(const Vector4& V) noexcept; + Vector4& operator-=(const Vector4& V) noexcept; + Vector4& operator*=(const Vector4& V) noexcept; + Vector4& operator*=(float S) noexcept; + Vector4& operator/=(float S) noexcept; // Unary operators - Vector4 operator+ () const noexcept { return *this; } - Vector4 operator- () const noexcept { return Vector4(-x, -y, -z, -w); } + Vector4 operator+() const noexcept { return *this; } + Vector4 operator-() const noexcept { return Vector4(-x, -y, -z, -w); } // Vector operations bool InBounds(const Vector4& Bounds) const noexcept; @@ -411,8 +677,8 @@ namespace DirectX float Length() const noexcept; float LengthSquared() const noexcept; - float Dot(const Vector4& V) const noexcept; - void Cross(const Vector4& v1, const Vector4& v2, Vector4& result) const noexcept; + float Dot(const Vector4& V) const noexcept; + void Cross(const Vector4& v1, const Vector4& v2, Vector4& result) const noexcept; Vector4 Cross(const Vector4& v1, const Vector4& v2) const noexcept; void Normalize() noexcept; @@ -425,45 +691,50 @@ namespace DirectX static float Distance(const Vector4& v1, const Vector4& v2) noexcept; static float DistanceSquared(const Vector4& v1, const Vector4& v2) noexcept; - static void Min(const Vector4& v1, const Vector4& v2, Vector4& result) noexcept; + static void Min(const Vector4& v1, const Vector4& v2, Vector4& result) noexcept; static Vector4 Min(const Vector4& v1, const Vector4& v2) noexcept; - static void Max(const Vector4& v1, const Vector4& v2, Vector4& result) noexcept; + static void Max(const Vector4& v1, const Vector4& v2, Vector4& result) noexcept; static Vector4 Max(const Vector4& v1, const Vector4& v2) noexcept; - static void Lerp(const Vector4& v1, const Vector4& v2, float t, Vector4& result) noexcept; + static void Lerp(const Vector4& v1, const Vector4& v2, float t, Vector4& result) noexcept; static Vector4 Lerp(const Vector4& v1, const Vector4& v2, float t) noexcept; - static void SmoothStep(const Vector4& v1, const Vector4& v2, float t, Vector4& result) noexcept; + static void SmoothStep(const Vector4& v1, const Vector4& v2, float t, Vector4& result) noexcept; static Vector4 SmoothStep(const Vector4& v1, const Vector4& v2, float t) noexcept; - static void Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g, Vector4& result) noexcept; + static void Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g, Vector4& result) noexcept; static Vector4 Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g) noexcept; - static void CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t, Vector4& result) noexcept; + static void + CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t, Vector4& result) noexcept; static Vector4 CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t) noexcept; - static void Hermite(const Vector4& v1, const Vector4& t1, const Vector4& v2, const Vector4& t2, float t, Vector4& result) noexcept; + static void + Hermite(const Vector4& v1, const Vector4& t1, const Vector4& v2, const Vector4& t2, float t, Vector4& result) noexcept; static Vector4 Hermite(const Vector4& v1, const Vector4& t1, const Vector4& v2, const Vector4& t2, float t) noexcept; - static void Reflect(const Vector4& ivec, const Vector4& nvec, Vector4& result) noexcept; + static void Reflect(const Vector4& ivec, const Vector4& nvec, Vector4& result) noexcept; static Vector4 Reflect(const Vector4& ivec, const Vector4& nvec) noexcept; - static void Refract(const Vector4& ivec, const Vector4& nvec, float refractionIndex, Vector4& result) noexcept; + static void Refract(const Vector4& ivec, const Vector4& nvec, float refractionIndex, Vector4& result) noexcept; static Vector4 Refract(const Vector4& ivec, const Vector4& nvec, float refractionIndex) noexcept; - static void Transform(const Vector2& v, const Quaternion& quat, Vector4& result) noexcept; + static void Transform(const Vector2& v, const Quaternion& quat, Vector4& result) noexcept; static Vector4 Transform(const Vector2& v, const Quaternion& quat) noexcept; - static void Transform(const Vector3& v, const Quaternion& quat, Vector4& result) noexcept; + static void Transform(const Vector3& v, const Quaternion& quat, Vector4& result) noexcept; static Vector4 Transform(const Vector3& v, const Quaternion& quat) noexcept; - static void Transform(const Vector4& v, const Quaternion& quat, Vector4& result) noexcept; + static void Transform(const Vector4& v, const Quaternion& quat, Vector4& result) noexcept; static Vector4 Transform(const Vector4& v, const Quaternion& quat) noexcept; - static void Transform(const Vector4& v, const Matrix& m, Vector4& result) noexcept; + static void Transform(const Vector4& v, const Matrix& m, Vector4& result) noexcept; static Vector4 Transform(const Vector4& v, const Matrix& m) noexcept; - static void Transform(_In_reads_(count) const Vector4* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector4* resultArray) noexcept; + static void Transform(_In_reads_(count) const Vector4* varray, + size_t count, + const Matrix& m, + _Out_writes_(count) Vector4* resultArray) noexcept; // Constants static const Vector4 Zero; @@ -475,111 +746,148 @@ namespace DirectX }; // Binary operators - DIRECTX_TOOLKIT_API Vector4 operator+ (const Vector4& V1, const Vector4& V2) noexcept; - DIRECTX_TOOLKIT_API Vector4 operator- (const Vector4& V1, const Vector4& V2) noexcept; - DIRECTX_TOOLKIT_API Vector4 operator* (const Vector4& V1, const Vector4& V2) noexcept; - DIRECTX_TOOLKIT_API Vector4 operator* (const Vector4& V, float S) noexcept; - DIRECTX_TOOLKIT_API Vector4 operator* (float S, const Vector4& V) noexcept; - DIRECTX_TOOLKIT_API Vector4 operator/ (const Vector4& V1, const Vector4& V2) noexcept; - DIRECTX_TOOLKIT_API Vector4 operator/ (const Vector4& V, float S) noexcept; - DIRECTX_TOOLKIT_API Vector4 operator/ (float S, const Vector4& V) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator+(const Vector4& V1, const Vector4& V2) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator-(const Vector4& V1, const Vector4& V2) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator*(const Vector4& V1, const Vector4& V2) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator*(const Vector4& V, float S) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator*(float S, const Vector4& V) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator/(const Vector4& V1, const Vector4& V2) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator/(const Vector4& V, float S) noexcept; + DIRECTX_TOOLKIT_API Vector4 operator/(float S, const Vector4& V) noexcept; //------------------------------------------------------------------------------ // 4x4 Matrix (assumes right-handed cooordinates) struct DIRECTX_TOOLKIT_API Matrix : public XMFLOAT4X4 { Matrix() noexcept - : XMFLOAT4X4(1.f, 0, 0, 0, - 0, 1.f, 0, 0, - 0, 0, 1.f, 0, - 0, 0, 0, 1.f) + : XMFLOAT4X4(1.f, 0, 0, 0, 0, 1.f, 0, 0, 0, 0, 1.f, 0, 0, 0, 0, 1.f) {} - constexpr Matrix(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23, - float m30, float m31, float m32, float m33) noexcept - : XMFLOAT4X4(m00, m01, m02, m03, - m10, m11, m12, m13, - m20, m21, m22, m23, - m30, m31, m32, m33) + constexpr Matrix(float m00, + float m01, + float m02, + float m03, + float m10, + float m11, + float m12, + float m13, + float m20, + float m21, + float m22, + float m23, + float m30, + float m31, + float m32, + float m33) noexcept + : XMFLOAT4X4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {} explicit Matrix(const Vector3& r0, const Vector3& r1, const Vector3& r2) noexcept - : XMFLOAT4X4(r0.x, r0.y, r0.z, 0, - r1.x, r1.y, r1.z, 0, - r2.x, r2.y, r2.z, 0, - 0, 0, 0, 1.f) + : XMFLOAT4X4(r0.x, r0.y, r0.z, 0, r1.x, r1.y, r1.z, 0, r2.x, r2.y, r2.z, 0, 0, 0, 0, 1.f) {} explicit Matrix(const Vector4& r0, const Vector4& r1, const Vector4& r2, const Vector4& r3) noexcept - : XMFLOAT4X4(r0.x, r0.y, r0.z, r0.w, - r1.x, r1.y, r1.z, r1.w, - r2.x, r2.y, r2.z, r2.w, - r3.x, r3.y, r3.z, r3.w) + : XMFLOAT4X4(r0.x, r0.y, r0.z, r0.w, r1.x, r1.y, r1.z, r1.w, r2.x, r2.y, r2.z, r2.w, r3.x, r3.y, r3.z, r3.w) {} Matrix(const XMFLOAT4X4& M) noexcept { memcpy(this, &M, sizeof(XMFLOAT4X4)); } Matrix(const XMFLOAT3X3& M) noexcept; Matrix(const XMFLOAT4X3& M) noexcept; - explicit Matrix(_In_reads_(16) const float *pArray) noexcept : XMFLOAT4X4(pArray) {} + explicit Matrix(_In_reads_(16) const float* pArray) noexcept + : XMFLOAT4X4(pArray) + {} Matrix(CXMMATRIX M) noexcept { XMStoreFloat4x4(this, M); } - Matrix(const Matrix&) = default; + Matrix(const Matrix&) = default; Matrix& operator=(const Matrix&) = default; - Matrix(Matrix&&) = default; + Matrix(Matrix&&) = default; Matrix& operator=(Matrix&&) = default; operator XMMATRIX() const noexcept { return XMLoadFloat4x4(this); } // Comparison operators - bool operator == (const Matrix& M) const noexcept; - bool operator != (const Matrix& M) const noexcept; + bool operator==(const Matrix& M) const noexcept; + bool operator!=(const Matrix& M) const noexcept; // Assignment operators - Matrix& operator= (const XMFLOAT3X3& M) noexcept; - Matrix& operator= (const XMFLOAT4X3& M) noexcept; - Matrix& operator+= (const Matrix& M) noexcept; - Matrix& operator-= (const Matrix& M) noexcept; - Matrix& operator*= (const Matrix& M) noexcept; - Matrix& operator*= (float S) noexcept; - Matrix& operator/= (float S) noexcept; - - Matrix& operator/= (const Matrix& M) noexcept; - // Element-wise divide + Matrix& operator=(const XMFLOAT3X3& M) noexcept; + Matrix& operator=(const XMFLOAT4X3& M) noexcept; + Matrix& operator+=(const Matrix& M) noexcept; + Matrix& operator-=(const Matrix& M) noexcept; + Matrix& operator*=(const Matrix& M) noexcept; + Matrix& operator*=(float S) noexcept; + Matrix& operator/=(float S) noexcept; + + Matrix& operator/=(const Matrix& M) noexcept; + // Element-wise divide // Unary operators - Matrix operator+ () const noexcept { return *this; } - Matrix operator- () const noexcept; + Matrix operator+() const noexcept { return *this; } + Matrix operator-() const noexcept; // Properties Vector3 Up() const noexcept { return Vector3(_21, _22, _23); } - void Up(const Vector3& v) noexcept { _21 = v.x; _22 = v.y; _23 = v.z; } + void Up(const Vector3& v) noexcept + { + _21 = v.x; + _22 = v.y; + _23 = v.z; + } Vector3 Down() const noexcept { return Vector3(-_21, -_22, -_23); } - void Down(const Vector3& v) noexcept { _21 = -v.x; _22 = -v.y; _23 = -v.z; } + void Down(const Vector3& v) noexcept + { + _21 = -v.x; + _22 = -v.y; + _23 = -v.z; + } Vector3 Right() const noexcept { return Vector3(_11, _12, _13); } - void Right(const Vector3& v) noexcept { _11 = v.x; _12 = v.y; _13 = v.z; } + void Right(const Vector3& v) noexcept + { + _11 = v.x; + _12 = v.y; + _13 = v.z; + } Vector3 Left() const noexcept { return Vector3(-_11, -_12, -_13); } - void Left(const Vector3& v) noexcept { _11 = -v.x; _12 = -v.y; _13 = -v.z; } + void Left(const Vector3& v) noexcept + { + _11 = -v.x; + _12 = -v.y; + _13 = -v.z; + } Vector3 Forward() const noexcept { return Vector3(-_31, -_32, -_33); } - void Forward(const Vector3& v) noexcept { _31 = -v.x; _32 = -v.y; _33 = -v.z; } + void Forward(const Vector3& v) noexcept + { + _31 = -v.x; + _32 = -v.y; + _33 = -v.z; + } Vector3 Backward() const noexcept { return Vector3(_31, _32, _33); } - void Backward(const Vector3& v) noexcept { _31 = v.x; _32 = v.y; _33 = v.z; } + void Backward(const Vector3& v) noexcept + { + _31 = v.x; + _32 = v.y; + _33 = v.z; + } Vector3 Translation() const noexcept { return Vector3(_41, _42, _43); } - void Translation(const Vector3& v) noexcept { _41 = v.x; _42 = v.y; _43 = v.z; } + void Translation(const Vector3& v) noexcept + { + _41 = v.x; + _42 = v.y; + _43 = v.z; + } // Matrix operations bool Decompose(Vector3& scale, Quaternion& rotation, Vector3& translation) noexcept; Matrix Transpose() const noexcept; - void Transpose(Matrix& result) const noexcept; + void Transpose(Matrix& result) const noexcept; Matrix Invert() const noexcept; - void Invert(Matrix& result) const noexcept; + void Invert(Matrix& result) const noexcept; float Determinant() const noexcept; @@ -587,12 +895,16 @@ namespace DirectX Vector3 ToEuler() const noexcept; // Static functions - static Matrix CreateBillboard( - const Vector3& object, const Vector3& cameraPosition, const Vector3& cameraUp, _In_opt_ const Vector3* cameraForward = nullptr) noexcept; + static Matrix CreateBillboard(const Vector3& object, + const Vector3& cameraPosition, + const Vector3& cameraUp, + _In_opt_ const Vector3* cameraForward = nullptr) noexcept; - static Matrix CreateConstrainedBillboard( - const Vector3& object, const Vector3& cameraPosition, const Vector3& rotateAxis, - _In_opt_ const Vector3* cameraForward = nullptr, _In_opt_ const Vector3* objectForward = nullptr) noexcept; + static Matrix CreateConstrainedBillboard(const Vector3& object, + const Vector3& cameraPosition, + const Vector3& rotateAxis, + _In_opt_ const Vector3* cameraForward = nullptr, + _In_opt_ const Vector3* objectForward = nullptr) noexcept; static Matrix CreateTranslation(const Vector3& position) noexcept; static Matrix CreateTranslation(float x, float y, float z) noexcept; @@ -609,9 +921,11 @@ namespace DirectX static Matrix CreatePerspectiveFieldOfView(float fov, float aspectRatio, float nearPlane, float farPlane) noexcept; static Matrix CreatePerspective(float width, float height, float nearPlane, float farPlane) noexcept; - static Matrix CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlane, float farPlane) noexcept; + static Matrix + CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlane, float farPlane) noexcept; static Matrix CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane) noexcept; - static Matrix CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane) noexcept; + static Matrix + CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane) noexcept; static Matrix CreateLookAt(const Vector3& position, const Vector3& target, const Vector3& up) noexcept; static Matrix CreateWorld(const Vector3& position, const Vector3& forward, const Vector3& up) noexcept; @@ -628,10 +942,10 @@ namespace DirectX static Matrix CreateReflection(const Plane& plane) noexcept; - static void Lerp(const Matrix& M1, const Matrix& M2, float t, Matrix& result) noexcept; + static void Lerp(const Matrix& M1, const Matrix& M2, float t, Matrix& result) noexcept; static Matrix Lerp(const Matrix& M1, const Matrix& M2, float t) noexcept; - static void Transform(const Matrix& M, const Quaternion& rotation, Matrix& result) noexcept; + static void Transform(const Matrix& M, const Quaternion& rotation, Matrix& result) noexcept; static Matrix Transform(const Matrix& M, const Quaternion& rotation) noexcept; // Constants @@ -639,52 +953,86 @@ namespace DirectX }; // Binary operators - DIRECTX_TOOLKIT_API Matrix operator+ (const Matrix& M1, const Matrix& M2) noexcept; - DIRECTX_TOOLKIT_API Matrix operator- (const Matrix& M1, const Matrix& M2) noexcept; - DIRECTX_TOOLKIT_API Matrix operator* (const Matrix& M1, const Matrix& M2) noexcept; - DIRECTX_TOOLKIT_API Matrix operator* (const Matrix& M, float S) noexcept; - DIRECTX_TOOLKIT_API Matrix operator* (float S, const Matrix& M) noexcept; - DIRECTX_TOOLKIT_API Matrix operator/ (const Matrix& M, float S) noexcept; - DIRECTX_TOOLKIT_API Matrix operator/ (const Matrix& M1, const Matrix& M2) noexcept; - // Element-wise divide - DIRECTX_TOOLKIT_API Matrix operator/ (float S, const Matrix& M) noexcept; + DIRECTX_TOOLKIT_API Matrix operator+(const Matrix& M1, const Matrix& M2) noexcept; + DIRECTX_TOOLKIT_API Matrix operator-(const Matrix& M1, const Matrix& M2) noexcept; + DIRECTX_TOOLKIT_API Matrix operator*(const Matrix& M1, const Matrix& M2) noexcept; + DIRECTX_TOOLKIT_API Matrix operator*(const Matrix& M, float S) noexcept; + DIRECTX_TOOLKIT_API Matrix operator*(float S, const Matrix& M) noexcept; + DIRECTX_TOOLKIT_API Matrix operator/(const Matrix& M, float S) noexcept; + DIRECTX_TOOLKIT_API Matrix operator/(const Matrix& M1, const Matrix& M2) noexcept; + // Element-wise divide + DIRECTX_TOOLKIT_API Matrix operator/(float S, const Matrix& M) noexcept; //----------------------------------------------------------------------------- // Plane struct DIRECTX_TOOLKIT_API Plane : public XMFLOAT4 { - Plane() noexcept : XMFLOAT4(0.f, 1.f, 0.f, 0.f) {} - constexpr Plane(float ix, float iy, float iz, float iw) noexcept : XMFLOAT4(ix, iy, iz, iw) {} - Plane(const Vector3& normal, float d) noexcept : XMFLOAT4(normal.x, normal.y, normal.z, d) {} + Plane() noexcept + : XMFLOAT4(0.f, 1.f, 0.f, 0.f) + {} + constexpr Plane(float ix, float iy, float iz, float iw) noexcept + : XMFLOAT4(ix, iy, iz, iw) + {} + Plane(const Vector3& normal, float d) noexcept + : XMFLOAT4(normal.x, normal.y, normal.z, d) + {} Plane(const Vector3& point1, const Vector3& point2, const Vector3& point3) noexcept; Plane(const Vector3& point, const Vector3& normal) noexcept; - explicit Plane(const Vector4& v) noexcept : XMFLOAT4(v.x, v.y, v.z, v.w) {} - explicit Plane(_In_reads_(4) const float *pArray) noexcept : XMFLOAT4(pArray) {} + explicit Plane(const Vector4& v) noexcept + : XMFLOAT4(v.x, v.y, v.z, v.w) + {} + explicit Plane(_In_reads_(4) const float* pArray) noexcept + : XMFLOAT4(pArray) + {} Plane(FXMVECTOR V) noexcept { XMStoreFloat4(this, V); } - Plane(const XMFLOAT4& p) noexcept { this->x = p.x; this->y = p.y; this->z = p.z; this->w = p.w; } - explicit Plane(const XMVECTORF32& F) noexcept { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } - - Plane(const Plane&) = default; + Plane(const XMFLOAT4& p) noexcept + { + this->x = p.x; + this->y = p.y; + this->z = p.z; + this->w = p.w; + } + explicit Plane(const XMVECTORF32& F) noexcept + { + this->x = F.f[0]; + this->y = F.f[1]; + this->z = F.f[2]; + this->w = F.f[3]; + } + + Plane(const Plane&) = default; Plane& operator=(const Plane&) = default; - Plane(Plane&&) = default; + Plane(Plane&&) = default; Plane& operator=(Plane&&) = default; operator XMVECTOR() const noexcept { return XMLoadFloat4(this); } // Comparison operators - bool operator == (const Plane& p) const noexcept; - bool operator != (const Plane& p) const noexcept; + bool operator==(const Plane& p) const noexcept; + bool operator!=(const Plane& p) const noexcept; // Assignment operators - Plane& operator= (const XMVECTORF32& F) noexcept { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } + Plane& operator=(const XMVECTORF32& F) noexcept + { + x = F.f[0]; + y = F.f[1]; + z = F.f[2]; + w = F.f[3]; + return *this; + } // Properties Vector3 Normal() const noexcept { return Vector3(x, y, z); } - void Normal(const Vector3& normal) noexcept { x = normal.x; y = normal.y; z = normal.z; } + void Normal(const Vector3& normal) noexcept + { + x = normal.x; + y = normal.y; + z = normal.z; + } float D() const noexcept { return w; } - void D(float d) noexcept { w = d; } + void D(float d) noexcept { w = d; } // Plane operations void Normalize() noexcept; @@ -695,50 +1043,79 @@ namespace DirectX float DotNormal(const Vector3& normal) const noexcept; // Static functions - static void Transform(const Plane& plane, const Matrix& M, Plane& result) noexcept; + static void Transform(const Plane& plane, const Matrix& M, Plane& result) noexcept; static Plane Transform(const Plane& plane, const Matrix& M) noexcept; - static void Transform(const Plane& plane, const Quaternion& rotation, Plane& result) noexcept; + static void Transform(const Plane& plane, const Quaternion& rotation, Plane& result) noexcept; static Plane Transform(const Plane& plane, const Quaternion& rotation) noexcept; - // Input quaternion must be the inverse transpose of the transformation + // Input quaternion must be the inverse transpose of the transformation }; //------------------------------------------------------------------------------ // Quaternion struct DIRECTX_TOOLKIT_API Quaternion : public XMFLOAT4 { - Quaternion() noexcept : XMFLOAT4(0, 0, 0, 1.f) {} - constexpr Quaternion(float ix, float iy, float iz, float iw) noexcept : XMFLOAT4(ix, iy, iz, iw) {} - Quaternion(const Vector3& v, float scalar) noexcept : XMFLOAT4(v.x, v.y, v.z, scalar) {} - explicit Quaternion(const Vector4& v) noexcept : XMFLOAT4(v.x, v.y, v.z, v.w) {} - explicit Quaternion(_In_reads_(4) const float *pArray) noexcept : XMFLOAT4(pArray) {} + Quaternion() noexcept + : XMFLOAT4(0, 0, 0, 1.f) + {} + constexpr Quaternion(float ix, float iy, float iz, float iw) noexcept + : XMFLOAT4(ix, iy, iz, iw) + {} + Quaternion(const Vector3& v, float scalar) noexcept + : XMFLOAT4(v.x, v.y, v.z, scalar) + {} + explicit Quaternion(const Vector4& v) noexcept + : XMFLOAT4(v.x, v.y, v.z, v.w) + {} + explicit Quaternion(_In_reads_(4) const float* pArray) noexcept + : XMFLOAT4(pArray) + {} Quaternion(FXMVECTOR V) noexcept { XMStoreFloat4(this, V); } - Quaternion(const XMFLOAT4& q) noexcept { this->x = q.x; this->y = q.y; this->z = q.z; this->w = q.w; } - explicit Quaternion(const XMVECTORF32& F) noexcept { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } - - Quaternion(const Quaternion&) = default; + Quaternion(const XMFLOAT4& q) noexcept + { + this->x = q.x; + this->y = q.y; + this->z = q.z; + this->w = q.w; + } + explicit Quaternion(const XMVECTORF32& F) noexcept + { + this->x = F.f[0]; + this->y = F.f[1]; + this->z = F.f[2]; + this->w = F.f[3]; + } + + Quaternion(const Quaternion&) = default; Quaternion& operator=(const Quaternion&) = default; - Quaternion(Quaternion&&) = default; + Quaternion(Quaternion&&) = default; Quaternion& operator=(Quaternion&&) = default; operator XMVECTOR() const noexcept { return XMLoadFloat4(this); } // Comparison operators - bool operator == (const Quaternion& q) const noexcept; - bool operator != (const Quaternion& q) const noexcept; + bool operator==(const Quaternion& q) const noexcept; + bool operator!=(const Quaternion& q) const noexcept; // Assignment operators - Quaternion& operator= (const XMVECTORF32& F) noexcept { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } - Quaternion& operator+= (const Quaternion& q) noexcept; - Quaternion& operator-= (const Quaternion& q) noexcept; - Quaternion& operator*= (const Quaternion& q) noexcept; - Quaternion& operator*= (float S) noexcept; - Quaternion& operator/= (const Quaternion& q) noexcept; + Quaternion& operator=(const XMVECTORF32& F) noexcept + { + x = F.f[0]; + y = F.f[1]; + z = F.f[2]; + w = F.f[3]; + return *this; + } + Quaternion& operator+=(const Quaternion& q) noexcept; + Quaternion& operator-=(const Quaternion& q) noexcept; + Quaternion& operator*=(const Quaternion& q) noexcept; + Quaternion& operator*=(float S) noexcept; + Quaternion& operator/=(const Quaternion& q) noexcept; // Unary operators - Quaternion operator+ () const noexcept { return *this; } - Quaternion operator- () const noexcept { return Quaternion(-x, -y, -z, -w); } + Quaternion operator+() const noexcept { return *this; } + Quaternion operator-() const noexcept { return Quaternion(-x, -y, -z, -w); } // Quaternion operations float Length() const noexcept; @@ -754,7 +1131,7 @@ namespace DirectX float Dot(const Quaternion& Q) const noexcept; - void RotateTowards(const Quaternion& target, float maxAngle) noexcept; + void RotateTowards(const Quaternion& target, float maxAngle) noexcept; void __cdecl RotateTowards(const Quaternion& target, float maxAngle, Quaternion& result) const noexcept; // Computes rotation about y-axis (y), then x-axis (x), then z-axis (z) @@ -771,20 +1148,20 @@ namespace DirectX static Quaternion CreateFromRotationMatrix(const Matrix& M) noexcept; - static void Lerp(const Quaternion& q1, const Quaternion& q2, float t, Quaternion& result) noexcept; + static void Lerp(const Quaternion& q1, const Quaternion& q2, float t, Quaternion& result) noexcept; static Quaternion Lerp(const Quaternion& q1, const Quaternion& q2, float t) noexcept; - static void Slerp(const Quaternion& q1, const Quaternion& q2, float t, Quaternion& result) noexcept; + static void Slerp(const Quaternion& q1, const Quaternion& q2, float t, Quaternion& result) noexcept; static Quaternion Slerp(const Quaternion& q1, const Quaternion& q2, float t) noexcept; - static void Concatenate(const Quaternion& q1, const Quaternion& q2, Quaternion& result) noexcept; + static void Concatenate(const Quaternion& q1, const Quaternion& q2, Quaternion& result) noexcept; static Quaternion Concatenate(const Quaternion& q1, const Quaternion& q2) noexcept; static void __cdecl FromToRotation(const Vector3& fromDir, const Vector3& toDir, Quaternion& result) noexcept; - static Quaternion FromToRotation(const Vector3& fromDir, const Vector3& toDir) noexcept; + static Quaternion FromToRotation(const Vector3& fromDir, const Vector3& toDir) noexcept; static void __cdecl LookRotation(const Vector3& forward, const Vector3& up, Quaternion& result) noexcept; - static Quaternion LookRotation(const Vector3& forward, const Vector3& up) noexcept; + static Quaternion LookRotation(const Vector3& forward, const Vector3& up) noexcept; static float Angle(const Quaternion& q1, const Quaternion& q2) noexcept; @@ -793,26 +1170,50 @@ namespace DirectX }; // Binary operators - DIRECTX_TOOLKIT_API Quaternion operator+ (const Quaternion& Q1, const Quaternion& Q2) noexcept; - DIRECTX_TOOLKIT_API Quaternion operator- (const Quaternion& Q1, const Quaternion& Q2) noexcept; - DIRECTX_TOOLKIT_API Quaternion operator* (const Quaternion& Q1, const Quaternion& Q2) noexcept; - DIRECTX_TOOLKIT_API Quaternion operator* (const Quaternion& Q, float S) noexcept; - DIRECTX_TOOLKIT_API Quaternion operator* (float S, const Quaternion& Q) noexcept; - DIRECTX_TOOLKIT_API Quaternion operator/ (const Quaternion& Q1, const Quaternion& Q2) noexcept; + DIRECTX_TOOLKIT_API Quaternion operator+(const Quaternion& Q1, const Quaternion& Q2) noexcept; + DIRECTX_TOOLKIT_API Quaternion operator-(const Quaternion& Q1, const Quaternion& Q2) noexcept; + DIRECTX_TOOLKIT_API Quaternion operator*(const Quaternion& Q1, const Quaternion& Q2) noexcept; + DIRECTX_TOOLKIT_API Quaternion operator*(const Quaternion& Q, float S) noexcept; + DIRECTX_TOOLKIT_API Quaternion operator*(float S, const Quaternion& Q) noexcept; + DIRECTX_TOOLKIT_API Quaternion operator/(const Quaternion& Q1, const Quaternion& Q2) noexcept; //------------------------------------------------------------------------------ // Color struct DIRECTX_TOOLKIT_API Color : public XMFLOAT4 { - Color() noexcept : XMFLOAT4(0, 0, 0, 1.f) {} - constexpr Color(float _r, float _g, float _b) noexcept : XMFLOAT4(_r, _g, _b, 1.f) {} - constexpr Color(float _r, float _g, float _b, float _a) noexcept : XMFLOAT4(_r, _g, _b, _a) {} - explicit Color(const Vector3& clr) noexcept : XMFLOAT4(clr.x, clr.y, clr.z, 1.f) {} - explicit Color(const Vector4& clr) noexcept : XMFLOAT4(clr.x, clr.y, clr.z, clr.w) {} - explicit Color(_In_reads_(4) const float *pArray) noexcept : XMFLOAT4(pArray) {} + Color() noexcept + : XMFLOAT4(0, 0, 0, 1.f) + {} + constexpr Color(float _r, float _g, float _b) noexcept + : XMFLOAT4(_r, _g, _b, 1.f) + {} + constexpr Color(float _r, float _g, float _b, float _a) noexcept + : XMFLOAT4(_r, _g, _b, _a) + {} + explicit Color(const Vector3& clr) noexcept + : XMFLOAT4(clr.x, clr.y, clr.z, 1.f) + {} + explicit Color(const Vector4& clr) noexcept + : XMFLOAT4(clr.x, clr.y, clr.z, clr.w) + {} + explicit Color(_In_reads_(4) const float* pArray) noexcept + : XMFLOAT4(pArray) + {} Color(FXMVECTOR V) noexcept { XMStoreFloat4(this, V); } - Color(const XMFLOAT4& c) noexcept { this->x = c.x; this->y = c.y; this->z = c.z; this->w = c.w; } - explicit Color(const XMVECTORF32& F) noexcept { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } + Color(const XMFLOAT4& c) noexcept + { + this->x = c.x; + this->y = c.y; + this->z = c.z; + this->w = c.w; + } + explicit Color(const XMVECTORF32& F) noexcept + { + this->x = F.f[0]; + this->y = F.f[1]; + this->z = F.f[2]; + this->w = F.f[3]; + } // BGRA Direct3D 9 D3DCOLOR packed color explicit Color(const DirectX::PackedVector::XMCOLOR& Packed) noexcept; @@ -820,48 +1221,55 @@ namespace DirectX // RGBA XNA Game Studio packed color explicit Color(const DirectX::PackedVector::XMUBYTEN4& Packed) noexcept; - Color(const Color&) = default; + Color(const Color&) = default; Color& operator=(const Color&) = default; - Color(Color&&) = default; + Color(Color&&) = default; Color& operator=(Color&&) = default; operator XMVECTOR() const noexcept { return XMLoadFloat4(this); } operator const float*() const noexcept { return reinterpret_cast(this); } // Comparison operators - bool operator == (const Color& c) const noexcept; - bool operator != (const Color& c) const noexcept; + bool operator==(const Color& c) const noexcept; + bool operator!=(const Color& c) const noexcept; // Assignment operators - Color& operator= (const XMVECTORF32& F) noexcept { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } - Color& operator= (const DirectX::PackedVector::XMCOLOR& Packed) noexcept; - Color& operator= (const DirectX::PackedVector::XMUBYTEN4& Packed) noexcept; - Color& operator+= (const Color& c) noexcept; - Color& operator-= (const Color& c) noexcept; - Color& operator*= (const Color& c) noexcept; - Color& operator*= (float S) noexcept; - Color& operator/= (const Color& c) noexcept; + Color& operator=(const XMVECTORF32& F) noexcept + { + x = F.f[0]; + y = F.f[1]; + z = F.f[2]; + w = F.f[3]; + return *this; + } + Color& operator=(const DirectX::PackedVector::XMCOLOR& Packed) noexcept; + Color& operator=(const DirectX::PackedVector::XMUBYTEN4& Packed) noexcept; + Color& operator+=(const Color& c) noexcept; + Color& operator-=(const Color& c) noexcept; + Color& operator*=(const Color& c) noexcept; + Color& operator*=(float S) noexcept; + Color& operator/=(const Color& c) noexcept; // Unary operators - Color operator+ () const noexcept { return *this; } - Color operator- () const noexcept { return Color(-x, -y, -z, -w); } + Color operator+() const noexcept { return *this; } + Color operator-() const noexcept { return Color(-x, -y, -z, -w); } // Properties float R() const noexcept { return x; } - void R(float r) noexcept { x = r; } + void R(float r) noexcept { x = r; } float G() const noexcept { return y; } - void G(float g) noexcept { y = g; } + void G(float g) noexcept { y = g; } float B() const noexcept { return z; } - void B(float b) noexcept { z = b; } + void B(float b) noexcept { z = b; } float A() const noexcept { return w; } - void A(float a) noexcept { w = a; } + void A(float a) noexcept { w = a; } // Color operations - DirectX::PackedVector::XMCOLOR BGRA() const noexcept; + DirectX::PackedVector::XMCOLOR BGRA() const noexcept; DirectX::PackedVector::XMUBYTEN4 RGBA() const noexcept; Vector3 ToVector3() const noexcept { return Vector3(x, y, z); } @@ -883,20 +1291,20 @@ namespace DirectX void AdjustContrast(float contrast, Color& result) const noexcept; // Static functions - static void Modulate(const Color& c1, const Color& c2, Color& result) noexcept; + static void Modulate(const Color& c1, const Color& c2, Color& result) noexcept; static Color Modulate(const Color& c1, const Color& c2) noexcept; - static void Lerp(const Color& c1, const Color& c2, float t, Color& result) noexcept; + static void Lerp(const Color& c1, const Color& c2, float t, Color& result) noexcept; static Color Lerp(const Color& c1, const Color& c2, float t) noexcept; }; // Binary operators - DIRECTX_TOOLKIT_API Color operator+ (const Color& C1, const Color& C2) noexcept; - DIRECTX_TOOLKIT_API Color operator- (const Color& C1, const Color& C2) noexcept; - DIRECTX_TOOLKIT_API Color operator* (const Color& C1, const Color& C2) noexcept; - DIRECTX_TOOLKIT_API Color operator* (const Color& C, float S) noexcept; - DIRECTX_TOOLKIT_API Color operator* (float S, const Color& C) noexcept; - DIRECTX_TOOLKIT_API Color operator/ (const Color& C1, const Color& C2) noexcept; + DIRECTX_TOOLKIT_API Color operator+(const Color& C1, const Color& C2) noexcept; + DIRECTX_TOOLKIT_API Color operator-(const Color& C1, const Color& C2) noexcept; + DIRECTX_TOOLKIT_API Color operator*(const Color& C1, const Color& C2) noexcept; + DIRECTX_TOOLKIT_API Color operator*(const Color& C, float S) noexcept; + DIRECTX_TOOLKIT_API Color operator*(float S, const Color& C) noexcept; + DIRECTX_TOOLKIT_API Color operator/(const Color& C1, const Color& C2) noexcept; //------------------------------------------------------------------------------ // Ray @@ -906,18 +1314,24 @@ namespace DirectX Vector3 position; Vector3 direction; - Ray() noexcept : position(0, 0, 0), direction(0, 0, 1) {} - Ray(const Vector3& pos, const Vector3& dir) noexcept : position(pos), direction(dir) {} + Ray() noexcept + : position(0, 0, 0), + direction(0, 0, 1) + {} + Ray(const Vector3& pos, const Vector3& dir) noexcept + : position(pos), + direction(dir) + {} - Ray(const Ray&) = default; + Ray(const Ray&) = default; Ray& operator=(const Ray&) = default; - Ray(Ray&&) = default; + Ray(Ray&&) = default; Ray& operator=(Ray&&) = default; // Comparison operators - bool operator == (const Ray& r) const noexcept; - bool operator != (const Ray& r) const noexcept; + bool operator==(const Ray& r) const noexcept; + bool operator!=(const Ray& r) const noexcept; // Ray operations bool Intersects(const BoundingSphere& sphere, _Out_ float& Dist) const noexcept; @@ -938,80 +1352,102 @@ namespace DirectX float minDepth; float maxDepth; - Viewport() noexcept : - x(0.f), y(0.f), width(0.f), height(0.f), minDepth(0.f), maxDepth(1.f) + Viewport() noexcept + : x(0.f), + y(0.f), + width(0.f), + height(0.f), + minDepth(0.f), + maxDepth(1.f) {} - constexpr Viewport(float ix, float iy, float iw, float ih, float iminz = 0.f, float imaxz = 1.f) noexcept : - x(ix), y(iy), width(iw), height(ih), minDepth(iminz), maxDepth(imaxz) + constexpr Viewport(float ix, float iy, float iw, float ih, float iminz = 0.f, float imaxz = 1.f) noexcept + : x(ix), + y(iy), + width(iw), + height(ih), + minDepth(iminz), + maxDepth(imaxz) {} - explicit Viewport(const RECT& rct) noexcept : - x(float(rct.left)), y(float(rct.top)), - width(float(rct.right - rct.left)), - height(float(rct.bottom - rct.top)), - minDepth(0.f), maxDepth(1.f) + explicit Viewport(const RECT& rct) noexcept + : x(float(rct.left)), + y(float(rct.top)), + width(float(rct.right - rct.left)), + height(float(rct.bottom - rct.top)), + minDepth(0.f), + maxDepth(1.f) {} - #if defined(__d3d11_h__) || defined(__d3d11_x_h__) +#if defined(__d3d11_h__) || defined(__d3d11_x_h__) // Direct3D 11 interop - explicit Viewport(const D3D11_VIEWPORT& vp) noexcept : - x(vp.TopLeftX), y(vp.TopLeftY), - width(vp.Width), height(vp.Height), - minDepth(vp.MinDepth), maxDepth(vp.MaxDepth) + explicit Viewport(const D3D11_VIEWPORT& vp) noexcept + : x(vp.TopLeftX), + y(vp.TopLeftY), + width(vp.Width), + height(vp.Height), + minDepth(vp.MinDepth), + maxDepth(vp.MaxDepth) {} - operator D3D11_VIEWPORT() noexcept { return *reinterpret_cast(this); } + operator D3D11_VIEWPORT() noexcept { return *reinterpret_cast(this); } const D3D11_VIEWPORT* Get11() const noexcept { return reinterpret_cast(this); } - Viewport& operator= (const D3D11_VIEWPORT& vp) noexcept; - #endif + Viewport& operator=(const D3D11_VIEWPORT& vp) noexcept; +#endif - #if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) +#if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) // Direct3D 12 interop - explicit Viewport(const D3D12_VIEWPORT& vp) noexcept : - x(vp.TopLeftX), y(vp.TopLeftY), - width(vp.Width), height(vp.Height), - minDepth(vp.MinDepth), maxDepth(vp.MaxDepth) + explicit Viewport(const D3D12_VIEWPORT& vp) noexcept + : x(vp.TopLeftX), + y(vp.TopLeftY), + width(vp.Width), + height(vp.Height), + minDepth(vp.MinDepth), + maxDepth(vp.MaxDepth) {} - operator D3D12_VIEWPORT() noexcept { return *reinterpret_cast(this); } + operator D3D12_VIEWPORT() noexcept { return *reinterpret_cast(this); } const D3D12_VIEWPORT* Get12() const noexcept { return reinterpret_cast(this); } - Viewport& operator= (const D3D12_VIEWPORT& vp) noexcept; - #endif + Viewport& operator=(const D3D12_VIEWPORT& vp) noexcept; +#endif - Viewport(const Viewport&) = default; + Viewport(const Viewport&) = default; Viewport& operator=(const Viewport&) = default; - Viewport(Viewport&&) = default; + Viewport(Viewport&&) = default; Viewport& operator=(Viewport&&) = default; // Comparison operators - #if (__cplusplus >= 202002L) - bool operator == (const Viewport&) const = default; - auto operator <=> (const Viewport&) const = default; - #else - bool operator == (const Viewport& vp) const noexcept; - bool operator != (const Viewport& vp) const noexcept; - #endif +#if (__cplusplus >= 202002L) + bool operator==(const Viewport&) const = default; + auto operator<= > (const Viewport&) const = default; +#else + bool operator==(const Viewport& vp) const noexcept; + bool operator!=(const Viewport& vp) const noexcept; +#endif // Assignment operators - Viewport& operator= (const RECT& rct) noexcept; + Viewport& operator=(const RECT& rct) noexcept; // Viewport operations float AspectRatio() const noexcept; Vector3 Project(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world) const noexcept; - void Project(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept; + void Project(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept; Vector3 Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world) const noexcept; void Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept; // Static methods - #if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) - static RECT __cdecl ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight) noexcept; - #endif +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) + static RECT __cdecl ComputeDisplayArea(DXGI_SCALING scaling, + UINT backBufferWidth, + UINT backBufferHeight, + int outputWidth, + int outputHeight) noexcept; +#endif static RECT __cdecl ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight) noexcept; }; - #include "SimpleMath.inl" +#include "SimpleMath.inl" } // namespace SimpleMath @@ -1022,18 +1458,18 @@ namespace DirectX namespace std { - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Rectangle& r1, const DirectX::SimpleMath::Rectangle& r2) const noexcept { - return ((r1.x < r2.x) - || ((r1.x == r2.x) && (r1.y < r2.y)) - || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width < r2.width)) - || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width == r2.width) && (r1.height < r2.height))); + return ((r1.x < r2.x) || ((r1.x == r2.x) && (r1.y < r2.y)) || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width < r2.width)) + || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width == r2.width) && (r1.height < r2.height))); } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Vector2& V1, const DirectX::SimpleMath::Vector2& V2) const noexcept { @@ -1041,113 +1477,139 @@ namespace std } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Vector3& V1, const DirectX::SimpleMath::Vector3& V2) const noexcept { - return ((V1.x < V2.x) - || ((V1.x == V2.x) && (V1.y < V2.y)) - || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z))); + return ((V1.x < V2.x) || ((V1.x == V2.x) && (V1.y < V2.y)) || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z))); } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Vector4& V1, const DirectX::SimpleMath::Vector4& V2) const noexcept { - return ((V1.x < V2.x) - || ((V1.x == V2.x) && (V1.y < V2.y)) - || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z)) - || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z == V2.z) && (V1.w < V2.w))); + return ((V1.x < V2.x) || ((V1.x == V2.x) && (V1.y < V2.y)) || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z)) + || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z == V2.z) && (V1.w < V2.w))); } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Matrix& M1, const DirectX::SimpleMath::Matrix& M2) const noexcept { - if (M1._11 != M2._11) return M1._11 < M2._11; - if (M1._12 != M2._12) return M1._12 < M2._12; - if (M1._13 != M2._13) return M1._13 < M2._13; - if (M1._14 != M2._14) return M1._14 < M2._14; - if (M1._21 != M2._21) return M1._21 < M2._21; - if (M1._22 != M2._22) return M1._22 < M2._22; - if (M1._23 != M2._23) return M1._23 < M2._23; - if (M1._24 != M2._24) return M1._24 < M2._24; - if (M1._31 != M2._31) return M1._31 < M2._31; - if (M1._32 != M2._32) return M1._32 < M2._32; - if (M1._33 != M2._33) return M1._33 < M2._33; - if (M1._34 != M2._34) return M1._34 < M2._34; - if (M1._41 != M2._41) return M1._41 < M2._41; - if (M1._42 != M2._42) return M1._42 < M2._42; - if (M1._43 != M2._43) return M1._43 < M2._43; - if (M1._44 != M2._44) return M1._44 < M2._44; + if (M1._11 != M2._11) + return M1._11 < M2._11; + if (M1._12 != M2._12) + return M1._12 < M2._12; + if (M1._13 != M2._13) + return M1._13 < M2._13; + if (M1._14 != M2._14) + return M1._14 < M2._14; + if (M1._21 != M2._21) + return M1._21 < M2._21; + if (M1._22 != M2._22) + return M1._22 < M2._22; + if (M1._23 != M2._23) + return M1._23 < M2._23; + if (M1._24 != M2._24) + return M1._24 < M2._24; + if (M1._31 != M2._31) + return M1._31 < M2._31; + if (M1._32 != M2._32) + return M1._32 < M2._32; + if (M1._33 != M2._33) + return M1._33 < M2._33; + if (M1._34 != M2._34) + return M1._34 < M2._34; + if (M1._41 != M2._41) + return M1._41 < M2._41; + if (M1._42 != M2._42) + return M1._42 < M2._42; + if (M1._43 != M2._43) + return M1._43 < M2._43; + if (M1._44 != M2._44) + return M1._44 < M2._44; return false; } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Plane& P1, const DirectX::SimpleMath::Plane& P2) const noexcept { - return ((P1.x < P2.x) - || ((P1.x == P2.x) && (P1.y < P2.y)) - || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z < P2.z)) - || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z == P2.z) && (P1.w < P2.w))); + return ((P1.x < P2.x) || ((P1.x == P2.x) && (P1.y < P2.y)) || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z < P2.z)) + || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z == P2.z) && (P1.w < P2.w))); } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Quaternion& Q1, const DirectX::SimpleMath::Quaternion& Q2) const noexcept { - return ((Q1.x < Q2.x) - || ((Q1.x == Q2.x) && (Q1.y < Q2.y)) - || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z < Q2.z)) - || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z == Q2.z) && (Q1.w < Q2.w))); + return ((Q1.x < Q2.x) || ((Q1.x == Q2.x) && (Q1.y < Q2.y)) || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z < Q2.z)) + || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z == Q2.z) && (Q1.w < Q2.w))); } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Color& C1, const DirectX::SimpleMath::Color& C2) const noexcept { - return ((C1.x < C2.x) - || ((C1.x == C2.x) && (C1.y < C2.y)) - || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z < C2.z)) - || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z == C2.z) && (C1.w < C2.w))); + return ((C1.x < C2.x) || ((C1.x == C2.x) && (C1.y < C2.y)) || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z < C2.z)) + || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z == C2.z) && (C1.w < C2.w))); } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Ray& R1, const DirectX::SimpleMath::Ray& R2) const noexcept { - if (R1.position.x != R2.position.x) return R1.position.x < R2.position.x; - if (R1.position.y != R2.position.y) return R1.position.y < R2.position.y; - if (R1.position.z != R2.position.z) return R1.position.z < R2.position.z; - - if (R1.direction.x != R2.direction.x) return R1.direction.x < R2.direction.x; - if (R1.direction.y != R2.direction.y) return R1.direction.y < R2.direction.y; - if (R1.direction.z != R2.direction.z) return R1.direction.z < R2.direction.z; + if (R1.position.x != R2.position.x) + return R1.position.x < R2.position.x; + if (R1.position.y != R2.position.y) + return R1.position.y < R2.position.y; + if (R1.position.z != R2.position.z) + return R1.position.z < R2.position.z; + + if (R1.direction.x != R2.direction.x) + return R1.direction.x < R2.direction.x; + if (R1.direction.y != R2.direction.y) + return R1.direction.y < R2.direction.y; + if (R1.direction.z != R2.direction.z) + return R1.direction.z < R2.direction.z; return false; } }; - template<> struct less + template<> + struct less { bool operator()(const DirectX::SimpleMath::Viewport& vp1, const DirectX::SimpleMath::Viewport& vp2) const noexcept { - if (vp1.x != vp2.x) return (vp1.x < vp2.x); - if (vp1.y != vp2.y) return (vp1.y < vp2.y); - - if (vp1.width != vp2.width) return (vp1.width < vp2.width); - if (vp1.height != vp2.height) return (vp1.height < vp2.height); - - if (vp1.minDepth != vp2.minDepth) return (vp1.minDepth < vp2.minDepth); - if (vp1.maxDepth != vp2.maxDepth) return (vp1.maxDepth < vp2.maxDepth); + if (vp1.x != vp2.x) + return (vp1.x < vp2.x); + if (vp1.y != vp2.y) + return (vp1.y < vp2.y); + + if (vp1.width != vp2.width) + return (vp1.width < vp2.width); + if (vp1.height != vp2.height) + return (vp1.height < vp2.height); + + if (vp1.minDepth != vp2.minDepth) + return (vp1.minDepth < vp2.minDepth); + if (vp1.maxDepth != vp2.maxDepth) + return (vp1.maxDepth < vp2.maxDepth); return false; } diff --git a/Inc/SimpleMath.inl b/Inc/SimpleMath.inl index 8cdb78f5..af1f8067 100644 --- a/Inc/SimpleMath.inl +++ b/Inc/SimpleMath.inl @@ -11,10 +11,10 @@ #pragma once /**************************************************************************** -* -* Rectangle -* -****************************************************************************/ + * + * Rectangle + * + ****************************************************************************/ //------------------------------------------------------------------------------ // Rectangle operations @@ -57,23 +57,23 @@ inline Rectangle Rectangle::Intersect(const Rectangle& ra, const Rectangle& rb) const long maxX = ra.x > rb.x ? ra.x : rb.x; const long maxY = ra.y > rb.y ? ra.y : rb.y; - const long minRight = righta < rightb ? righta : rightb; + const long minRight = righta < rightb ? righta : rightb; const long minBottom = bottoma < bottomb ? bottoma : bottomb; Rectangle result; if ((minRight > maxX) && (minBottom > maxY)) { - result.x = maxX; - result.y = maxY; - result.width = minRight - maxX; + result.x = maxX; + result.y = maxY; + result.width = minRight - maxX; result.height = minBottom - maxY; } else { - result.x = 0; - result.y = 0; - result.width = 0; + result.x = 0; + result.y = 0; + result.width = 0; result.height = 0; } @@ -85,23 +85,23 @@ inline RECT Rectangle::Intersect(const RECT& rcta, const RECT& rctb) noexcept const long maxX = rcta.left > rctb.left ? rcta.left : rctb.left; const long maxY = rcta.top > rctb.top ? rcta.top : rctb.top; - const long minRight = rcta.right < rctb.right ? rcta.right : rctb.right; + const long minRight = rcta.right < rctb.right ? rcta.right : rctb.right; const long minBottom = rcta.bottom < rctb.bottom ? rcta.bottom : rctb.bottom; RECT result; if ((minRight > maxX) && (minBottom > maxY)) { - result.left = maxX; - result.top = maxY; - result.right = minRight; + result.left = maxX; + result.top = maxY; + result.right = minRight; result.bottom = minBottom; } else { - result.left = 0; - result.top = 0; - result.right = 0; + result.left = 0; + result.top = 0; + result.right = 0; result.bottom = 0; } @@ -119,13 +119,13 @@ inline Rectangle Rectangle::Union(const Rectangle& ra, const Rectangle& rb) noex const int minX = ra.x < rb.x ? ra.x : rb.x; const int minY = ra.y < rb.y ? ra.y : rb.y; - const int maxRight = righta > rightb ? righta : rightb; + const int maxRight = righta > rightb ? righta : rightb; const int maxBottom = bottoma > bottomb ? bottoma : bottomb; Rectangle result; - result.x = minX; - result.y = minY; - result.width = maxRight - minX; + result.x = minX; + result.y = minY; + result.width = maxRight - minX; result.height = maxBottom - minY; return result; } @@ -133,14 +133,13 @@ inline Rectangle Rectangle::Union(const Rectangle& ra, const Rectangle& rb) noex inline RECT Rectangle::Union(const RECT& rcta, const RECT& rctb) noexcept { RECT result; - result.left = rcta.left < rctb.left ? rcta.left : rctb.left; - result.top = rcta.top < rctb.top ? rcta.top : rctb.top; - result.right = rcta.right > rctb.right ? rcta.right : rctb.right; + result.left = rcta.left < rctb.left ? rcta.left : rctb.left; + result.top = rcta.top < rctb.top ? rcta.top : rctb.top; + result.right = rcta.right > rctb.right ? rcta.right : rctb.right; result.bottom = rcta.bottom > rctb.bottom ? rcta.bottom : rctb.bottom; return result; } - /**************************************************************************** * * Vector2 @@ -163,7 +162,7 @@ inline void Vector2::Normalize() noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(this); - const XMVECTOR X = XMVector2Normalize(v1); + const XMVECTOR X = XMVector2Normalize(v1); XMStoreFloat2(this, X); } @@ -171,7 +170,7 @@ inline void Vector2::Normalize(Vector2& result) const noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(this); - const XMVECTOR X = XMVector2Normalize(v1); + const XMVECTOR X = XMVector2Normalize(v1); XMStoreFloat2(&result, X); } @@ -181,7 +180,7 @@ inline void Vector2::Clamp(const Vector2& vmin, const Vector2& vmax) noexcept const XMVECTOR v1 = XMLoadFloat2(this); const XMVECTOR v2 = XMLoadFloat2(&vmin); const XMVECTOR v3 = XMLoadFloat2(&vmax); - const XMVECTOR X = XMVectorClamp(v1, v2, v3); + const XMVECTOR X = XMVectorClamp(v1, v2, v3); XMStoreFloat2(this, X); } @@ -191,7 +190,7 @@ inline void Vector2::Clamp(const Vector2& vmin, const Vector2& vmax, Vector2& re const XMVECTOR v1 = XMLoadFloat2(this); const XMVECTOR v2 = XMLoadFloat2(&vmin); const XMVECTOR v3 = XMLoadFloat2(&vmax); - const XMVECTOR X = XMVectorClamp(v1, v2, v3); + const XMVECTOR X = XMVectorClamp(v1, v2, v3); XMStoreFloat2(&result, X); } @@ -204,8 +203,8 @@ inline float Vector2::Distance(const Vector2& v1, const Vector2& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR V = XMVectorSubtract(x2, x1); - const XMVECTOR X = XMVector2Length(V); + const XMVECTOR V = XMVectorSubtract(x2, x1); + const XMVECTOR X = XMVector2Length(V); return XMVectorGetX(X); } @@ -214,8 +213,8 @@ inline float Vector2::DistanceSquared(const Vector2& v1, const Vector2& v2) noex using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR V = XMVectorSubtract(x2, x1); - const XMVECTOR X = XMVector2LengthSq(V); + const XMVECTOR V = XMVectorSubtract(x2, x1); + const XMVECTOR X = XMVector2LengthSq(V); return XMVectorGetX(X); } @@ -224,7 +223,7 @@ inline void Vector2::Min(const Vector2& v1, const Vector2& v2, Vector2& result) using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorMin(x1, x2); + const XMVECTOR X = XMVectorMin(x1, x2); XMStoreFloat2(&result, X); } @@ -233,7 +232,7 @@ inline Vector2 Vector2::Min(const Vector2& v1, const Vector2& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorMin(x1, x2); + const XMVECTOR X = XMVectorMin(x1, x2); Vector2 result; XMStoreFloat2(&result, X); @@ -245,7 +244,7 @@ inline void Vector2::Max(const Vector2& v1, const Vector2& v2, Vector2& result) using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorMax(x1, x2); + const XMVECTOR X = XMVectorMax(x1, x2); XMStoreFloat2(&result, X); } @@ -254,7 +253,7 @@ inline Vector2 Vector2::Max(const Vector2& v1, const Vector2& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorMax(x1, x2); + const XMVECTOR X = XMVectorMax(x1, x2); Vector2 result; XMStoreFloat2(&result, X); @@ -266,7 +265,7 @@ inline void Vector2::Lerp(const Vector2& v1, const Vector2& v2, float t, Vector2 using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); XMStoreFloat2(&result, X); } @@ -275,7 +274,7 @@ inline Vector2 Vector2::Lerp(const Vector2& v1, const Vector2& v2, float t) noex using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); Vector2 result; XMStoreFloat2(&result, X); @@ -285,22 +284,22 @@ inline Vector2 Vector2::Lerp(const Vector2& v1, const Vector2& v2, float t) noex inline void Vector2::SmoothStep(const Vector2& v1, const Vector2& v2, float t, Vector2& result) noexcept { using namespace DirectX; - t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 - t = t * t*(3.f - 2.f*t); + t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 + t = t * t * (3.f - 2.f * t); const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); XMStoreFloat2(&result, X); } inline Vector2 Vector2::SmoothStep(const Vector2& v1, const Vector2& v2, float t) noexcept { using namespace DirectX; - t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 - t = t * t*(3.f - 2.f*t); + t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 + t = t * t * (3.f - 2.f * t); const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); Vector2 result; XMStoreFloat2(&result, X); @@ -313,7 +312,7 @@ inline void Vector2::Barycentric(const Vector2& v1, const Vector2& v2, const Vec const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); const XMVECTOR x3 = XMLoadFloat2(&v3); - const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); + const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); XMStoreFloat2(&result, X); } @@ -323,21 +322,22 @@ inline Vector2 Vector2::Barycentric(const Vector2& v1, const Vector2& v2, const const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); const XMVECTOR x3 = XMLoadFloat2(&v3); - const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); + const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); Vector2 result; XMStoreFloat2(&result, X); return result; } -inline void Vector2::CatmullRom(const Vector2& v1, const Vector2& v2, const Vector2& v3, const Vector2& v4, float t, Vector2& result) noexcept +inline void +Vector2::CatmullRom(const Vector2& v1, const Vector2& v2, const Vector2& v3, const Vector2& v4, float t, Vector2& result) noexcept { using namespace DirectX; const XMVECTOR x1 = XMLoadFloat2(&v1); const XMVECTOR x2 = XMLoadFloat2(&v2); const XMVECTOR x3 = XMLoadFloat2(&v3); const XMVECTOR x4 = XMLoadFloat2(&v4); - const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); XMStoreFloat2(&result, X); } @@ -348,7 +348,7 @@ inline Vector2 Vector2::CatmullRom(const Vector2& v1, const Vector2& v2, const V const XMVECTOR x2 = XMLoadFloat2(&v2); const XMVECTOR x3 = XMLoadFloat2(&v3); const XMVECTOR x4 = XMLoadFloat2(&v4); - const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); Vector2 result; XMStoreFloat2(&result, X); @@ -362,7 +362,7 @@ inline void Vector2::Hermite(const Vector2& v1, const Vector2& t1, const Vector2 const XMVECTOR x2 = XMLoadFloat2(&t1); const XMVECTOR x3 = XMLoadFloat2(&v2); const XMVECTOR x4 = XMLoadFloat2(&t2); - const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); XMStoreFloat2(&result, X); } @@ -373,7 +373,7 @@ inline Vector2 Vector2::Hermite(const Vector2& v1, const Vector2& t1, const Vect const XMVECTOR x2 = XMLoadFloat2(&t1); const XMVECTOR x3 = XMLoadFloat2(&v2); const XMVECTOR x4 = XMLoadFloat2(&t2); - const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); Vector2 result; XMStoreFloat2(&result, X); @@ -426,8 +426,8 @@ inline void Vector2::Transform(const Vector2& v, const Quaternion& quat, Vector2 { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - const XMVECTOR X = XMVector3Rotate(v1, q); + const XMVECTOR q = XMLoadFloat4(&quat); + const XMVECTOR X = XMVector3Rotate(v1, q); XMStoreFloat2(&result, X); } @@ -435,8 +435,8 @@ inline Vector2 Vector2::Transform(const Vector2& v, const Quaternion& quat) noex { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - const XMVECTOR X = XMVector3Rotate(v1, q); + const XMVECTOR q = XMLoadFloat4(&quat); + const XMVECTOR X = XMVector3Rotate(v1, q); Vector2 result; XMStoreFloat2(&result, X); @@ -447,8 +447,8 @@ inline void Vector2::Transform(const Vector2& v, const Matrix& m, Vector2& resul { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector2TransformCoord(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector2TransformCoord(v1, M); XMStoreFloat2(&result, X); } @@ -456,16 +456,15 @@ inline Vector2 Vector2::Transform(const Vector2& v, const Matrix& m) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector2TransformCoord(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector2TransformCoord(v1, M); Vector2 result; XMStoreFloat2(&result, X); return result; } -_Use_decl_annotations_ -inline void Vector2::Transform(const Vector2* varray, size_t count, const Matrix& m, Vector2* resultArray) noexcept +_Use_decl_annotations_ inline void Vector2::Transform(const Vector2* varray, size_t count, const Matrix& m, Vector2* resultArray) noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(&m); @@ -476,13 +475,12 @@ inline void Vector2::Transform(const Vector2& v, const Matrix& m, Vector4& resul { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector2Transform(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector2Transform(v1, M); XMStoreFloat4(&result, X); } -_Use_decl_annotations_ -inline void Vector2::Transform(const Vector2* varray, size_t count, const Matrix& m, Vector4* resultArray) noexcept +_Use_decl_annotations_ inline void Vector2::Transform(const Vector2* varray, size_t count, const Matrix& m, Vector4* resultArray) noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(&m); @@ -493,8 +491,8 @@ inline void Vector2::TransformNormal(const Vector2& v, const Matrix& m, Vector2& { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector2TransformNormal(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector2TransformNormal(v1, M); XMStoreFloat2(&result, X); } @@ -502,23 +500,22 @@ inline Vector2 Vector2::TransformNormal(const Vector2& v, const Matrix& m) noexc { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector2TransformNormal(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector2TransformNormal(v1, M); Vector2 result; XMStoreFloat2(&result, X); return result; } -_Use_decl_annotations_ -inline void Vector2::TransformNormal(const Vector2* varray, size_t count, const Matrix& m, Vector2* resultArray) noexcept +_Use_decl_annotations_ inline void +Vector2::TransformNormal(const Vector2* varray, size_t count, const Matrix& m, Vector2* resultArray) noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(&m); XMVector2TransformNormalStream(resultArray, sizeof(XMFLOAT2), varray, sizeof(XMFLOAT2), count, M); } - /**************************************************************************** * * Vector3 @@ -541,7 +538,7 @@ inline void Vector3::Normalize() noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(this); - const XMVECTOR X = XMVector3Normalize(v1); + const XMVECTOR X = XMVector3Normalize(v1); XMStoreFloat3(this, X); } @@ -549,7 +546,7 @@ inline void Vector3::Normalize(Vector3& result) const noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(this); - const XMVECTOR X = XMVector3Normalize(v1); + const XMVECTOR X = XMVector3Normalize(v1); XMStoreFloat3(&result, X); } @@ -559,7 +556,7 @@ inline void Vector3::Clamp(const Vector3& vmin, const Vector3& vmax) noexcept const XMVECTOR v1 = XMLoadFloat3(this); const XMVECTOR v2 = XMLoadFloat3(&vmin); const XMVECTOR v3 = XMLoadFloat3(&vmax); - const XMVECTOR X = XMVectorClamp(v1, v2, v3); + const XMVECTOR X = XMVectorClamp(v1, v2, v3); XMStoreFloat3(this, X); } @@ -569,7 +566,7 @@ inline void Vector3::Clamp(const Vector3& vmin, const Vector3& vmax, Vector3& re const XMVECTOR v1 = XMLoadFloat3(this); const XMVECTOR v2 = XMLoadFloat3(&vmin); const XMVECTOR v3 = XMLoadFloat3(&vmax); - const XMVECTOR X = XMVectorClamp(v1, v2, v3); + const XMVECTOR X = XMVectorClamp(v1, v2, v3); XMStoreFloat3(&result, X); } @@ -582,8 +579,8 @@ inline float Vector3::Distance(const Vector3& v1, const Vector3& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR V = XMVectorSubtract(x2, x1); - const XMVECTOR X = XMVector3Length(V); + const XMVECTOR V = XMVectorSubtract(x2, x1); + const XMVECTOR X = XMVector3Length(V); return XMVectorGetX(X); } @@ -592,8 +589,8 @@ inline float Vector3::DistanceSquared(const Vector3& v1, const Vector3& v2) noex using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR V = XMVectorSubtract(x2, x1); - const XMVECTOR X = XMVector3LengthSq(V); + const XMVECTOR V = XMVectorSubtract(x2, x1); + const XMVECTOR X = XMVector3LengthSq(V); return XMVectorGetX(X); } @@ -602,7 +599,7 @@ inline void Vector3::Min(const Vector3& v1, const Vector3& v2, Vector3& result) using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorMin(x1, x2); + const XMVECTOR X = XMVectorMin(x1, x2); XMStoreFloat3(&result, X); } @@ -611,7 +608,7 @@ inline Vector3 Vector3::Min(const Vector3& v1, const Vector3& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorMin(x1, x2); + const XMVECTOR X = XMVectorMin(x1, x2); Vector3 result; XMStoreFloat3(&result, X); @@ -623,7 +620,7 @@ inline void Vector3::Max(const Vector3& v1, const Vector3& v2, Vector3& result) using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorMax(x1, x2); + const XMVECTOR X = XMVectorMax(x1, x2); XMStoreFloat3(&result, X); } @@ -632,7 +629,7 @@ inline Vector3 Vector3::Max(const Vector3& v1, const Vector3& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorMax(x1, x2); + const XMVECTOR X = XMVectorMax(x1, x2); Vector3 result; XMStoreFloat3(&result, X); @@ -644,7 +641,7 @@ inline void Vector3::Lerp(const Vector3& v1, const Vector3& v2, float t, Vector3 using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); XMStoreFloat3(&result, X); } @@ -653,7 +650,7 @@ inline Vector3 Vector3::Lerp(const Vector3& v1, const Vector3& v2, float t) noex using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); Vector3 result; XMStoreFloat3(&result, X); @@ -663,22 +660,22 @@ inline Vector3 Vector3::Lerp(const Vector3& v1, const Vector3& v2, float t) noex inline void Vector3::SmoothStep(const Vector3& v1, const Vector3& v2, float t, Vector3& result) noexcept { using namespace DirectX; - t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 - t = t * t*(3.f - 2.f*t); + t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 + t = t * t * (3.f - 2.f * t); const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); XMStoreFloat3(&result, X); } inline Vector3 Vector3::SmoothStep(const Vector3& v1, const Vector3& v2, float t) noexcept { using namespace DirectX; - t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 - t = t * t*(3.f - 2.f*t); + t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 + t = t * t * (3.f - 2.f * t); const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); Vector3 result; XMStoreFloat3(&result, X); @@ -691,7 +688,7 @@ inline void Vector3::Barycentric(const Vector3& v1, const Vector3& v2, const Vec const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); const XMVECTOR x3 = XMLoadFloat3(&v3); - const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); + const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); XMStoreFloat3(&result, X); } @@ -701,21 +698,22 @@ inline Vector3 Vector3::Barycentric(const Vector3& v1, const Vector3& v2, const const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); const XMVECTOR x3 = XMLoadFloat3(&v3); - const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); + const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); Vector3 result; XMStoreFloat3(&result, X); return result; } -inline void Vector3::CatmullRom(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float t, Vector3& result) noexcept +inline void +Vector3::CatmullRom(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float t, Vector3& result) noexcept { using namespace DirectX; const XMVECTOR x1 = XMLoadFloat3(&v1); const XMVECTOR x2 = XMLoadFloat3(&v2); const XMVECTOR x3 = XMLoadFloat3(&v3); const XMVECTOR x4 = XMLoadFloat3(&v4); - const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); XMStoreFloat3(&result, X); } @@ -726,7 +724,7 @@ inline Vector3 Vector3::CatmullRom(const Vector3& v1, const Vector3& v2, const V const XMVECTOR x2 = XMLoadFloat3(&v2); const XMVECTOR x3 = XMLoadFloat3(&v3); const XMVECTOR x4 = XMLoadFloat3(&v4); - const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); Vector3 result; XMStoreFloat3(&result, X); @@ -740,7 +738,7 @@ inline void Vector3::Hermite(const Vector3& v1, const Vector3& t1, const Vector3 const XMVECTOR x2 = XMLoadFloat3(&t1); const XMVECTOR x3 = XMLoadFloat3(&v2); const XMVECTOR x4 = XMLoadFloat3(&t2); - const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); XMStoreFloat3(&result, X); } @@ -751,7 +749,7 @@ inline Vector3 Vector3::Hermite(const Vector3& v1, const Vector3& t1, const Vect const XMVECTOR x2 = XMLoadFloat3(&t1); const XMVECTOR x3 = XMLoadFloat3(&v2); const XMVECTOR x4 = XMLoadFloat3(&t2); - const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); Vector3 result; XMStoreFloat3(&result, X); @@ -804,8 +802,8 @@ inline void Vector3::Transform(const Vector3& v, const Quaternion& quat, Vector3 { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - const XMVECTOR X = XMVector3Rotate(v1, q); + const XMVECTOR q = XMLoadFloat4(&quat); + const XMVECTOR X = XMVector3Rotate(v1, q); XMStoreFloat3(&result, X); } @@ -813,8 +811,8 @@ inline Vector3 Vector3::Transform(const Vector3& v, const Quaternion& quat) noex { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - const XMVECTOR X = XMVector3Rotate(v1, q); + const XMVECTOR q = XMLoadFloat4(&quat); + const XMVECTOR X = XMVector3Rotate(v1, q); Vector3 result; XMStoreFloat3(&result, X); @@ -825,8 +823,8 @@ inline void Vector3::Transform(const Vector3& v, const Matrix& m, Vector3& resul { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector3TransformCoord(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector3TransformCoord(v1, M); XMStoreFloat3(&result, X); } @@ -834,16 +832,15 @@ inline Vector3 Vector3::Transform(const Vector3& v, const Matrix& m) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector3TransformCoord(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector3TransformCoord(v1, M); Vector3 result; XMStoreFloat3(&result, X); return result; } -_Use_decl_annotations_ -inline void Vector3::Transform(const Vector3* varray, size_t count, const Matrix& m, Vector3* resultArray) noexcept +_Use_decl_annotations_ inline void Vector3::Transform(const Vector3* varray, size_t count, const Matrix& m, Vector3* resultArray) noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(&m); @@ -854,13 +851,12 @@ inline void Vector3::Transform(const Vector3& v, const Matrix& m, Vector4& resul { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector3Transform(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector3Transform(v1, M); XMStoreFloat4(&result, X); } -_Use_decl_annotations_ -inline void Vector3::Transform(const Vector3* varray, size_t count, const Matrix& m, Vector4* resultArray) noexcept +_Use_decl_annotations_ inline void Vector3::Transform(const Vector3* varray, size_t count, const Matrix& m, Vector4* resultArray) noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(&m); @@ -871,8 +867,8 @@ inline void Vector3::TransformNormal(const Vector3& v, const Matrix& m, Vector3& { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector3TransformNormal(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector3TransformNormal(v1, M); XMStoreFloat3(&result, X); } @@ -880,23 +876,22 @@ inline Vector3 Vector3::TransformNormal(const Vector3& v, const Matrix& m) noexc { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector3TransformNormal(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector3TransformNormal(v1, M); Vector3 result; XMStoreFloat3(&result, X); return result; } -_Use_decl_annotations_ -inline void Vector3::TransformNormal(const Vector3* varray, size_t count, const Matrix& m, Vector3* resultArray) noexcept +_Use_decl_annotations_ inline void +Vector3::TransformNormal(const Vector3* varray, size_t count, const Matrix& m, Vector3* resultArray) noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(&m); XMVector3TransformNormalStream(resultArray, sizeof(XMFLOAT3), varray, sizeof(XMFLOAT3), count, M); } - /**************************************************************************** * * Vector4 @@ -907,7 +902,7 @@ inline void Vector3::TransformNormal(const Vector3* varray, size_t count, const // Comparision operators //------------------------------------------------------------------------------ -inline bool Vector4::operator == (const Vector4& V) const noexcept +inline bool Vector4::operator==(const Vector4& V) const noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); @@ -915,7 +910,7 @@ inline bool Vector4::operator == (const Vector4& V) const noexcept return XMVector4Equal(v1, v2); } -inline bool Vector4::operator != (const Vector4& V) const noexcept +inline bool Vector4::operator!=(const Vector4& V) const noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); @@ -927,37 +922,37 @@ inline bool Vector4::operator != (const Vector4& V) const noexcept // Assignment operators //------------------------------------------------------------------------------ -inline Vector4& Vector4::operator+= (const Vector4& V) noexcept +inline Vector4& Vector4::operator+=(const Vector4& V) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); const XMVECTOR v2 = XMLoadFloat4(&V); - const XMVECTOR X = XMVectorAdd(v1, v2); + const XMVECTOR X = XMVectorAdd(v1, v2); XMStoreFloat4(this, X); return *this; } -inline Vector4& Vector4::operator-= (const Vector4& V) noexcept +inline Vector4& Vector4::operator-=(const Vector4& V) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); const XMVECTOR v2 = XMLoadFloat4(&V); - const XMVECTOR X = XMVectorSubtract(v1, v2); + const XMVECTOR X = XMVectorSubtract(v1, v2); XMStoreFloat4(this, X); return *this; } -inline Vector4& Vector4::operator*= (const Vector4& V) noexcept +inline Vector4& Vector4::operator*=(const Vector4& V) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); const XMVECTOR v2 = XMLoadFloat4(&V); - const XMVECTOR X = XMVectorMultiply(v1, v2); + const XMVECTOR X = XMVectorMultiply(v1, v2); XMStoreFloat4(this, X); return *this; } -inline Vector4& Vector4::operator*= (float S) noexcept +inline Vector4& Vector4::operator*=(float S) noexcept { using namespace DirectX; const XMVECTOR v = XMLoadFloat4(this); @@ -966,7 +961,7 @@ inline Vector4& Vector4::operator*= (float S) noexcept return *this; } -inline Vector4& Vector4::operator/= (float S) noexcept +inline Vector4& Vector4::operator/=(float S) noexcept { using namespace DirectX; assert(S != 0.0f); @@ -980,90 +975,89 @@ inline Vector4& Vector4::operator/= (float S) noexcept // Binary operators //------------------------------------------------------------------------------ -inline Vector4 operator+ (const Vector4& V1, const Vector4& V2) noexcept +inline Vector4 operator+(const Vector4& V1, const Vector4& V2) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&V1); const XMVECTOR v2 = XMLoadFloat4(&V2); - const XMVECTOR X = XMVectorAdd(v1, v2); - Vector4 R; + const XMVECTOR X = XMVectorAdd(v1, v2); + Vector4 R; XMStoreFloat4(&R, X); return R; } -inline Vector4 operator- (const Vector4& V1, const Vector4& V2) noexcept +inline Vector4 operator-(const Vector4& V1, const Vector4& V2) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&V1); const XMVECTOR v2 = XMLoadFloat4(&V2); - const XMVECTOR X = XMVectorSubtract(v1, v2); - Vector4 R; + const XMVECTOR X = XMVectorSubtract(v1, v2); + Vector4 R; XMStoreFloat4(&R, X); return R; } -inline Vector4 operator* (const Vector4& V1, const Vector4& V2) noexcept +inline Vector4 operator*(const Vector4& V1, const Vector4& V2) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&V1); const XMVECTOR v2 = XMLoadFloat4(&V2); - const XMVECTOR X = XMVectorMultiply(v1, v2); - Vector4 R; + const XMVECTOR X = XMVectorMultiply(v1, v2); + Vector4 R; XMStoreFloat4(&R, X); return R; } -inline Vector4 operator* (const Vector4& V, float S) noexcept +inline Vector4 operator*(const Vector4& V, float S) noexcept { using namespace DirectX; const XMVECTOR v = XMLoadFloat4(&V); const XMVECTOR X = XMVectorScale(v, S); - Vector4 R; + Vector4 R; XMStoreFloat4(&R, X); return R; } -inline Vector4 operator* (float S, const Vector4& V) noexcept +inline Vector4 operator*(float S, const Vector4& V) noexcept { using namespace DirectX; const XMVECTOR v = XMLoadFloat4(&V); const XMVECTOR X = XMVectorScale(v, S); - Vector4 R; + Vector4 R; XMStoreFloat4(&R, X); return R; } -inline Vector4 operator/ (const Vector4& V1, const Vector4& V2) noexcept +inline Vector4 operator/(const Vector4& V1, const Vector4& V2) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&V1); const XMVECTOR v2 = XMLoadFloat4(&V2); - const XMVECTOR X = XMVectorDivide(v1, v2); - Vector4 R; + const XMVECTOR X = XMVectorDivide(v1, v2); + Vector4 R; XMStoreFloat4(&R, X); return R; } -inline Vector4 operator/ (const Vector4& V, float S) noexcept +inline Vector4 operator/(const Vector4& V, float S) noexcept { using namespace DirectX; const XMVECTOR v = XMLoadFloat4(&V); const XMVECTOR X = XMVectorScale(v, 1.f / S); - Vector4 R; + Vector4 R; XMStoreFloat4(&R, X); return R; } -inline Vector4 operator/ (float S, const Vector4& V) noexcept +inline Vector4 operator/(float S, const Vector4& V) noexcept { using namespace DirectX; const XMVECTOR v1 = XMVectorReplicate(S); const XMVECTOR v2 = XMLoadFloat4(&V); - const XMVECTOR X = XMVectorDivide(v1, v2); - Vector4 R; + const XMVECTOR X = XMVectorDivide(v1, v2); + Vector4 R; XMStoreFloat4(&R, X); return R; - } //------------------------------------------------------------------------------ @@ -1082,7 +1076,7 @@ inline float Vector4::Length() const noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); - const XMVECTOR X = XMVector4Length(v1); + const XMVECTOR X = XMVector4Length(v1); return XMVectorGetX(X); } @@ -1090,7 +1084,7 @@ inline float Vector4::LengthSquared() const noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); - const XMVECTOR X = XMVector4LengthSq(v1); + const XMVECTOR X = XMVector4LengthSq(v1); return XMVectorGetX(X); } @@ -1099,7 +1093,7 @@ inline float Vector4::Dot(const Vector4& V) const noexcept using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); const XMVECTOR v2 = XMLoadFloat4(&V); - const XMVECTOR X = XMVector4Dot(v1, v2); + const XMVECTOR X = XMVector4Dot(v1, v2); return XMVectorGetX(X); } @@ -1109,7 +1103,7 @@ inline void Vector4::Cross(const Vector4& v1, const Vector4& v2, Vector4& result const XMVECTOR x1 = XMLoadFloat4(this); const XMVECTOR x2 = XMLoadFloat4(&v1); const XMVECTOR x3 = XMLoadFloat4(&v2); - const XMVECTOR R = XMVector4Cross(x1, x2, x3); + const XMVECTOR R = XMVector4Cross(x1, x2, x3); XMStoreFloat4(&result, R); } @@ -1119,7 +1113,7 @@ inline Vector4 Vector4::Cross(const Vector4& v1, const Vector4& v2) const noexce const XMVECTOR x1 = XMLoadFloat4(this); const XMVECTOR x2 = XMLoadFloat4(&v1); const XMVECTOR x3 = XMLoadFloat4(&v2); - const XMVECTOR R = XMVector4Cross(x1, x2, x3); + const XMVECTOR R = XMVector4Cross(x1, x2, x3); Vector4 result; XMStoreFloat4(&result, R); @@ -1130,7 +1124,7 @@ inline void Vector4::Normalize() noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); - const XMVECTOR X = XMVector4Normalize(v1); + const XMVECTOR X = XMVector4Normalize(v1); XMStoreFloat4(this, X); } @@ -1138,7 +1132,7 @@ inline void Vector4::Normalize(Vector4& result) const noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(this); - const XMVECTOR X = XMVector4Normalize(v1); + const XMVECTOR X = XMVector4Normalize(v1); XMStoreFloat4(&result, X); } @@ -1148,7 +1142,7 @@ inline void Vector4::Clamp(const Vector4& vmin, const Vector4& vmax) noexcept const XMVECTOR v1 = XMLoadFloat4(this); const XMVECTOR v2 = XMLoadFloat4(&vmin); const XMVECTOR v3 = XMLoadFloat4(&vmax); - const XMVECTOR X = XMVectorClamp(v1, v2, v3); + const XMVECTOR X = XMVectorClamp(v1, v2, v3); XMStoreFloat4(this, X); } @@ -1158,7 +1152,7 @@ inline void Vector4::Clamp(const Vector4& vmin, const Vector4& vmax, Vector4& re const XMVECTOR v1 = XMLoadFloat4(this); const XMVECTOR v2 = XMLoadFloat4(&vmin); const XMVECTOR v3 = XMLoadFloat4(&vmax); - const XMVECTOR X = XMVectorClamp(v1, v2, v3); + const XMVECTOR X = XMVectorClamp(v1, v2, v3); XMStoreFloat4(&result, X); } @@ -1171,8 +1165,8 @@ inline float Vector4::Distance(const Vector4& v1, const Vector4& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR V = XMVectorSubtract(x2, x1); - const XMVECTOR X = XMVector4Length(V); + const XMVECTOR V = XMVectorSubtract(x2, x1); + const XMVECTOR X = XMVector4Length(V); return XMVectorGetX(X); } @@ -1181,8 +1175,8 @@ inline float Vector4::DistanceSquared(const Vector4& v1, const Vector4& v2) noex using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR V = XMVectorSubtract(x2, x1); - const XMVECTOR X = XMVector4LengthSq(V); + const XMVECTOR V = XMVectorSubtract(x2, x1); + const XMVECTOR X = XMVector4LengthSq(V); return XMVectorGetX(X); } @@ -1191,7 +1185,7 @@ inline void Vector4::Min(const Vector4& v1, const Vector4& v2, Vector4& result) using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorMin(x1, x2); + const XMVECTOR X = XMVectorMin(x1, x2); XMStoreFloat4(&result, X); } @@ -1200,7 +1194,7 @@ inline Vector4 Vector4::Min(const Vector4& v1, const Vector4& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorMin(x1, x2); + const XMVECTOR X = XMVectorMin(x1, x2); Vector4 result; XMStoreFloat4(&result, X); @@ -1212,7 +1206,7 @@ inline void Vector4::Max(const Vector4& v1, const Vector4& v2, Vector4& result) using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorMax(x1, x2); + const XMVECTOR X = XMVectorMax(x1, x2); XMStoreFloat4(&result, X); } @@ -1221,7 +1215,7 @@ inline Vector4 Vector4::Max(const Vector4& v1, const Vector4& v2) noexcept using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorMax(x1, x2); + const XMVECTOR X = XMVectorMax(x1, x2); Vector4 result; XMStoreFloat4(&result, X); @@ -1233,7 +1227,7 @@ inline void Vector4::Lerp(const Vector4& v1, const Vector4& v2, float t, Vector4 using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); XMStoreFloat4(&result, X); } @@ -1242,7 +1236,7 @@ inline Vector4 Vector4::Lerp(const Vector4& v1, const Vector4& v2, float t) noex using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); Vector4 result; XMStoreFloat4(&result, X); @@ -1252,22 +1246,22 @@ inline Vector4 Vector4::Lerp(const Vector4& v1, const Vector4& v2, float t) noex inline void Vector4::SmoothStep(const Vector4& v1, const Vector4& v2, float t, Vector4& result) noexcept { using namespace DirectX; - t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 - t = t * t*(3.f - 2.f*t); + t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 + t = t * t * (3.f - 2.f * t); const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); XMStoreFloat4(&result, X); } inline Vector4 Vector4::SmoothStep(const Vector4& v1, const Vector4& v2, float t) noexcept { using namespace DirectX; - t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 - t = t * t*(3.f - 2.f*t); + t = (t > 1.0f) ? 1.0f : ((t < 0.0f) ? 0.0f : t); // Clamp value to 0 to 1 + t = t * t * (3.f - 2.f * t); const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); - const XMVECTOR X = XMVectorLerp(x1, x2, t); + const XMVECTOR X = XMVectorLerp(x1, x2, t); Vector4 result; XMStoreFloat4(&result, X); @@ -1280,7 +1274,7 @@ inline void Vector4::Barycentric(const Vector4& v1, const Vector4& v2, const Vec const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); const XMVECTOR x3 = XMLoadFloat4(&v3); - const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); + const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); XMStoreFloat4(&result, X); } @@ -1290,21 +1284,22 @@ inline Vector4 Vector4::Barycentric(const Vector4& v1, const Vector4& v2, const const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); const XMVECTOR x3 = XMLoadFloat4(&v3); - const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); + const XMVECTOR X = XMVectorBaryCentric(x1, x2, x3, f, g); Vector4 result; XMStoreFloat4(&result, X); return result; } -inline void Vector4::CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t, Vector4& result) noexcept +inline void +Vector4::CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t, Vector4& result) noexcept { using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(&v1); const XMVECTOR x2 = XMLoadFloat4(&v2); const XMVECTOR x3 = XMLoadFloat4(&v3); const XMVECTOR x4 = XMLoadFloat4(&v4); - const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); XMStoreFloat4(&result, X); } @@ -1315,7 +1310,7 @@ inline Vector4 Vector4::CatmullRom(const Vector4& v1, const Vector4& v2, const V const XMVECTOR x2 = XMLoadFloat4(&v2); const XMVECTOR x3 = XMLoadFloat4(&v3); const XMVECTOR x4 = XMLoadFloat4(&v4); - const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorCatmullRom(x1, x2, x3, x4, t); Vector4 result; XMStoreFloat4(&result, X); @@ -1329,7 +1324,7 @@ inline void Vector4::Hermite(const Vector4& v1, const Vector4& t1, const Vector4 const XMVECTOR x2 = XMLoadFloat4(&t1); const XMVECTOR x3 = XMLoadFloat4(&v2); const XMVECTOR x4 = XMLoadFloat4(&t2); - const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); XMStoreFloat4(&result, X); } @@ -1340,7 +1335,7 @@ inline Vector4 Vector4::Hermite(const Vector4& v1, const Vector4& t1, const Vect const XMVECTOR x2 = XMLoadFloat4(&t1); const XMVECTOR x3 = XMLoadFloat4(&v2); const XMVECTOR x4 = XMLoadFloat4(&t2); - const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); + const XMVECTOR X = XMVectorHermite(x1, x2, x3, x4, t); Vector4 result; XMStoreFloat4(&result, X); @@ -1393,9 +1388,9 @@ inline void Vector4::Transform(const Vector2& v, const Quaternion& quat, Vector4 { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - XMVECTOR X = XMVector3Rotate(v1, q); - X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f + const XMVECTOR q = XMLoadFloat4(&quat); + XMVECTOR X = XMVector3Rotate(v1, q); + X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f XMStoreFloat4(&result, X); } @@ -1403,9 +1398,9 @@ inline Vector4 Vector4::Transform(const Vector2& v, const Quaternion& quat) noex { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat2(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - XMVECTOR X = XMVector3Rotate(v1, q); - X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f + const XMVECTOR q = XMLoadFloat4(&quat); + XMVECTOR X = XMVector3Rotate(v1, q); + X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f Vector4 result; XMStoreFloat4(&result, X); @@ -1416,9 +1411,9 @@ inline void Vector4::Transform(const Vector3& v, const Quaternion& quat, Vector4 { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - XMVECTOR X = XMVector3Rotate(v1, q); - X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f + const XMVECTOR q = XMLoadFloat4(&quat); + XMVECTOR X = XMVector3Rotate(v1, q); + X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f XMStoreFloat4(&result, X); } @@ -1426,9 +1421,9 @@ inline Vector4 Vector4::Transform(const Vector3& v, const Quaternion& quat) noex { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat3(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - XMVECTOR X = XMVector3Rotate(v1, q); - X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f + const XMVECTOR q = XMLoadFloat4(&quat); + XMVECTOR X = XMVector3Rotate(v1, q); + X = XMVectorSelect(g_XMIdentityR3, X, g_XMSelect1110); // result.w = 1.f Vector4 result; XMStoreFloat4(&result, X); @@ -1439,9 +1434,9 @@ inline void Vector4::Transform(const Vector4& v, const Quaternion& quat, Vector4 { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - XMVECTOR X = XMVector3Rotate(v1, q); - X = XMVectorSelect(v1, X, g_XMSelect1110); // result.w = v.w + const XMVECTOR q = XMLoadFloat4(&quat); + XMVECTOR X = XMVector3Rotate(v1, q); + X = XMVectorSelect(v1, X, g_XMSelect1110); // result.w = v.w XMStoreFloat4(&result, X); } @@ -1449,9 +1444,9 @@ inline Vector4 Vector4::Transform(const Vector4& v, const Quaternion& quat) noex { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&v); - const XMVECTOR q = XMLoadFloat4(&quat); - XMVECTOR X = XMVector3Rotate(v1, q); - X = XMVectorSelect(v1, X, g_XMSelect1110); // result.w = v.w + const XMVECTOR q = XMLoadFloat4(&quat); + XMVECTOR X = XMVector3Rotate(v1, q); + X = XMVectorSelect(v1, X, g_XMSelect1110); // result.w = v.w Vector4 result; XMStoreFloat4(&result, X); @@ -1462,8 +1457,8 @@ inline void Vector4::Transform(const Vector4& v, const Matrix& m, Vector4& resul { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector4Transform(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector4Transform(v1, M); XMStoreFloat4(&result, X); } @@ -1471,23 +1466,21 @@ inline Vector4 Vector4::Transform(const Vector4& v, const Matrix& m) noexcept { using namespace DirectX; const XMVECTOR v1 = XMLoadFloat4(&v); - const XMMATRIX M = XMLoadFloat4x4(&m); - const XMVECTOR X = XMVector4Transform(v1, M); + const XMMATRIX M = XMLoadFloat4x4(&m); + const XMVECTOR X = XMVector4Transform(v1, M); Vector4 result; XMStoreFloat4(&result, X); return result; } -_Use_decl_annotations_ -inline void Vector4::Transform(const Vector4* varray, size_t count, const Matrix& m, Vector4* resultArray) noexcept +_Use_decl_annotations_ inline void Vector4::Transform(const Vector4* varray, size_t count, const Matrix& m, Vector4* resultArray) noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(&m); XMVector4TransformStream(resultArray, sizeof(XMFLOAT4), varray, sizeof(XMFLOAT4), count, M); } - /**************************************************************************** * * Matrix @@ -1498,7 +1491,7 @@ inline void Vector4::Transform(const Vector4* varray, size_t count, const Matrix // Comparision operators //------------------------------------------------------------------------------ -inline bool Matrix::operator == (const Matrix& M) const noexcept +inline bool Matrix::operator==(const Matrix& M) const noexcept { using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&_11)); @@ -1511,13 +1504,10 @@ inline bool Matrix::operator == (const Matrix& M) const noexcept const XMVECTOR y3 = XMLoadFloat4(reinterpret_cast(&M._31)); const XMVECTOR y4 = XMLoadFloat4(reinterpret_cast(&M._41)); - return (XMVector4Equal(x1, y1) - && XMVector4Equal(x2, y2) - && XMVector4Equal(x3, y3) - && XMVector4Equal(x4, y4)) != 0; + return (XMVector4Equal(x1, y1) && XMVector4Equal(x2, y2) && XMVector4Equal(x3, y3) && XMVector4Equal(x4, y4)) != 0; } -inline bool Matrix::operator != (const Matrix& M) const noexcept +inline bool Matrix::operator!=(const Matrix& M) const noexcept { using namespace DirectX; const XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&_11)); @@ -1530,10 +1520,7 @@ inline bool Matrix::operator != (const Matrix& M) const noexcept const XMVECTOR y3 = XMLoadFloat4(reinterpret_cast(&M._31)); const XMVECTOR y4 = XMLoadFloat4(reinterpret_cast(&M._41)); - return (XMVector4NotEqual(x1, y1) - || XMVector4NotEqual(x2, y2) - || XMVector4NotEqual(x3, y3) - || XMVector4NotEqual(x4, y4)) != 0; + return (XMVector4NotEqual(x1, y1) || XMVector4NotEqual(x2, y2) || XMVector4NotEqual(x3, y3) || XMVector4NotEqual(x4, y4)) != 0; } //------------------------------------------------------------------------------ @@ -1542,39 +1529,87 @@ inline bool Matrix::operator != (const Matrix& M) const noexcept inline Matrix::Matrix(const XMFLOAT3X3& M) noexcept { - _11 = M._11; _12 = M._12; _13 = M._13; _14 = 0.f; - _21 = M._21; _22 = M._22; _23 = M._23; _24 = 0.f; - _31 = M._31; _32 = M._32; _33 = M._33; _34 = 0.f; - _41 = 0.f; _42 = 0.f; _43 = 0.f; _44 = 1.f; + _11 = M._11; + _12 = M._12; + _13 = M._13; + _14 = 0.f; + _21 = M._21; + _22 = M._22; + _23 = M._23; + _24 = 0.f; + _31 = M._31; + _32 = M._32; + _33 = M._33; + _34 = 0.f; + _41 = 0.f; + _42 = 0.f; + _43 = 0.f; + _44 = 1.f; } inline Matrix::Matrix(const XMFLOAT4X3& M) noexcept { - _11 = M._11; _12 = M._12; _13 = M._13; _14 = 0.f; - _21 = M._21; _22 = M._22; _23 = M._23; _24 = 0.f; - _31 = M._31; _32 = M._32; _33 = M._33; _34 = 0.f; - _41 = M._41; _42 = M._42; _43 = M._43; _44 = 1.f; -} - -inline Matrix& Matrix::operator= (const XMFLOAT3X3& M) noexcept -{ - _11 = M._11; _12 = M._12; _13 = M._13; _14 = 0.f; - _21 = M._21; _22 = M._22; _23 = M._23; _24 = 0.f; - _31 = M._31; _32 = M._32; _33 = M._33; _34 = 0.f; - _41 = 0.f; _42 = 0.f; _43 = 0.f; _44 = 1.f; + _11 = M._11; + _12 = M._12; + _13 = M._13; + _14 = 0.f; + _21 = M._21; + _22 = M._22; + _23 = M._23; + _24 = 0.f; + _31 = M._31; + _32 = M._32; + _33 = M._33; + _34 = 0.f; + _41 = M._41; + _42 = M._42; + _43 = M._43; + _44 = 1.f; +} + +inline Matrix& Matrix::operator=(const XMFLOAT3X3& M) noexcept +{ + _11 = M._11; + _12 = M._12; + _13 = M._13; + _14 = 0.f; + _21 = M._21; + _22 = M._22; + _23 = M._23; + _24 = 0.f; + _31 = M._31; + _32 = M._32; + _33 = M._33; + _34 = 0.f; + _41 = 0.f; + _42 = 0.f; + _43 = 0.f; + _44 = 1.f; return *this; } -inline Matrix& Matrix::operator= (const XMFLOAT4X3& M) noexcept -{ - _11 = M._11; _12 = M._12; _13 = M._13; _14 = 0.f; - _21 = M._21; _22 = M._22; _23 = M._23; _24 = 0.f; - _31 = M._31; _32 = M._32; _33 = M._33; _34 = 0.f; - _41 = M._41; _42 = M._42; _43 = M._43; _44 = 1.f; +inline Matrix& Matrix::operator=(const XMFLOAT4X3& M) noexcept +{ + _11 = M._11; + _12 = M._12; + _13 = M._13; + _14 = 0.f; + _21 = M._21; + _22 = M._22; + _23 = M._23; + _24 = 0.f; + _31 = M._31; + _32 = M._32; + _33 = M._33; + _34 = 0.f; + _41 = M._41; + _42 = M._42; + _43 = M._43; + _44 = 1.f; return *this; } -inline Matrix& Matrix::operator+= (const Matrix& M) noexcept +inline Matrix& Matrix::operator+=(const Matrix& M) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&_11)); @@ -1599,7 +1634,7 @@ inline Matrix& Matrix::operator+= (const Matrix& M) noexcept return *this; } -inline Matrix& Matrix::operator-= (const Matrix& M) noexcept +inline Matrix& Matrix::operator-=(const Matrix& M) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&_11)); @@ -1624,17 +1659,17 @@ inline Matrix& Matrix::operator-= (const Matrix& M) noexcept return *this; } -inline Matrix& Matrix::operator*= (const Matrix& M) noexcept +inline Matrix& Matrix::operator*=(const Matrix& M) noexcept { using namespace DirectX; const XMMATRIX M1 = XMLoadFloat4x4(this); const XMMATRIX M2 = XMLoadFloat4x4(&M); - const XMMATRIX X = XMMatrixMultiply(M1, M2); + const XMMATRIX X = XMMatrixMultiply(M1, M2); XMStoreFloat4x4(this, X); return *this; } -inline Matrix& Matrix::operator*= (float S) noexcept +inline Matrix& Matrix::operator*=(float S) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&_11)); @@ -1654,7 +1689,7 @@ inline Matrix& Matrix::operator*= (float S) noexcept return *this; } -inline Matrix& Matrix::operator/= (float S) noexcept +inline Matrix& Matrix::operator/=(float S) noexcept { using namespace DirectX; assert(S != 0.f); @@ -1677,7 +1712,7 @@ inline Matrix& Matrix::operator/= (float S) noexcept return *this; } -inline Matrix& Matrix::operator/= (const Matrix& M) noexcept +inline Matrix& Matrix::operator/=(const Matrix& M) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&_11)); @@ -1706,7 +1741,7 @@ inline Matrix& Matrix::operator/= (const Matrix& M) noexcept // Urnary operators //------------------------------------------------------------------------------ -inline Matrix Matrix::operator- () const noexcept +inline Matrix Matrix::operator-() const noexcept { using namespace DirectX; XMVECTOR v1 = XMLoadFloat4(reinterpret_cast(&_11)); @@ -1731,7 +1766,7 @@ inline Matrix Matrix::operator- () const noexcept // Binary operators //------------------------------------------------------------------------------ -inline Matrix operator+ (const Matrix& M1, const Matrix& M2) noexcept +inline Matrix operator+(const Matrix& M1, const Matrix& M2) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&M1._11)); @@ -1757,7 +1792,7 @@ inline Matrix operator+ (const Matrix& M1, const Matrix& M2) noexcept return R; } -inline Matrix operator- (const Matrix& M1, const Matrix& M2) noexcept +inline Matrix operator-(const Matrix& M1, const Matrix& M2) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&M1._11)); @@ -1783,19 +1818,19 @@ inline Matrix operator- (const Matrix& M1, const Matrix& M2) noexcept return R; } -inline Matrix operator* (const Matrix& M1, const Matrix& M2) noexcept +inline Matrix operator*(const Matrix& M1, const Matrix& M2) noexcept { using namespace DirectX; const XMMATRIX m1 = XMLoadFloat4x4(&M1); const XMMATRIX m2 = XMLoadFloat4x4(&M2); - const XMMATRIX X = XMMatrixMultiply(m1, m2); + const XMMATRIX X = XMMatrixMultiply(m1, m2); Matrix R; XMStoreFloat4x4(&R, X); return R; } -inline Matrix operator* (const Matrix& M, float S) noexcept +inline Matrix operator*(const Matrix& M, float S) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&M._11)); @@ -1816,7 +1851,7 @@ inline Matrix operator* (const Matrix& M, float S) noexcept return R; } -inline Matrix operator* (float S, const Matrix& M) noexcept +inline Matrix operator*(float S, const Matrix& M) noexcept { using namespace DirectX; @@ -1838,7 +1873,7 @@ inline Matrix operator* (float S, const Matrix& M) noexcept return R; } -inline Matrix operator/ (const Matrix& M, float S) noexcept +inline Matrix operator/(const Matrix& M, float S) noexcept { using namespace DirectX; assert(S != 0.f); @@ -1863,7 +1898,7 @@ inline Matrix operator/ (const Matrix& M, float S) noexcept return R; } -inline Matrix operator/ (const Matrix& M1, const Matrix& M2) noexcept +inline Matrix operator/(const Matrix& M1, const Matrix& M2) noexcept { using namespace DirectX; XMVECTOR x1 = XMLoadFloat4(reinterpret_cast(&M1._11)); @@ -1889,7 +1924,7 @@ inline Matrix operator/ (const Matrix& M1, const Matrix& M2) noexcept return R; } -inline Matrix operator/ (float S, const Matrix& M) noexcept +inline Matrix operator/(float S, const Matrix& M) noexcept { using namespace DirectX; @@ -1937,7 +1972,7 @@ inline Matrix Matrix::Transpose() const noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(this); - Matrix R; + Matrix R; XMStoreFloat4x4(&R, XMMatrixTranspose(M)); return R; } @@ -1953,8 +1988,8 @@ inline Matrix Matrix::Invert() const noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(this); - Matrix R; - XMVECTOR det; + Matrix R; + XMVECTOR det; XMStoreFloat4x4(&R, XMMatrixInverse(&det, M)); return R; } @@ -1963,7 +1998,7 @@ inline void Matrix::Invert(Matrix& result) const noexcept { using namespace DirectX; const XMMATRIX M = XMLoadFloat4x4(this); - XMVECTOR det; + XMVECTOR det; XMStoreFloat4x4(&result, XMMatrixInverse(&det, M)); } @@ -1992,17 +2027,15 @@ inline Vector3 Matrix::ToEuler() const noexcept // Static functions //------------------------------------------------------------------------------ -_Use_decl_annotations_ -inline Matrix Matrix::CreateBillboard( - const Vector3& object, - const Vector3& cameraPosition, - const Vector3& cameraUp, - const Vector3* cameraForward) noexcept +_Use_decl_annotations_ inline Matrix Matrix::CreateBillboard(const Vector3& object, + const Vector3& cameraPosition, + const Vector3& cameraUp, + const Vector3* cameraForward) noexcept { using namespace DirectX; const XMVECTOR O = XMLoadFloat3(&object); const XMVECTOR C = XMLoadFloat3(&cameraPosition); - XMVECTOR Z = XMVectorSubtract(O, C); + XMVECTOR Z = XMVectorSubtract(O, C); const XMVECTOR N = XMVector3LengthSq(Z); if (XMVector3Less(N, g_XMEpsilon)) @@ -2010,7 +2043,7 @@ inline Matrix Matrix::CreateBillboard( if (cameraForward) { const XMVECTOR F = XMLoadFloat3(cameraForward); - Z = XMVectorNegate(F); + Z = XMVectorNegate(F); } else Z = g_XMNegIdentityR2; @@ -2021,8 +2054,8 @@ inline Matrix Matrix::CreateBillboard( } const XMVECTOR up = XMLoadFloat3(&cameraUp); - XMVECTOR X = XMVector3Cross(up, Z); - X = XMVector3Normalize(X); + XMVECTOR X = XMVector3Cross(up, Z); + X = XMVector3Normalize(X); const XMVECTOR Y = XMVector3Cross(Z, X); @@ -2037,21 +2070,20 @@ inline Matrix Matrix::CreateBillboard( return R; } -_Use_decl_annotations_ -inline Matrix Matrix::CreateConstrainedBillboard( - const Vector3& object, - const Vector3& cameraPosition, - const Vector3& rotateAxis, - const Vector3* cameraForward, - const Vector3* objectForward) noexcept +_Use_decl_annotations_ inline Matrix Matrix::CreateConstrainedBillboard(const Vector3& object, + const Vector3& cameraPosition, + const Vector3& rotateAxis, + const Vector3* cameraForward, + const Vector3* objectForward) noexcept { using namespace DirectX; - static const XMVECTORF32 s_minAngle = { { { 0.99825467075f, 0.99825467075f, 0.99825467075f, 0.99825467075f } } }; // 1.0 - XMConvertToRadians( 0.1f ); + static const XMVECTORF32 s_minAngle + = { { { 0.99825467075f, 0.99825467075f, 0.99825467075f, 0.99825467075f } } }; // 1.0 - XMConvertToRadians( 0.1f ); - const XMVECTOR O = XMLoadFloat3(&object); - const XMVECTOR C = XMLoadFloat3(&cameraPosition); - XMVECTOR faceDir = XMVectorSubtract(O, C); + const XMVECTOR O = XMLoadFloat3(&object); + const XMVECTOR C = XMLoadFloat3(&cameraPosition); + XMVECTOR faceDir = XMVectorSubtract(O, C); const XMVECTOR N = XMVector3LengthSq(faceDir); if (XMVector3Less(N, g_XMEpsilon)) @@ -2059,7 +2091,7 @@ inline Matrix Matrix::CreateConstrainedBillboard( if (cameraForward) { const XMVECTOR F = XMLoadFloat3(cameraForward); - faceDir = XMVectorNegate(F); + faceDir = XMVectorNegate(F); } else faceDir = g_XMNegIdentityR2; @@ -2070,25 +2102,25 @@ inline Matrix Matrix::CreateConstrainedBillboard( } const XMVECTOR Y = XMLoadFloat3(&rotateAxis); - XMVECTOR X, Z; + XMVECTOR X, Z; XMVECTOR dot = XMVectorAbs(XMVector3Dot(Y, faceDir)); if (XMVector3Greater(dot, s_minAngle)) { if (objectForward) { - Z = XMLoadFloat3(objectForward); + Z = XMLoadFloat3(objectForward); dot = XMVectorAbs(XMVector3Dot(Y, Z)); if (XMVector3Greater(dot, s_minAngle)) { dot = XMVectorAbs(XMVector3Dot(Y, g_XMNegIdentityR2)); - Z = (XMVector3Greater(dot, s_minAngle)) ? g_XMIdentityR0 : g_XMNegIdentityR2; + Z = (XMVector3Greater(dot, s_minAngle)) ? g_XMIdentityR0 : g_XMNegIdentityR2; } } else { dot = XMVectorAbs(XMVector3Dot(Y, g_XMNegIdentityR2)); - Z = (XMVector3Greater(dot, s_minAngle)) ? g_XMIdentityR0 : g_XMNegIdentityR2; + Z = (XMVector3Greater(dot, s_minAngle)) ? g_XMIdentityR0 : g_XMNegIdentityR2; } X = XMVector3Cross(Y, Z); @@ -2184,7 +2216,7 @@ inline Matrix Matrix::CreateRotationZ(float radians) noexcept inline Matrix Matrix::CreateFromAxisAngle(const Vector3& axis, float angle) noexcept { using namespace DirectX; - Matrix R; + Matrix R; const XMVECTOR a = XMLoadFloat3(&axis); XMStoreFloat4x4(&R, XMMatrixRotationAxis(a, angle)); return R; @@ -2222,7 +2254,8 @@ inline Matrix Matrix::CreateOrthographic(float width, float height, float zNearP return R; } -inline Matrix Matrix::CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane) noexcept +inline Matrix +Matrix::CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane) noexcept { using namespace DirectX; Matrix R; @@ -2233,10 +2266,10 @@ inline Matrix Matrix::CreateOrthographicOffCenter(float left, float right, float inline Matrix Matrix::CreateLookAt(const Vector3& eye, const Vector3& target, const Vector3& up) noexcept { using namespace DirectX; - Matrix R; - const XMVECTOR eyev = XMLoadFloat3(&eye); + Matrix R; + const XMVECTOR eyev = XMLoadFloat3(&eye); const XMVECTOR targetv = XMLoadFloat3(&target); - const XMVECTOR upv = XMLoadFloat3(&up); + const XMVECTOR upv = XMLoadFloat3(&up); XMStoreFloat4x4(&R, XMMatrixLookAtRH(eyev, targetv, upv)); return R; } @@ -2245,17 +2278,19 @@ inline Matrix Matrix::CreateWorld(const Vector3& position, const Vector3& forwar { using namespace DirectX; const XMVECTOR zaxis = XMVector3Normalize(XMVectorNegate(XMLoadFloat3(&forward))); - XMVECTOR yaxis = XMLoadFloat3(&up); + XMVECTOR yaxis = XMLoadFloat3(&up); const XMVECTOR xaxis = XMVector3Normalize(XMVector3Cross(yaxis, zaxis)); - yaxis = XMVector3Cross(zaxis, xaxis); + yaxis = XMVector3Cross(zaxis, xaxis); Matrix R; XMStoreFloat3(reinterpret_cast(&R._11), xaxis); XMStoreFloat3(reinterpret_cast(&R._21), yaxis); XMStoreFloat3(reinterpret_cast(&R._31), zaxis); R._14 = R._24 = R._34 = 0.f; - R._41 = position.x; R._42 = position.y; R._43 = position.z; - R._44 = 1.f; + R._41 = position.x; + R._42 = position.y; + R._43 = position.z; + R._44 = 1.f; return R; } @@ -2263,7 +2298,7 @@ inline Matrix Matrix::CreateFromQuaternion(const Quaternion& rotation) noexcept { using namespace DirectX; const XMVECTOR quatv = XMLoadFloat4(&rotation); - Matrix R; + Matrix R; XMStoreFloat4x4(&R, XMMatrixRotationQuaternion(quatv)); return R; } @@ -2287,9 +2322,9 @@ inline Matrix Matrix::CreateFromYawPitchRoll(const Vector3& angles) noexcept inline Matrix Matrix::CreateShadow(const Vector3& lightDir, const Plane& plane) noexcept { using namespace DirectX; - const XMVECTOR light = XMLoadFloat3(&lightDir); + const XMVECTOR light = XMLoadFloat3(&lightDir); const XMVECTOR planev = XMLoadFloat4(&plane); - Matrix R; + Matrix R; XMStoreFloat4x4(&R, XMMatrixShadow(planev, light)); return R; } @@ -2298,7 +2333,7 @@ inline Matrix Matrix::CreateReflection(const Plane& plane) noexcept { using namespace DirectX; const XMVECTOR planev = XMLoadFloat4(&plane); - Matrix R; + Matrix R; XMStoreFloat4x4(&R, XMMatrixReflect(planev)); return R; } @@ -2377,7 +2412,6 @@ inline Matrix Matrix::Transform(const Matrix& M, const Quaternion& rotation) noe return result; } - /**************************************************************************** * * Plane @@ -2405,7 +2439,7 @@ inline Plane::Plane(const Vector3& point, const Vector3& normal) noexcept // Comparision operators //------------------------------------------------------------------------------ -inline bool Plane::operator == (const Plane& p) const noexcept +inline bool Plane::operator==(const Plane& p) const noexcept { using namespace DirectX; const XMVECTOR p1 = XMLoadFloat4(this); @@ -2413,7 +2447,7 @@ inline bool Plane::operator == (const Plane& p) const noexcept return XMPlaneEqual(p1, p2); } -inline bool Plane::operator != (const Plane& p) const noexcept +inline bool Plane::operator!=(const Plane& p) const noexcept { using namespace DirectX; const XMVECTOR p1 = XMLoadFloat4(this); @@ -2442,7 +2476,7 @@ inline void Plane::Normalize(Plane& result) const noexcept inline float Plane::Dot(const Vector4& v) const noexcept { using namespace DirectX; - const XMVECTOR p = XMLoadFloat4(this); + const XMVECTOR p = XMLoadFloat4(this); const XMVECTOR v0 = XMLoadFloat4(&v); return XMVectorGetX(XMPlaneDot(p, v0)); } @@ -2450,7 +2484,7 @@ inline float Plane::Dot(const Vector4& v) const noexcept inline float Plane::DotCoordinate(const Vector3& position) const noexcept { using namespace DirectX; - const XMVECTOR p = XMLoadFloat4(this); + const XMVECTOR p = XMLoadFloat4(this); const XMVECTOR v0 = XMLoadFloat3(&position); return XMVectorGetX(XMPlaneDotCoord(p, v0)); } @@ -2458,7 +2492,7 @@ inline float Plane::DotCoordinate(const Vector3& position) const noexcept inline float Plane::DotNormal(const Vector3& normal) const noexcept { using namespace DirectX; - const XMVECTOR p = XMLoadFloat4(this); + const XMVECTOR p = XMLoadFloat4(this); const XMVECTOR n0 = XMLoadFloat3(&normal); return XMVectorGetX(XMPlaneDotNormal(p, n0)); } @@ -2470,7 +2504,7 @@ inline float Plane::DotNormal(const Vector3& normal) const noexcept inline void Plane::Transform(const Plane& plane, const Matrix& M, Plane& result) noexcept { using namespace DirectX; - const XMVECTOR p = XMLoadFloat4(&plane); + const XMVECTOR p = XMLoadFloat4(&plane); const XMMATRIX m0 = XMLoadFloat4x4(&M); XMStoreFloat4(&result, XMPlaneTransform(p, m0)); } @@ -2478,7 +2512,7 @@ inline void Plane::Transform(const Plane& plane, const Matrix& M, Plane& result) inline Plane Plane::Transform(const Plane& plane, const Matrix& M) noexcept { using namespace DirectX; - const XMVECTOR p = XMLoadFloat4(&plane); + const XMVECTOR p = XMLoadFloat4(&plane); const XMMATRIX m0 = XMLoadFloat4x4(&M); Plane result; @@ -2491,8 +2525,8 @@ inline void Plane::Transform(const Plane& plane, const Quaternion& rotation, Pla using namespace DirectX; const XMVECTOR p = XMLoadFloat4(&plane); const XMVECTOR q = XMLoadFloat4(&rotation); - XMVECTOR X = XMVector3Rotate(p, q); - X = XMVectorSelect(p, X, g_XMSelect1110); // result.d = plane.d + XMVECTOR X = XMVector3Rotate(p, q); + X = XMVectorSelect(p, X, g_XMSelect1110); // result.d = plane.d XMStoreFloat4(&result, X); } @@ -2501,15 +2535,14 @@ inline Plane Plane::Transform(const Plane& plane, const Quaternion& rotation) no using namespace DirectX; const XMVECTOR p = XMLoadFloat4(&plane); const XMVECTOR q = XMLoadFloat4(&rotation); - XMVECTOR X = XMVector3Rotate(p, q); - X = XMVectorSelect(p, X, g_XMSelect1110); // result.d = plane.d + XMVECTOR X = XMVector3Rotate(p, q); + X = XMVectorSelect(p, X, g_XMSelect1110); // result.d = plane.d Plane result; XMStoreFloat4(&result, X); return result; } - /**************************************************************************** * * Quaternion @@ -2520,7 +2553,7 @@ inline Plane Plane::Transform(const Plane& plane, const Quaternion& rotation) no // Comparision operators //------------------------------------------------------------------------------ -inline bool Quaternion::operator == (const Quaternion& q) const noexcept +inline bool Quaternion::operator==(const Quaternion& q) const noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(this); @@ -2528,7 +2561,7 @@ inline bool Quaternion::operator == (const Quaternion& q) const noexcept return XMQuaternionEqual(q1, q2); } -inline bool Quaternion::operator != (const Quaternion& q) const noexcept +inline bool Quaternion::operator!=(const Quaternion& q) const noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(this); @@ -2540,7 +2573,7 @@ inline bool Quaternion::operator != (const Quaternion& q) const noexcept // Assignment operators //------------------------------------------------------------------------------ -inline Quaternion& Quaternion::operator+= (const Quaternion& q) noexcept +inline Quaternion& Quaternion::operator+=(const Quaternion& q) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(this); @@ -2549,7 +2582,7 @@ inline Quaternion& Quaternion::operator+= (const Quaternion& q) noexcept return *this; } -inline Quaternion& Quaternion::operator-= (const Quaternion& q) noexcept +inline Quaternion& Quaternion::operator-=(const Quaternion& q) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(this); @@ -2558,7 +2591,7 @@ inline Quaternion& Quaternion::operator-= (const Quaternion& q) noexcept return *this; } -inline Quaternion& Quaternion::operator*= (const Quaternion& q) noexcept +inline Quaternion& Quaternion::operator*=(const Quaternion& q) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(this); @@ -2567,7 +2600,7 @@ inline Quaternion& Quaternion::operator*= (const Quaternion& q) noexcept return *this; } -inline Quaternion& Quaternion::operator*= (float S) noexcept +inline Quaternion& Quaternion::operator*=(float S) noexcept { using namespace DirectX; const XMVECTOR q = XMLoadFloat4(this); @@ -2575,12 +2608,12 @@ inline Quaternion& Quaternion::operator*= (float S) noexcept return *this; } -inline Quaternion& Quaternion::operator/= (const Quaternion& q) noexcept +inline Quaternion& Quaternion::operator/=(const Quaternion& q) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(this); - XMVECTOR q2 = XMLoadFloat4(&q); - q2 = XMQuaternionInverse(q2); + XMVECTOR q2 = XMLoadFloat4(&q); + q2 = XMQuaternionInverse(q2); XMStoreFloat4(this, XMQuaternionMultiply(q1, q2)); return *this; } @@ -2589,7 +2622,7 @@ inline Quaternion& Quaternion::operator/= (const Quaternion& q) noexcept // Binary operators //------------------------------------------------------------------------------ -inline Quaternion operator+ (const Quaternion& Q1, const Quaternion& Q2) noexcept +inline Quaternion operator+(const Quaternion& Q1, const Quaternion& Q2) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(&Q1); @@ -2600,7 +2633,7 @@ inline Quaternion operator+ (const Quaternion& Q1, const Quaternion& Q2) noexcep return R; } -inline Quaternion operator- (const Quaternion& Q1, const Quaternion& Q2) noexcept +inline Quaternion operator-(const Quaternion& Q1, const Quaternion& Q2) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(&Q1); @@ -2611,7 +2644,7 @@ inline Quaternion operator- (const Quaternion& Q1, const Quaternion& Q2) noexcep return R; } -inline Quaternion operator* (const Quaternion& Q1, const Quaternion& Q2) noexcept +inline Quaternion operator*(const Quaternion& Q1, const Quaternion& Q2) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(&Q1); @@ -2622,7 +2655,7 @@ inline Quaternion operator* (const Quaternion& Q1, const Quaternion& Q2) noexcep return R; } -inline Quaternion operator* (const Quaternion& Q, float S) noexcept +inline Quaternion operator*(const Quaternion& Q, float S) noexcept { using namespace DirectX; const XMVECTOR q = XMLoadFloat4(&Q); @@ -2632,7 +2665,7 @@ inline Quaternion operator* (const Quaternion& Q, float S) noexcept return R; } -inline Quaternion operator* (float S, const Quaternion& Q) noexcept +inline Quaternion operator*(float S, const Quaternion& Q) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(&Q); @@ -2642,12 +2675,12 @@ inline Quaternion operator* (float S, const Quaternion& Q) noexcept return R; } -inline Quaternion operator/ (const Quaternion& Q1, const Quaternion& Q2) noexcept +inline Quaternion operator/(const Quaternion& Q1, const Quaternion& Q2) noexcept { using namespace DirectX; const XMVECTOR q1 = XMLoadFloat4(&Q1); - XMVECTOR q2 = XMLoadFloat4(&Q2); - q2 = XMQuaternionInverse(q2); + XMVECTOR q2 = XMLoadFloat4(&Q2); + q2 = XMQuaternionInverse(q2); Quaternion R; XMStoreFloat4(&R, XMQuaternionMultiply(q1, q2)); @@ -2803,11 +2836,11 @@ inline void Quaternion::Lerp(const Quaternion& q1, const Quaternion& q2, float t } else { - const XMVECTOR tv = XMVectorReplicate(t); + const XMVECTOR tv = XMVectorReplicate(t); const XMVECTOR t1v = XMVectorReplicate(1.f - t); - const XMVECTOR X0 = XMVectorMultiply(Q0, t1v); - const XMVECTOR X1 = XMVectorMultiply(Q1, tv); - R = XMVectorSubtract(X0, X1); + const XMVECTOR X0 = XMVectorMultiply(Q0, t1v); + const XMVECTOR X1 = XMVectorMultiply(Q1, tv); + R = XMVectorSubtract(X0, X1); } XMStoreFloat4(&result, XMQuaternionNormalize(R)); @@ -2828,11 +2861,11 @@ inline Quaternion Quaternion::Lerp(const Quaternion& q1, const Quaternion& q2, f } else { - const XMVECTOR tv = XMVectorReplicate(t); + const XMVECTOR tv = XMVectorReplicate(t); const XMVECTOR t1v = XMVectorReplicate(1.f - t); - const XMVECTOR X0 = XMVectorMultiply(Q0, t1v); - const XMVECTOR X1 = XMVectorMultiply(Q1, tv); - R = XMVectorSubtract(X0, X1); + const XMVECTOR X0 = XMVectorMultiply(Q0, t1v); + const XMVECTOR X1 = XMVectorMultiply(Q1, tv); + R = XMVectorSubtract(X0, X1); } Quaternion result; @@ -2902,11 +2935,10 @@ inline float Quaternion::Angle(const Quaternion& q1, const Quaternion& q2) noexc XMVECTOR R = XMQuaternionMultiply(XMQuaternionConjugate(Q0), Q1); const float rs = XMVectorGetW(R); - R = XMVector3Length(R); + R = XMVector3Length(R); return 2.f * atan2f(XMVectorGetX(R), rs); } - /**************************************************************************** * * Color @@ -2928,7 +2960,7 @@ inline Color::Color(const DirectX::PackedVector::XMUBYTEN4& Packed) noexcept //------------------------------------------------------------------------------ // Comparision operators //------------------------------------------------------------------------------ -inline bool Color::operator == (const Color& c) const noexcept +inline bool Color::operator==(const Color& c) const noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(this); @@ -2936,7 +2968,7 @@ inline bool Color::operator == (const Color& c) const noexcept return XMColorEqual(c1, c2); } -inline bool Color::operator != (const Color& c) const noexcept +inline bool Color::operator!=(const Color& c) const noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(this); @@ -2948,21 +2980,21 @@ inline bool Color::operator != (const Color& c) const noexcept // Assignment operators //------------------------------------------------------------------------------ -inline Color& Color::operator= (const DirectX::PackedVector::XMCOLOR& Packed) noexcept +inline Color& Color::operator=(const DirectX::PackedVector::XMCOLOR& Packed) noexcept { using namespace DirectX; XMStoreFloat4(this, PackedVector::XMLoadColor(&Packed)); return *this; } -inline Color& Color::operator= (const DirectX::PackedVector::XMUBYTEN4& Packed) noexcept +inline Color& Color::operator=(const DirectX::PackedVector::XMUBYTEN4& Packed) noexcept { using namespace DirectX; XMStoreFloat4(this, PackedVector::XMLoadUByteN4(&Packed)); return *this; } -inline Color& Color::operator+= (const Color& c) noexcept +inline Color& Color::operator+=(const Color& c) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(this); @@ -2971,7 +3003,7 @@ inline Color& Color::operator+= (const Color& c) noexcept return *this; } -inline Color& Color::operator-= (const Color& c) noexcept +inline Color& Color::operator-=(const Color& c) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(this); @@ -2980,7 +3012,7 @@ inline Color& Color::operator-= (const Color& c) noexcept return *this; } -inline Color& Color::operator*= (const Color& c) noexcept +inline Color& Color::operator*=(const Color& c) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(this); @@ -2989,7 +3021,7 @@ inline Color& Color::operator*= (const Color& c) noexcept return *this; } -inline Color& Color::operator*= (float S) noexcept +inline Color& Color::operator*=(float S) noexcept { using namespace DirectX; const XMVECTOR c = XMLoadFloat4(this); @@ -2997,7 +3029,7 @@ inline Color& Color::operator*= (float S) noexcept return *this; } -inline Color& Color::operator/= (const Color& c) noexcept +inline Color& Color::operator/=(const Color& c) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(this); @@ -3010,60 +3042,60 @@ inline Color& Color::operator/= (const Color& c) noexcept // Binary operators //------------------------------------------------------------------------------ -inline Color operator+ (const Color& C1, const Color& C2) noexcept +inline Color operator+(const Color& C1, const Color& C2) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(&C1); const XMVECTOR c2 = XMLoadFloat4(&C2); - Color R; + Color R; XMStoreFloat4(&R, XMVectorAdd(c1, c2)); return R; } -inline Color operator- (const Color& C1, const Color& C2) noexcept +inline Color operator-(const Color& C1, const Color& C2) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(&C1); const XMVECTOR c2 = XMLoadFloat4(&C2); - Color R; + Color R; XMStoreFloat4(&R, XMVectorSubtract(c1, c2)); return R; } -inline Color operator* (const Color& C1, const Color& C2) noexcept +inline Color operator*(const Color& C1, const Color& C2) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(&C1); const XMVECTOR c2 = XMLoadFloat4(&C2); - Color R; + Color R; XMStoreFloat4(&R, XMVectorMultiply(c1, c2)); return R; } -inline Color operator* (const Color& C, float S) noexcept +inline Color operator*(const Color& C, float S) noexcept { using namespace DirectX; const XMVECTOR c = XMLoadFloat4(&C); - Color R; + Color R; XMStoreFloat4(&R, XMVectorScale(c, S)); return R; } -inline Color operator* (float S, const Color& C) noexcept +inline Color operator*(float S, const Color& C) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(&C); - Color R; + Color R; XMStoreFloat4(&R, XMVectorScale(c1, S)); return R; } -inline Color operator/ (const Color& C1, const Color& C2) noexcept +inline Color operator/(const Color& C1, const Color& C2) noexcept { using namespace DirectX; const XMVECTOR c1 = XMLoadFloat4(&C1); const XMVECTOR c2 = XMLoadFloat4(&C2); - Color R; + Color R; XMStoreFloat4(&R, XMVectorDivide(c1, c2)); return R; } @@ -3075,7 +3107,7 @@ inline Color operator/ (const Color& C1, const Color& C2) noexcept inline DirectX::PackedVector::XMCOLOR Color::BGRA() const noexcept { using namespace DirectX; - const XMVECTOR clr = XMLoadFloat4(this); + const XMVECTOR clr = XMLoadFloat4(this); PackedVector::XMCOLOR Packed; PackedVector::XMStoreColor(&Packed, clr); return Packed; @@ -3084,7 +3116,7 @@ inline DirectX::PackedVector::XMCOLOR Color::BGRA() const noexcept inline DirectX::PackedVector::XMUBYTEN4 Color::RGBA() const noexcept { using namespace DirectX; - const XMVECTOR clr = XMLoadFloat4(this); + const XMVECTOR clr = XMLoadFloat4(this); PackedVector::XMUBYTEN4 Packed; PackedVector::XMStoreUByteN4(&Packed, clr); return Packed; @@ -3122,8 +3154,8 @@ inline void Color::Premultiply() noexcept { using namespace DirectX; const XMVECTOR c = XMLoadFloat4(this); - XMVECTOR a = XMVectorSplatW(c); - a = XMVectorSelect(g_XMIdentityR3, a, g_XMSelect1110); + XMVECTOR a = XMVectorSplatW(c); + a = XMVectorSelect(g_XMIdentityR3, a, g_XMSelect1110); XMStoreFloat4(this, XMVectorMultiply(c, a)); } @@ -3131,8 +3163,8 @@ inline void Color::Premultiply(Color& result) const noexcept { using namespace DirectX; const XMVECTOR c = XMLoadFloat4(this); - XMVECTOR a = XMVectorSplatW(c); - a = XMVectorSelect(g_XMIdentityR3, a, g_XMSelect1110); + XMVECTOR a = XMVectorSplatW(c); + a = XMVectorSelect(g_XMIdentityR3, a, g_XMSelect1110); XMStoreFloat4(&result, XMVectorMultiply(c, a)); } @@ -3206,7 +3238,6 @@ inline Color Color::Lerp(const Color& c1, const Color& c2, float t) noexcept return result; } - /**************************************************************************** * * Ray @@ -3216,7 +3247,7 @@ inline Color Color::Lerp(const Color& c1, const Color& c2, float t) noexcept //----------------------------------------------------------------------------- // Comparision operators //------------------------------------------------------------------------------ -inline bool Ray::operator == (const Ray& r) const noexcept +inline bool Ray::operator==(const Ray& r) const noexcept { using namespace DirectX; const XMVECTOR r1p = XMLoadFloat3(&position); @@ -3226,7 +3257,7 @@ inline bool Ray::operator == (const Ray& r) const noexcept return XMVector3Equal(r1p, r2p) && XMVector3Equal(r1d, r2d); } -inline bool Ray::operator != (const Ray& r) const noexcept +inline bool Ray::operator!=(const Ray& r) const noexcept { using namespace DirectX; const XMVECTOR r1p = XMLoadFloat3(&position); @@ -3259,7 +3290,7 @@ inline bool Ray::Intersects(const Plane& plane, _Out_ float& Dist) const noexcep { using namespace DirectX; - const XMVECTOR p = XMLoadFloat4(&plane); + const XMVECTOR p = XMLoadFloat4(&plane); const XMVECTOR dir = XMLoadFloat3(&direction); const XMVECTOR nd = XMPlaneDotNormal(p, dir); @@ -3273,10 +3304,10 @@ inline bool Ray::Intersects(const Plane& plane, _Out_ float& Dist) const noexcep { // t = -(dot(n,origin) + D) / dot(n,dir) const XMVECTOR pos = XMLoadFloat3(&position); - XMVECTOR v = XMPlaneDotNormal(p, pos); - v = XMVectorAdd(v, XMVectorSplatW(p)); - v = XMVectorDivide(v, nd); - float dist = -XMVectorGetX(v); + XMVECTOR v = XMPlaneDotNormal(p, pos); + v = XMVectorAdd(v, XMVectorSplatW(p)); + v = XMVectorDivide(v, nd); + float dist = -XMVectorGetX(v); if (dist < 0) { Dist = 0.f; @@ -3290,7 +3321,6 @@ inline bool Ray::Intersects(const Plane& plane, _Out_ float& Dist) const noexcep } } - /**************************************************************************** * * Viewport @@ -3302,18 +3332,14 @@ inline bool Ray::Intersects(const Plane& plane, _Out_ float& Dist) const noexcep //------------------------------------------------------------------------------ #if (__cplusplus < 202002L) -inline bool Viewport::operator == (const Viewport& vp) const noexcept +inline bool Viewport::operator==(const Viewport& vp) const noexcept { - return (x == vp.x && y == vp.y - && width == vp.width && height == vp.height - && minDepth == vp.minDepth && maxDepth == vp.maxDepth); + return (x == vp.x && y == vp.y && width == vp.width && height == vp.height && minDepth == vp.minDepth && maxDepth == vp.maxDepth); } -inline bool Viewport::operator != (const Viewport& vp) const noexcept +inline bool Viewport::operator!=(const Viewport& vp) const noexcept { - return (x != vp.x || y != vp.y - || width != vp.width || height != vp.height - || minDepth != vp.minDepth || maxDepth != vp.maxDepth); + return (x != vp.x || y != vp.y || width != vp.width || height != vp.height || minDepth != vp.minDepth || maxDepth != vp.maxDepth); } #endif @@ -3321,31 +3347,39 @@ inline bool Viewport::operator != (const Viewport& vp) const noexcept // Assignment operators //------------------------------------------------------------------------------ -inline Viewport& Viewport::operator= (const RECT& rct) noexcept +inline Viewport& Viewport::operator=(const RECT& rct) noexcept { - x = float(rct.left); y = float(rct.top); - width = float(rct.right - rct.left); - height = float(rct.bottom - rct.top); - minDepth = 0.f; maxDepth = 1.f; + x = float(rct.left); + y = float(rct.top); + width = float(rct.right - rct.left); + height = float(rct.bottom - rct.top); + minDepth = 0.f; + maxDepth = 1.f; return *this; } #if defined(__d3d11_h__) || defined(__d3d11_x_h__) -inline Viewport& Viewport::operator= (const D3D11_VIEWPORT& vp) noexcept -{ - x = vp.TopLeftX; y = vp.TopLeftY; - width = vp.Width; height = vp.Height; - minDepth = vp.MinDepth; maxDepth = vp.MaxDepth; +inline Viewport& Viewport::operator=(const D3D11_VIEWPORT& vp) noexcept +{ + x = vp.TopLeftX; + y = vp.TopLeftY; + width = vp.Width; + height = vp.Height; + minDepth = vp.MinDepth; + maxDepth = vp.MaxDepth; return *this; } #endif #if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) -inline Viewport& Viewport::operator= (const D3D12_VIEWPORT& vp) noexcept -{ - x = vp.TopLeftX; y = vp.TopLeftY; - width = vp.Width; height = vp.Height; - minDepth = vp.MinDepth; maxDepth = vp.MaxDepth; +inline Viewport& Viewport::operator=(const D3D12_VIEWPORT& vp) noexcept +{ + x = vp.TopLeftX; + y = vp.TopLeftY; + width = vp.Width; + height = vp.Height; + minDepth = vp.MinDepth; + maxDepth = vp.MaxDepth; return *this; } #endif @@ -3365,9 +3399,9 @@ inline float Viewport::AspectRatio() const noexcept inline Vector3 Viewport::Project(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world) const noexcept { using namespace DirectX; - XMVECTOR v = XMLoadFloat3(&p); + XMVECTOR v = XMLoadFloat3(&p); const XMMATRIX projection = XMLoadFloat4x4(&proj); - v = XMVector3Project(v, x, y, width, height, minDepth, maxDepth, projection, view, world); + v = XMVector3Project(v, x, y, width, height, minDepth, maxDepth, projection, view, world); Vector3 result; XMStoreFloat3(&result, v); return result; @@ -3376,28 +3410,29 @@ inline Vector3 Viewport::Project(const Vector3& p, const Matrix& proj, const Mat inline void Viewport::Project(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept { using namespace DirectX; - XMVECTOR v = XMLoadFloat3(&p); + XMVECTOR v = XMLoadFloat3(&p); const XMMATRIX projection = XMLoadFloat4x4(&proj); - v = XMVector3Project(v, x, y, width, height, minDepth, maxDepth, projection, view, world); + v = XMVector3Project(v, x, y, width, height, minDepth, maxDepth, projection, view, world); XMStoreFloat3(&result, v); } inline Vector3 Viewport::Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world) const noexcept { using namespace DirectX; - XMVECTOR v = XMLoadFloat3(&p); + XMVECTOR v = XMLoadFloat3(&p); const XMMATRIX projection = XMLoadFloat4x4(&proj); - v = XMVector3Unproject(v, x, y, width, height, minDepth, maxDepth, projection, view, world); + v = XMVector3Unproject(v, x, y, width, height, minDepth, maxDepth, projection, view, world); Vector3 result; XMStoreFloat3(&result, v); return result; } -inline void Viewport::Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept +inline void +Viewport::Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept { using namespace DirectX; - XMVECTOR v = XMLoadFloat3(&p); + XMVECTOR v = XMLoadFloat3(&p); const XMMATRIX projection = XMLoadFloat4x4(&proj); - v = XMVector3Unproject(v, x, y, width, height, minDepth, maxDepth, projection, view, world); + v = XMVector3Unproject(v, x, y, width, height, minDepth, maxDepth, projection, view, world); XMStoreFloat3(&result, v); } diff --git a/Inc/SpriteBatch.h b/Inc/SpriteBatch.h index 6659a124..71c24435 100644 --- a/Inc/SpriteBatch.h +++ b/Inc/SpriteBatch.h @@ -35,13 +35,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -50,7 +50,6 @@ #endif #endif - namespace DirectX { class ResourceUploadBatch; @@ -68,31 +67,29 @@ namespace DirectX enum SpriteEffects : uint32_t { - SpriteEffects_None = 0, + SpriteEffects_None = 0, SpriteEffects_FlipHorizontally = 1, - SpriteEffects_FlipVertically = 2, - SpriteEffects_FlipBoth = SpriteEffects_FlipHorizontally | SpriteEffects_FlipVertically, + SpriteEffects_FlipVertically = 2, + SpriteEffects_FlipBoth = SpriteEffects_FlipHorizontally | SpriteEffects_FlipVertically, }; class DIRECTX_TOOLKIT_API SpriteBatchPipelineStateDescription { public: - explicit SpriteBatchPipelineStateDescription( - const RenderTargetState& renderTarget, - _In_opt_ const D3D12_BLEND_DESC* blend = nullptr, - _In_opt_ const D3D12_DEPTH_STENCIL_DESC* depthStencil = nullptr, - _In_opt_ const D3D12_RASTERIZER_DESC* rasterizer = nullptr, - _In_opt_ const D3D12_GPU_DESCRIPTOR_HANDLE* isamplerDescriptor = nullptr) noexcept - : - blendDesc(blend ? *blend : s_DefaultBlendDesc), - depthStencilDesc(depthStencil ? *depthStencil : s_DefaultDepthStencilDesc), - rasterizerDesc(rasterizer ? *rasterizer : s_DefaultRasterizerDesc), - renderTargetState(renderTarget), - samplerDescriptor{}, - customRootSignature(nullptr), - customVertexShader{}, - customPixelShader{}, - customCBV(false) + explicit SpriteBatchPipelineStateDescription(const RenderTargetState& renderTarget, + _In_opt_ const D3D12_BLEND_DESC* blend = nullptr, + _In_opt_ const D3D12_DEPTH_STENCIL_DESC* depthStencil = nullptr, + _In_opt_ const D3D12_RASTERIZER_DESC* rasterizer = nullptr, + _In_opt_ const D3D12_GPU_DESCRIPTOR_HANDLE* isamplerDescriptor = nullptr) noexcept + : blendDesc(blend ? *blend : s_DefaultBlendDesc), + depthStencilDesc(depthStencil ? *depthStencil : s_DefaultDepthStencilDesc), + rasterizerDesc(rasterizer ? *rasterizer : s_DefaultRasterizerDesc), + renderTargetState(renderTarget), + samplerDescriptor{}, + customRootSignature(nullptr), + customVertexShader{}, + customPixelShader{}, + customCBV(false) { if (isamplerDescriptor) this->samplerDescriptor = *isamplerDescriptor; @@ -109,106 +106,126 @@ namespace DirectX bool customCBV; private: - static const D3D12_BLEND_DESC s_DefaultBlendDesc; - static const D3D12_RASTERIZER_DESC s_DefaultRasterizerDesc; - static const D3D12_DEPTH_STENCIL_DESC s_DefaultDepthStencilDesc; + static const D3D12_BLEND_DESC s_DefaultBlendDesc; + static const D3D12_RASTERIZER_DESC s_DefaultRasterizerDesc; + static const D3D12_DEPTH_STENCIL_DESC s_DefaultDepthStencilDesc; }; class SpriteBatch { public: - DIRECTX_TOOLKIT_API SpriteBatch( - _In_ ID3D12Device* device, ResourceUploadBatch& upload, - const SpriteBatchPipelineStateDescription& psoDesc, - _In_opt_ const D3D12_VIEWPORT* viewport = nullptr); + DIRECTX_TOOLKIT_API SpriteBatch(_In_ ID3D12Device* device, + ResourceUploadBatch& upload, + const SpriteBatchPipelineStateDescription& psoDesc, + _In_opt_ const D3D12_VIEWPORT* viewport = nullptr); - DIRECTX_TOOLKIT_API SpriteBatch(SpriteBatch&&) noexcept; - DIRECTX_TOOLKIT_API SpriteBatch& operator= (SpriteBatch&&) noexcept; + DIRECTX_TOOLKIT_API SpriteBatch(SpriteBatch&&) noexcept; + DIRECTX_TOOLKIT_API SpriteBatch& operator=(SpriteBatch&&) noexcept; - SpriteBatch(SpriteBatch const&) = delete; - SpriteBatch& operator= (SpriteBatch const&) = delete; + SpriteBatch(SpriteBatch const&) = delete; + SpriteBatch& operator=(SpriteBatch const&) = delete; DIRECTX_TOOLKIT_API virtual ~SpriteBatch(); // Begin/End a batch of sprite drawing operations. - DIRECTX_TOOLKIT_API void XM_CALLCONV Begin( - _In_ ID3D12GraphicsCommandList* commandList, - SpriteSortMode sortMode = SpriteSortMode_Deferred, - FXMMATRIX transformMatrix = MatrixIdentity); - // Begin using a static sampler. - - DIRECTX_TOOLKIT_API void XM_CALLCONV Begin( - _In_ ID3D12GraphicsCommandList* commandList, - D3D12_GPU_DESCRIPTOR_HANDLE sampler, - SpriteSortMode sortMode = SpriteSortMode_Deferred, - FXMMATRIX transformMatrix = MatrixIdentity); - // Begin with a heap-based sampler. - - DIRECTX_TOOLKIT_API void XM_CALLCONV Begin( - _In_ ID3D12GraphicsCommandList* commandList, - std::function setCustomCallback, - SpriteSortMode sortMode = SpriteSortMode_Deferred, - FXMMATRIX transformMatrix = MatrixIdentity); - // Begin with a static sampler and custom callback. - - DIRECTX_TOOLKIT_API void XM_CALLCONV Begin( - _In_ ID3D12GraphicsCommandList* commandList, - D3D12_GPU_DESCRIPTOR_HANDLE sampler, - std::function setCustomCallback, - SpriteSortMode sortMode = SpriteSortMode_Deferred, - FXMMATRIX transformMatrix = MatrixIdentity); - // Begin with a heap-based sampler and custom callback. + DIRECTX_TOOLKIT_API void XM_CALLCONV Begin(_In_ ID3D12GraphicsCommandList* commandList, + SpriteSortMode sortMode = SpriteSortMode_Deferred, + FXMMATRIX transformMatrix = MatrixIdentity); + // Begin using a static sampler. + + DIRECTX_TOOLKIT_API void XM_CALLCONV Begin(_In_ ID3D12GraphicsCommandList* commandList, + D3D12_GPU_DESCRIPTOR_HANDLE sampler, + SpriteSortMode sortMode = SpriteSortMode_Deferred, + FXMMATRIX transformMatrix = MatrixIdentity); + // Begin with a heap-based sampler. + + DIRECTX_TOOLKIT_API void XM_CALLCONV Begin(_In_ ID3D12GraphicsCommandList* commandList, + std::function setCustomCallback, + SpriteSortMode sortMode = SpriteSortMode_Deferred, + FXMMATRIX transformMatrix = MatrixIdentity); + // Begin with a static sampler and custom callback. + + DIRECTX_TOOLKIT_API void XM_CALLCONV Begin(_In_ ID3D12GraphicsCommandList* commandList, + D3D12_GPU_DESCRIPTOR_HANDLE sampler, + std::function setCustomCallback, + SpriteSortMode sortMode = SpriteSortMode_Deferred, + FXMMATRIX transformMatrix = MatrixIdentity); + // Begin with a heap-based sampler and custom callback. DIRECTX_TOOLKIT_API void __cdecl End(); // Draw overloads specifying position, origin and scale as XMFLOAT2. - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, - XMFLOAT2 const& position, - FXMVECTOR color = Colors::White); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, - XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, - FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, - XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, - FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + XMFLOAT2 const& position, + FXMVECTOR color = Colors::White); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + XMFLOAT2 const& position, + _In_opt_ RECT const* sourceRectangle, + FXMVECTOR color = Colors::White, + float rotation = 0, + XMFLOAT2 const& origin = Float2Zero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + XMFLOAT2 const& position, + _In_opt_ RECT const* sourceRectangle, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0); // Draw overloads specifying position, origin and scale via the first two components of an XMVECTOR. - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, - FXMVECTOR position, - FXMVECTOR color = Colors::White); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, - FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, - FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, - FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, - FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + FXMVECTOR position, + FXMVECTOR color = Colors::White); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + FXMVECTOR position, + _In_opt_ RECT const* sourceRectangle, + FXMVECTOR color = Colors::White, + float rotation = 0, + FXMVECTOR origin = g_XMZero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + FXMVECTOR position, + _In_opt_ RECT const* sourceRectangle, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0); // Draw overloads specifying position as a RECT. - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, - RECT const& destinationRectangle, - FXMVECTOR color = Colors::White); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE - textureSRV, XMUINT2 const& textureSize, - RECT const& destinationRectangle, _In_opt_ RECT const* sourceRectangle, - FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + RECT const& destinationRectangle, + FXMVECTOR color = Colors::White); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, + XMUINT2 const& textureSize, + RECT const& destinationRectangle, + _In_opt_ RECT const* sourceRectangle, + FXMVECTOR color = Colors::White, + float rotation = 0, + XMFLOAT2 const& origin = Float2Zero, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0); // Rotation mode to be applied to the sprite transformation - #if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) - DIRECTX_TOOLKIT_API void __cdecl SetRotation(DXGI_MODE_ROTATION mode); +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) + DIRECTX_TOOLKIT_API void __cdecl SetRotation(DXGI_MODE_ROTATION mode); DIRECTX_TOOLKIT_API DXGI_MODE_ROTATION __cdecl GetRotation() const noexcept; - #endif +#endif // Set viewport for sprite transformation DIRECTX_TOOLKIT_API void __cdecl SetViewport(const D3D12_VIEWPORT& viewPort); @@ -225,5 +242,5 @@ namespace DirectX DIRECTX_TOOLKIT_API static const XMMATRIX MatrixIdentity; DIRECTX_TOOLKIT_API static const XMFLOAT2 Float2Zero; }; - } -} + } // namespace DX12 +} // namespace DirectX diff --git a/Inc/SpriteFont.h b/Inc/SpriteFont.h index 6cc2a585..c2285bfd 100644 --- a/Inc/SpriteFont.h +++ b/Inc/SpriteFont.h @@ -18,13 +18,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -33,7 +33,6 @@ #endif #endif - namespace DirectX { inline namespace DX12 @@ -43,186 +42,211 @@ namespace DirectX public: struct Glyph; - DIRECTX_TOOLKIT_API SpriteFont( - _In_ ID3D12Device* device, - ResourceUploadBatch& upload, - _In_z_ wchar_t const* fileName, - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, - bool forceSRGB = false); - DIRECTX_TOOLKIT_API SpriteFont( - _In_ ID3D12Device* device, - ResourceUploadBatch& upload, - _In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize, - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, - bool forceSRGB = false); - DIRECTX_TOOLKIT_API SpriteFont( - D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 textureSize, - _In_reads_(glyphCount) Glyph const* glyphs, size_t glyphCount, - float lineSpacing); - - DIRECTX_TOOLKIT_API SpriteFont(SpriteFont&&) noexcept; - DIRECTX_TOOLKIT_API SpriteFont& operator= (SpriteFont&&) noexcept; - - SpriteFont(SpriteFont const&) = delete; - SpriteFont& operator= (SpriteFont const&) = delete; + DIRECTX_TOOLKIT_API SpriteFont(_In_ ID3D12Device* device, + ResourceUploadBatch& upload, + _In_z_ wchar_t const* fileName, + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, + D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, + bool forceSRGB = false); + DIRECTX_TOOLKIT_API SpriteFont(_In_ ID3D12Device* device, + ResourceUploadBatch& upload, + _In_reads_bytes_(dataSize) uint8_t const* dataBlob, + size_t dataSize, + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, + D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, + bool forceSRGB = false); + DIRECTX_TOOLKIT_API SpriteFont(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 textureSize, + _In_reads_(glyphCount) Glyph const* glyphs, + size_t glyphCount, + float lineSpacing); + + DIRECTX_TOOLKIT_API SpriteFont(SpriteFont&&) noexcept; + DIRECTX_TOOLKIT_API SpriteFont& operator=(SpriteFont&&) noexcept; + + SpriteFont(SpriteFont const&) = delete; + SpriteFont& operator=(SpriteFont const&) = delete; DIRECTX_TOOLKIT_API virtual ~SpriteFont(); // Wide-character / UTF-16LE - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ wchar_t const* text, - XMFLOAT2 const& position, - FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ wchar_t const* text, - XMFLOAT2 const& position, - FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ wchar_t const* text, - FXMVECTOR position, - FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ wchar_t const* text, - FXMVECTOR position, - FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - - DIRECTX_TOOLKIT_API XMVECTOR XM_CALLCONV MeasureString( - _In_z_ wchar_t const* text, - bool ignoreWhitespace = true) const; - - DIRECTX_TOOLKIT_API RECT __cdecl MeasureDrawBounds( - _In_z_ wchar_t const* text, - XMFLOAT2 const& position, - bool ignoreWhitespace = true) const; - DIRECTX_TOOLKIT_API RECT XM_CALLCONV MeasureDrawBounds( - _In_z_ wchar_t const* text, - FXMVECTOR position, - bool ignoreWhitespace = true) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color = Colors::White, + float rotation = 0, + XMFLOAT2 const& origin = Float2Zero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color = Colors::White, + float rotation = 0, + FXMVECTOR origin = g_XMZero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + + DIRECTX_TOOLKIT_API XMVECTOR XM_CALLCONV MeasureString(_In_z_ wchar_t const* text, bool ignoreWhitespace = true) const; + + DIRECTX_TOOLKIT_API + RECT __cdecl MeasureDrawBounds(_In_z_ wchar_t const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const; + DIRECTX_TOOLKIT_API RECT XM_CALLCONV MeasureDrawBounds(_In_z_ wchar_t const* text, + FXMVECTOR position, + bool ignoreWhitespace = true) const; // UTF-8 - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ char const* text, - XMFLOAT2 const& position, - FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ char const* text, - XMFLOAT2 const& position, - FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ char const* text, - FXMVECTOR position, - FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ char const* text, - FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - - DIRECTX_TOOLKIT_API XMVECTOR XM_CALLCONV MeasureString( - _In_z_ char const* text, - bool ignoreWhitespace = true) const; - - DIRECTX_TOOLKIT_API RECT __cdecl MeasureDrawBounds( - _In_z_ char const* text, - XMFLOAT2 const& position, - bool ignoreWhitespace = true) const; - DIRECTX_TOOLKIT_API RECT XM_CALLCONV MeasureDrawBounds( - _In_z_ char const* text, - FXMVECTOR position, - bool ignoreWhitespace = true) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + XMFLOAT2 const& position, + FXMVECTOR color = Colors::White, + float rotation = 0, + XMFLOAT2 const& origin = Float2Zero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + FXMVECTOR position, + FXMVECTOR color = Colors::White, + float rotation = 0, + FXMVECTOR origin = g_XMZero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + + DIRECTX_TOOLKIT_API XMVECTOR XM_CALLCONV MeasureString(_In_z_ char const* text, bool ignoreWhitespace = true) const; + + DIRECTX_TOOLKIT_API + RECT __cdecl MeasureDrawBounds(_In_z_ char const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const; + DIRECTX_TOOLKIT_API RECT XM_CALLCONV MeasureDrawBounds(_In_z_ char const* text, + FXMVECTOR position, + bool ignoreWhitespace = true) const; // Spacing properties DIRECTX_TOOLKIT_API float __cdecl GetLineSpacing() const noexcept; - DIRECTX_TOOLKIT_API void __cdecl SetLineSpacing(float spacing) noexcept; + DIRECTX_TOOLKIT_API void __cdecl SetLineSpacing(float spacing) noexcept; DIRECTX_TOOLKIT_API void __cdecl SetPixelAlignment(bool enable) noexcept; // Font properties DIRECTX_TOOLKIT_API wchar_t __cdecl GetDefaultCharacter() const noexcept; - DIRECTX_TOOLKIT_API void __cdecl SetDefaultCharacter(wchar_t character); + DIRECTX_TOOLKIT_API void __cdecl SetDefaultCharacter(wchar_t character); DIRECTX_TOOLKIT_API bool __cdecl ContainsCharacter(wchar_t character) const; // Custom layout/rendering - DIRECTX_TOOLKIT_API Glyph const* __cdecl FindGlyph(wchar_t character) const; + DIRECTX_TOOLKIT_API Glyph const* __cdecl FindGlyph(wchar_t character) const; DIRECTX_TOOLKIT_API D3D12_GPU_DESCRIPTOR_HANDLE __cdecl GetSpriteSheet() const noexcept; - DIRECTX_TOOLKIT_API XMUINT2 __cdecl GetSpriteSheetSize() const noexcept; + DIRECTX_TOOLKIT_API XMUINT2 __cdecl GetSpriteSheetSize() const noexcept; // Describes a single character glyph. struct Glyph { uint32_t Character; - RECT Subrect; - float XOffset; - float YOffset; - float XAdvance; + RECT Subrect; + float XOffset; + float YOffset; + float XAdvance; }; - #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) - DIRECTX_TOOLKIT_API SpriteFont( - ID3D12Device* device, ResourceUploadBatch& upload, - _In_z_ __wchar_t const* fileName, - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, - bool forceSRGB = false); - - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ __wchar_t const* text, - XMFLOAT2 const& position, - FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ __wchar_t const* text, - XMFLOAT2 const& position, - FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ __wchar_t const* text, - FXMVECTOR position, - FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString( - _In_ SpriteBatch* spriteBatch, - _In_z_ __wchar_t const* text, - FXMVECTOR position, - FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, - SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const; - - DIRECTX_TOOLKIT_API XMVECTOR XM_CALLCONV MeasureString( - _In_z_ __wchar_t const* text, - bool ignoreWhitespace = true) const; - - DIRECTX_TOOLKIT_API RECT __cdecl MeasureDrawBounds( - _In_z_ __wchar_t const* text, - XMFLOAT2 const& position, - bool ignoreWhitespace = true) const; - DIRECTX_TOOLKIT_API RECT XM_CALLCONV MeasureDrawBounds( - _In_z_ __wchar_t const* text, - FXMVECTOR position, - bool ignoreWhitespace = true) const; +#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) + DIRECTX_TOOLKIT_API SpriteFont(ID3D12Device* device, + ResourceUploadBatch& upload, + _In_z_ __wchar_t const* fileName, + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, + D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, + bool forceSRGB = false); + + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color = Colors::White, + float rotation = 0, + XMFLOAT2 const& origin = Float2Zero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color = Colors::White, + float rotation = 0, + FXMVECTOR origin = g_XMZero, + float scale = 1, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects = SpriteEffects_None, + float layerDepth = 0) const; + + DIRECTX_TOOLKIT_API XMVECTOR XM_CALLCONV MeasureString(_In_z_ __wchar_t const* text, bool ignoreWhitespace = true) const; + + DIRECTX_TOOLKIT_API + RECT __cdecl MeasureDrawBounds(_In_z_ __wchar_t const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const; + DIRECTX_TOOLKIT_API RECT XM_CALLCONV MeasureDrawBounds(_In_z_ __wchar_t const* text, + FXMVECTOR position, + bool ignoreWhitespace = true) const; DIRECTX_TOOLKIT_API void __cdecl SetDefaultCharacter(__wchar_t character); DIRECTX_TOOLKIT_API bool __cdecl ContainsCharacter(__wchar_t character) const; DIRECTX_TOOLKIT_API Glyph const* __cdecl FindGlyph(__wchar_t character) const; - #endif // !_NATIVE_WCHAR_T_DEFINED +#endif // !_NATIVE_WCHAR_T_DEFINED private: // Private implementation. @@ -232,5 +256,5 @@ namespace DirectX DIRECTX_TOOLKIT_API static const XMFLOAT2 Float2Zero; }; - } -} + } // namespace DX12 +} // namespace DirectX diff --git a/Inc/VertexTypes.h b/Inc/VertexTypes.h index dccd6f23..fa287fa1 100644 --- a/Inc/VertexTypes.h +++ b/Inc/VertexTypes.h @@ -25,13 +25,13 @@ #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -45,55 +45,50 @@ #pragma warning(disable : 4251) #endif - namespace DirectX { inline namespace DX12 { - // Vertex struct holding position information. + // Vertex struct holding position information. struct DIRECTX_TOOLKIT_API VertexPosition { VertexPosition() = default; - VertexPosition(const VertexPosition&) = default; + VertexPosition(const VertexPosition&) = default; VertexPosition& operator=(const VertexPosition&) = default; - VertexPosition(VertexPosition&&) = default; + VertexPosition(VertexPosition&&) = default; VertexPosition& operator=(VertexPosition&&) = default; VertexPosition(XMFLOAT3 const& iposition) noexcept : position(iposition) {} - VertexPosition(FXMVECTOR iposition) noexcept - { - XMStoreFloat3(&this->position, iposition); - } + VertexPosition(FXMVECTOR iposition) noexcept { XMStoreFloat3(&this->position, iposition); } XMFLOAT3 position; static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 1; + static constexpr unsigned int InputElementCount = 1; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position and color information. struct DIRECTX_TOOLKIT_API VertexPositionColor { VertexPositionColor() = default; - VertexPositionColor(const VertexPositionColor&) = default; + VertexPositionColor(const VertexPositionColor&) = default; VertexPositionColor& operator=(const VertexPositionColor&) = default; - VertexPositionColor(VertexPositionColor&&) = default; + VertexPositionColor(VertexPositionColor&&) = default; VertexPositionColor& operator=(VertexPositionColor&&) = default; VertexPositionColor(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor) noexcept : position(iposition), - color(icolor) + color(icolor) {} VertexPositionColor(FXMVECTOR iposition, FXMVECTOR icolor) noexcept @@ -108,25 +103,24 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 2; + static constexpr unsigned int InputElementCount = 2; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position and texture mapping information. struct DIRECTX_TOOLKIT_API VertexPositionTexture { VertexPositionTexture() = default; - VertexPositionTexture(const VertexPositionTexture&) = default; + VertexPositionTexture(const VertexPositionTexture&) = default; VertexPositionTexture& operator=(const VertexPositionTexture&) = default; - VertexPositionTexture(VertexPositionTexture&&) = default; + VertexPositionTexture(VertexPositionTexture&&) = default; VertexPositionTexture& operator=(VertexPositionTexture&&) = default; VertexPositionTexture(XMFLOAT3 const& iposition, XMFLOAT2 const& itextureCoordinate) noexcept : position(iposition), - textureCoordinate(itextureCoordinate) + textureCoordinate(itextureCoordinate) {} VertexPositionTexture(FXMVECTOR iposition, FXMVECTOR itextureCoordinate) noexcept @@ -141,35 +135,30 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 2; + static constexpr unsigned int InputElementCount = 2; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position and dual texture mapping information. struct DIRECTX_TOOLKIT_API VertexPositionDualTexture { VertexPositionDualTexture() = default; - VertexPositionDualTexture(const VertexPositionDualTexture&) = default; + VertexPositionDualTexture(const VertexPositionDualTexture&) = default; VertexPositionDualTexture& operator=(const VertexPositionDualTexture&) = default; - VertexPositionDualTexture(VertexPositionDualTexture&&) = default; + VertexPositionDualTexture(VertexPositionDualTexture&&) = default; VertexPositionDualTexture& operator=(VertexPositionDualTexture&&) = default; - VertexPositionDualTexture( - XMFLOAT3 const& iposition, - XMFLOAT2 const& itextureCoordinate0, - XMFLOAT2 const& itextureCoordinate1) noexcept + VertexPositionDualTexture(XMFLOAT3 const& iposition, + XMFLOAT2 const& itextureCoordinate0, + XMFLOAT2 const& itextureCoordinate1) noexcept : position(iposition), - textureCoordinate0(itextureCoordinate0), - textureCoordinate1(itextureCoordinate1) + textureCoordinate0(itextureCoordinate0), + textureCoordinate1(itextureCoordinate1) {} - VertexPositionDualTexture( - FXMVECTOR iposition, - FXMVECTOR itextureCoordinate0, - FXMVECTOR itextureCoordinate1) noexcept + VertexPositionDualTexture(FXMVECTOR iposition, FXMVECTOR itextureCoordinate0, FXMVECTOR itextureCoordinate1) noexcept { XMStoreFloat3(&this->position, iposition); XMStoreFloat2(&this->textureCoordinate0, itextureCoordinate0); @@ -183,25 +172,24 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position and normal vector. struct DIRECTX_TOOLKIT_API VertexPositionNormal { VertexPositionNormal() = default; - VertexPositionNormal(const VertexPositionNormal&) = default; + VertexPositionNormal(const VertexPositionNormal&) = default; VertexPositionNormal& operator=(const VertexPositionNormal&) = default; - VertexPositionNormal(VertexPositionNormal&&) = default; + VertexPositionNormal(VertexPositionNormal&&) = default; VertexPositionNormal& operator=(VertexPositionNormal&&) = default; VertexPositionNormal(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal) noexcept : position(iposition), - normal(inormal) + normal(inormal) {} VertexPositionNormal(FXMVECTOR iposition, FXMVECTOR inormal) noexcept @@ -216,26 +204,25 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 2; + static constexpr unsigned int InputElementCount = 2; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position, color, and texture mapping information. struct DIRECTX_TOOLKIT_API VertexPositionColorTexture { VertexPositionColorTexture() = default; - VertexPositionColorTexture(const VertexPositionColorTexture&) = default; + VertexPositionColorTexture(const VertexPositionColorTexture&) = default; VertexPositionColorTexture& operator=(const VertexPositionColorTexture&) = default; - VertexPositionColorTexture(VertexPositionColorTexture&&) = default; + VertexPositionColorTexture(VertexPositionColorTexture&&) = default; VertexPositionColorTexture& operator=(VertexPositionColorTexture&&) = default; VertexPositionColorTexture(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor, XMFLOAT2 const& itextureCoordinate) noexcept : position(iposition), - color(icolor), - textureCoordinate(itextureCoordinate) + color(icolor), + textureCoordinate(itextureCoordinate) {} VertexPositionColorTexture(FXMVECTOR iposition, FXMVECTOR icolor, FXMVECTOR itextureCoordinate) noexcept @@ -252,26 +239,25 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position, normal vector, and color information. struct DIRECTX_TOOLKIT_API VertexPositionNormalColor { VertexPositionNormalColor() = default; - VertexPositionNormalColor(const VertexPositionNormalColor&) = default; + VertexPositionNormalColor(const VertexPositionNormalColor&) = default; VertexPositionNormalColor& operator=(const VertexPositionNormalColor&) = default; - VertexPositionNormalColor(VertexPositionNormalColor&&) = default; + VertexPositionNormalColor(VertexPositionNormalColor&&) = default; VertexPositionNormalColor& operator=(VertexPositionNormalColor&&) = default; VertexPositionNormalColor(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT4 const& icolor) noexcept : position(iposition), - normal(inormal), - color(icolor) + normal(inormal), + color(icolor) {} VertexPositionNormalColor(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor) noexcept @@ -288,26 +274,25 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position, normal vector, and texture mapping information. struct DIRECTX_TOOLKIT_API VertexPositionNormalTexture { VertexPositionNormalTexture() = default; - VertexPositionNormalTexture(const VertexPositionNormalTexture&) = default; + VertexPositionNormalTexture(const VertexPositionNormalTexture&) = default; VertexPositionNormalTexture& operator=(const VertexPositionNormalTexture&) = default; - VertexPositionNormalTexture(VertexPositionNormalTexture&&) = default; + VertexPositionNormalTexture(VertexPositionNormalTexture&&) = default; VertexPositionNormalTexture& operator=(VertexPositionNormalTexture&&) = default; VertexPositionNormalTexture(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT2 const& itextureCoordinate) noexcept : position(iposition), - normal(inormal), - textureCoordinate(itextureCoordinate) + normal(inormal), + textureCoordinate(itextureCoordinate) {} VertexPositionNormalTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR itextureCoordinate) noexcept @@ -324,34 +309,35 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct holding position, normal vector, color, and texture mapping information. struct DIRECTX_TOOLKIT_API VertexPositionNormalColorTexture { VertexPositionNormalColorTexture() = default; - VertexPositionNormalColorTexture(const VertexPositionNormalColorTexture&) = default; + VertexPositionNormalColorTexture(const VertexPositionNormalColorTexture&) = default; VertexPositionNormalColorTexture& operator=(const VertexPositionNormalColorTexture&) = default; - VertexPositionNormalColorTexture(VertexPositionNormalColorTexture&&) = default; + VertexPositionNormalColorTexture(VertexPositionNormalColorTexture&&) = default; VertexPositionNormalColorTexture& operator=(VertexPositionNormalColorTexture&&) = default; - VertexPositionNormalColorTexture( - XMFLOAT3 const& iposition, - XMFLOAT3 const& inormal, - XMFLOAT4 const& icolor, - XMFLOAT2 const& itextureCoordinate) noexcept + VertexPositionNormalColorTexture(XMFLOAT3 const& iposition, + XMFLOAT3 const& inormal, + XMFLOAT4 const& icolor, + XMFLOAT2 const& itextureCoordinate) noexcept : position(iposition), - normal(inormal), - color(icolor), - textureCoordinate(itextureCoordinate) + normal(inormal), + color(icolor), + textureCoordinate(itextureCoordinate) {} - VertexPositionNormalColorTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor, CXMVECTOR itextureCoordinate) noexcept + VertexPositionNormalColorTexture(FXMVECTOR iposition, + FXMVECTOR inormal, + FXMVECTOR icolor, + CXMVECTOR itextureCoordinate) noexcept { XMStoreFloat3(&this->position, iposition); XMStoreFloat3(&this->normal, inormal); @@ -367,11 +353,11 @@ namespace DirectX static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 4; + static constexpr unsigned int InputElementCount = 4; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - } -} + } // namespace DX12 +} // namespace DirectX #if defined(DIRECTX_TOOLKIT_IMPORT) && defined(_MSC_VER) #pragma warning(pop) diff --git a/Inc/WICTextureLoader.h b/Inc/WICTextureLoader.h index 5737416e..7b403e2c 100644 --- a/Inc/WICTextureLoader.h +++ b/Inc/WICTextureLoader.h @@ -35,19 +35,19 @@ #include #ifdef _MSC_VER -#pragma comment(lib,"uuid.lib") +#pragma comment(lib, "uuid.lib") #endif #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -56,21 +56,20 @@ #endif #endif - namespace DirectX { inline namespace DX12 { enum WIC_LOADER_FLAGS : uint32_t { - WIC_LOADER_DEFAULT = 0, - WIC_LOADER_FORCE_SRGB = 0x1, - WIC_LOADER_IGNORE_SRGB = 0x2, + WIC_LOADER_DEFAULT = 0, + WIC_LOADER_FORCE_SRGB = 0x1, + WIC_LOADER_IGNORE_SRGB = 0x2, WIC_LOADER_SRGB_DEFAULT = 0x4, - WIC_LOADER_MIP_AUTOGEN = 0x8, - WIC_LOADER_MIP_RESERVE = 0x10, - WIC_LOADER_FIT_POW2 = 0x20, - WIC_LOADER_MAKE_SQUARE = 0x40, + WIC_LOADER_MIP_AUTOGEN = 0x8, + WIC_LOADER_MIP_RESERVE = 0x10, + WIC_LOADER_FIT_POW2 = 0x20, + WIC_LOADER_MAKE_SQUARE = 0x40, WIC_LOADER_FORCE_RGBA32 = 0x80, }; } @@ -79,144 +78,159 @@ namespace DirectX // Standard version DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadWICTextureFromMemory( - _In_ ID3D12Device* device, - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - size_t wicDataSize, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource, - size_t maxsize = 0) noexcept; + HRESULT __cdecl LoadWICTextureFromMemory(_In_ ID3D12Device* device, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + size_t wicDataSize, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource, + size_t maxsize = 0) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadWICTextureFromFile( - _In_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource, - size_t maxsize = 0) noexcept; - - // Standard version with resource upload + HRESULT __cdecl LoadWICTextureFromFile(_In_ ID3D12Device* device, + _In_z_ const wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource, + size_t maxsize = 0) noexcept; + + // Standard version with resource upload DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromMemory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - size_t wicDataSize, - _Outptr_ ID3D12Resource** texture, - bool generateMips = false, - size_t maxsize = 0); + HRESULT __cdecl CreateWICTextureFromMemory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + size_t wicDataSize, + _Outptr_ ID3D12Resource** texture, + bool generateMips = false, + size_t maxsize = 0); DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromFile( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - bool generateMips = false, - size_t maxsize = 0); - - // Extended version + HRESULT __cdecl CreateWICTextureFromFile(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + bool generateMips = false, + size_t maxsize = 0); + + // Extended version DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadWICTextureFromMemoryEx( - _In_ ID3D12Device* device, - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - size_t wicDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource) noexcept; + HRESULT __cdecl LoadWICTextureFromMemoryEx(_In_ ID3D12Device* device, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl LoadWICTextureFromFileEx( - _In_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource) noexcept; - - // Extended version with resource upload + HRESULT __cdecl LoadWICTextureFromFileEx(_In_ ID3D12Device* device, + _In_z_ const wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource) noexcept; + + // Extended version with resource upload DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromMemoryEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - size_t wicDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture); + HRESULT __cdecl CreateWICTextureFromMemoryEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture); DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromFileEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture); + HRESULT __cdecl CreateWICTextureFromFileEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture); #ifdef __cpp_lib_byte DIRECTX_TOOLKIT_API - inline HRESULT __cdecl LoadWICTextureFromMemory( - _In_ ID3D12Device* device, - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - size_t wicDataSize, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource, - size_t maxsize = 0) noexcept + inline HRESULT __cdecl LoadWICTextureFromMemory(_In_ ID3D12Device* device, + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + size_t wicDataSize, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource, + size_t maxsize = 0) noexcept { - return LoadWICTextureFromMemory(device, reinterpret_cast(wicData), wicDataSize, texture, decodedData, subresource, maxsize); + return LoadWICTextureFromMemory(device, + reinterpret_cast(wicData), + wicDataSize, + texture, + decodedData, + subresource, + maxsize); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateWICTextureFromMemory( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - size_t wicDataSize, - _Outptr_ ID3D12Resource** texture, - bool generateMips = false, - size_t maxsize = 0) + inline HRESULT __cdecl CreateWICTextureFromMemory(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + size_t wicDataSize, + _Outptr_ ID3D12Resource** texture, + bool generateMips = false, + size_t maxsize = 0) { - return CreateWICTextureFromMemory(device, resourceUpload, reinterpret_cast(wicData), wicDataSize, texture, generateMips, maxsize); + return CreateWICTextureFromMemory(device, + resourceUpload, + reinterpret_cast(wicData), + wicDataSize, + texture, + generateMips, + maxsize); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl LoadWICTextureFromMemoryEx( - _In_ ID3D12Device* device, - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - size_t wicDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource) noexcept + inline HRESULT __cdecl LoadWICTextureFromMemoryEx(_In_ ID3D12Device* device, + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + size_t wicDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource) noexcept { - return LoadWICTextureFromMemoryEx(device, reinterpret_cast(wicData), wicDataSize, maxsize, resFlags, loadFlags, texture, decodedData, subresource); + return LoadWICTextureFromMemoryEx(device, + reinterpret_cast(wicData), + wicDataSize, + maxsize, + resFlags, + loadFlags, + texture, + decodedData, + subresource); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateWICTextureFromMemoryEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - size_t wicDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture) + inline HRESULT __cdecl CreateWICTextureFromMemoryEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + size_t wicDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture) { - return CreateWICTextureFromMemoryEx(device, resourceUpload, reinterpret_cast(wicData), wicDataSize, maxsize, resFlags, loadFlags, texture); + return CreateWICTextureFromMemoryEx(device, + resourceUpload, + reinterpret_cast(wicData), + wicDataSize, + maxsize, + resFlags, + loadFlags, + texture); } #endif // __cpp_lib_byte @@ -233,4 +247,4 @@ namespace DirectX #ifdef __clang__ #pragma clang diagnostic pop #endif -} +} // namespace DirectX diff --git a/Inc/XboxDDSTextureLoader.h b/Inc/XboxDDSTextureLoader.h index d886232c..298dfa72 100644 --- a/Inc/XboxDDSTextureLoader.h +++ b/Inc/XboxDDSTextureLoader.h @@ -27,7 +27,7 @@ #endif #ifdef _GAMING_XBOX -#pragma comment(lib,"xmem.lib") +#pragma comment(lib, "xmem.lib") #endif #include @@ -39,11 +39,11 @@ namespace DirectX { enum DDS_ALPHA_MODE : uint32_t { - DDS_ALPHA_MODE_UNKNOWN = 0, - DDS_ALPHA_MODE_STRAIGHT = 1, + DDS_ALPHA_MODE_UNKNOWN = 0, + DDS_ALPHA_MODE_STRAIGHT = 1, DDS_ALPHA_MODE_PREMULTIPLIED = 2, - DDS_ALPHA_MODE_OPAQUE = 3, - DDS_ALPHA_MODE_CUSTOM = 4, + DDS_ALPHA_MODE_OPAQUE = 3, + DDS_ALPHA_MODE_CUSTOM = 4, }; } #endif @@ -51,13 +51,13 @@ namespace DirectX #ifndef DIRECTX_TOOLKIT_API #ifdef DIRECTX_TOOLKIT_EXPORT #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllexport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllexport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllexport) #endif #elif defined(DIRECTX_TOOLKIT_IMPORT) #ifdef __GNUC__ -#define DIRECTX_TOOLKIT_API __attribute__ ((dllimport)) +#define DIRECTX_TOOLKIT_API __attribute__((dllimport)) #else #define DIRECTX_TOOLKIT_API __declspec(dllimport) #endif @@ -66,7 +66,6 @@ namespace DirectX #endif #endif - namespace Xbox { using DirectX::DDS_ALPHA_MODE; @@ -94,41 +93,45 @@ namespace Xbox // DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D12Device* device, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D12Resource** texture, - _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _In_ bool forceSRGB = false, - _Out_opt_ bool* isCubeMap = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D12Device* device, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D12Resource** texture, + _Outptr_ void** grfxMemory, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _In_ bool forceSRGB = false, + _Out_opt_ bool* isCubeMap = nullptr) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFile( - _In_ ID3D12Device* device, - _In_z_ const wchar_t* szFileName, - _Outptr_opt_ ID3D12Resource** texture, - _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _In_ bool forceSRGB = false, - _Out_opt_ bool* isCubeMap = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromFile(_In_ ID3D12Device* device, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D12Resource** texture, + _Outptr_ void** grfxMemory, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _In_ bool forceSRGB = false, + _Out_opt_ bool* isCubeMap = nullptr) noexcept; DIRECTX_TOOLKIT_API void FreeDDSTextureMemory(_In_opt_ void* grfxMemory) noexcept; #ifdef __cpp_lib_byte DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D12Device* device, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D12Resource** texture, - _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _In_ bool forceSRGB = false, - _Out_opt_ bool* isCubeMap = nullptr) noexcept + inline HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D12Device* device, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D12Resource** texture, + _Outptr_ void** grfxMemory, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _In_ bool forceSRGB = false, + _Out_opt_ bool* isCubeMap = nullptr) noexcept { - return CreateDDSTextureFromMemory(device, reinterpret_cast(ddsData), ddsDataSize, texture, grfxMemory, alphaMode, forceSRGB, isCubeMap); + return CreateDDSTextureFromMemory(device, + reinterpret_cast(ddsData), + ddsDataSize, + texture, + grfxMemory, + alphaMode, + forceSRGB, + isCubeMap); } #endif // __cpp_lib_byte -} +} // namespace Xbox diff --git a/README.md b/README.md index e7a748c0..b81e3183 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Copyright (c) Microsoft Corporation. This package contains the "DirectX Tool Kit", a collection of helper classes for writing Direct3D 12 C++ code for Win32 desktop applications for Windows 11 and Windows 10, game titles for Xbox Series X\|S and Xbox One, and Universal Windows Platform (UWP) apps for Windows 11 and Windows 10. -This code is designed to build with Visual Studio 2022, Visual Studio 2026, clang for Windows v12 or later, or MinGW. Use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later is required for Visual Studio. +This code is designed to build with Visual Studio 2022, Visual Studio 2026, clang for Windows v12 or later, or MinGW. Use of the Windows 11 SDK ([22000](https://walbourn.github.io/windows-sdk-for-windows-11/)) or later is required for Visual Studio. These components are designed to work without requiring any content from the legacy DirectX SDK. For details, see [Where is the DirectX SDK?](https://aka.ms/dxsdk). @@ -104,6 +104,13 @@ FOR SECURITY ADVISORIES, see [GitHub](https://github.com/microsoft/DirectXTK12/s For a full change history, see [CHANGELOG.md](https://github.com/microsoft/DirectXTK12/blob/main/CHANGELOG.md). +* clang-format use for this project must match the version use by GitHub Super-Linter to pass the validation. VS 2022 and VS 2026 come with different versions, so to match use: + +```cmd +winget install --id=LLVM.LLVM --version 21.1.2 +powershell -File build/Format.ps1 -LLVM +``` + * The _directxtk12_desktop_win10_ and _directxtk12_uwp_ NuGet packages are deprecated. The best way to integrate the latest DirectX Tool Kit into your C++ project is using [vcpkg](https://github.com/microsoft/vcpkg/tree/master/ports/directxtk12). * The CMake projects require 3.21 or later. diff --git a/Src/AlignedNew.h b/Src/AlignedNew.h index 0a4702b2..5f23640c 100644 --- a/Src/AlignedNew.h +++ b/Src/AlignedNew.h @@ -18,7 +18,6 @@ #include #endif - namespace DirectX { // Derive from this to customize operator new and delete for @@ -32,38 +31,37 @@ namespace DirectX struct AlignedNew { // Allocate aligned memory. - static void* operator new (size_t size) + static void* operator new(size_t size) { const size_t alignment = alignof(TDerived); - static_assert(alignment > 8, "AlignedNew is only useful for types with > 8 byte alignment. Did you forget a __declspec(align) on TDerived?"); + static_assert(alignment > 8, + "AlignedNew is only useful for types with > 8 byte alignment. Did you forget a __declspec(align) on TDerived?"); static_assert(((alignment - 1) & alignment) == 0, "AlignedNew only works with power of two alignment"); - #ifdef _WIN32 +#ifdef _WIN32 void* ptr = _aligned_malloc(size, alignment); - #else - // This C++17 Standard Library function is currently NOT - // implemented for the Microsoft Standard C++ Library. +#else + // This C++17 Standard Library function is currently NOT + // implemented for the Microsoft Standard C++ Library. void* ptr = aligned_alloc(alignment, size); - #endif +#endif if (!ptr) throw std::bad_alloc(); return ptr; } - // Free aligned memory. - static void operator delete (void* ptr) + static void operator delete(void* ptr) { - #ifdef _WIN32 +#ifdef _WIN32 _aligned_free(ptr); - #else +#else free(ptr); - #endif +#endif } - // Array overloads. static void* operator new[](size_t size) { @@ -72,10 +70,6 @@ namespace DirectX return operator new(size); } - - static void operator delete[](void* ptr) - { - operator delete(ptr); - } + static void operator delete[](void* ptr) { operator delete(ptr); } }; -} +} // namespace DirectX diff --git a/Src/AlphaTestEffect.cpp b/Src/AlphaTestEffect.cpp index 29428e5f..676e843d 100644 --- a/Src/AlphaTestEffect.cpp +++ b/Src/AlphaTestEffect.cpp @@ -26,30 +26,31 @@ namespace static_assert((sizeof(AlphaTestEffectConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct AlphaTestEffectTraits { using ConstantBufferType = AlphaTestEffectConstants; - static constexpr int VertexShaderCount = 4; - static constexpr int PixelShaderCount = 4; + static constexpr int VertexShaderCount = 4; + static constexpr int PixelShaderCount = 4; static constexpr int ShaderPermutationCount = 8; - static constexpr int RootSignatureCount = 1; + static constexpr int RootSignatureCount = 1; }; -} +} // namespace // Internal AlphaTestEffect implementation class. class AlphaTestEffect::Impl : public EffectBase { public: - Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - D3D12_COMPARISON_FUNC alphaFunction); + Impl(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + D3D12_COMPARISON_FUNC alphaFunction); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; enum RootParameterIndex @@ -61,7 +62,7 @@ class AlphaTestEffect::Impl : public EffectBase }; D3D12_COMPARISON_FUNC mAlphaFunction; - int referenceAlpha; + int referenceAlpha; EffectColor color; @@ -73,7 +74,6 @@ class AlphaTestEffect::Impl : public EffectBase void Apply(_In_ ID3D12GraphicsCommandList* commandList); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -119,91 +119,88 @@ namespace #include "AlphaTestEffect_PSAlphaTestEqNe.inc" #include "AlphaTestEffect_PSAlphaTestEqNeNoFog.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { AlphaTestEffect_VSAlphaTest, sizeof(AlphaTestEffect_VSAlphaTest) }, - { AlphaTestEffect_VSAlphaTestNoFog, sizeof(AlphaTestEffect_VSAlphaTestNoFog) }, - { AlphaTestEffect_VSAlphaTestVc, sizeof(AlphaTestEffect_VSAlphaTestVc) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { AlphaTestEffect_VSAlphaTest, sizeof(AlphaTestEffect_VSAlphaTest) }, + { AlphaTestEffect_VSAlphaTestNoFog, sizeof(AlphaTestEffect_VSAlphaTestNoFog) }, + { AlphaTestEffect_VSAlphaTestVc, sizeof(AlphaTestEffect_VSAlphaTestVc) }, { AlphaTestEffect_VSAlphaTestVcNoFog, sizeof(AlphaTestEffect_VSAlphaTestVcNoFog) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // lt/gt - 1, // lt/gt, no fog - 2, // lt/gt, vertex color - 3, // lt/gt, vertex color, no fog - - 0, // eq/ne - 1, // eq/ne, no fog - 2, // eq/ne, vertex color - 3, // eq/ne, vertex color, no fog +const int EffectBase::VertexShaderIndices[] = { + 0, // lt/gt + 1, // lt/gt, no fog + 2, // lt/gt, vertex color + 3, // lt/gt, vertex color, no fog + + 0, // eq/ne + 1, // eq/ne, no fog + 2, // eq/ne, vertex color + 3, // eq/ne, vertex color, no fog }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { AlphaTestEffect_PSAlphaTestLtGt, sizeof(AlphaTestEffect_PSAlphaTestLtGt) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { AlphaTestEffect_PSAlphaTestLtGt, sizeof(AlphaTestEffect_PSAlphaTestLtGt) }, { AlphaTestEffect_PSAlphaTestLtGtNoFog, sizeof(AlphaTestEffect_PSAlphaTestLtGtNoFog) }, - { AlphaTestEffect_PSAlphaTestEqNe, sizeof(AlphaTestEffect_PSAlphaTestEqNe) }, + { AlphaTestEffect_PSAlphaTestEqNe, sizeof(AlphaTestEffect_PSAlphaTestEqNe) }, { AlphaTestEffect_PSAlphaTestEqNeNoFog, sizeof(AlphaTestEffect_PSAlphaTestEqNeNoFog) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // lt/gt - 1, // lt/gt, no fog - 0, // lt/gt, vertex color - 1, // lt/gt, vertex color, no fog - - 2, // eq/ne - 3, // eq/ne, no fog - 2, // eq/ne, vertex color - 3, // eq/ne, vertex color, no fog +const int EffectBase::PixelShaderIndices[] = { + 0, // lt/gt + 1, // lt/gt, no fog + 0, // lt/gt, vertex color + 1, // lt/gt, vertex color, no fog + + 2, // eq/ne + 3, // eq/ne, no fog + 2, // eq/ne, vertex color + 3, // eq/ne, vertex color, no fog }; #pragma endregion // Global pool of per-device AlphaTestEffect resources. template<> -SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; +SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool + = {}; // Constructor. -AlphaTestEffect::Impl::Impl( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - D3D12_COMPARISON_FUNC alphaFunction) +AlphaTestEffect::Impl::Impl(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + D3D12_COMPARISON_FUNC alphaFunction) : EffectBase(device), - mAlphaFunction(alphaFunction), - referenceAlpha(0), - texture{}, - textureSampler{} + mAlphaFunction(alphaFunction), + referenceAlpha(0), + texture{}, + textureSampler{} { - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == AlphaTestEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == AlphaTestEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) + == AlphaTestEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) + == AlphaTestEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) + == AlphaTestEffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) + == AlphaTestEffectTraits::ShaderPermutationCount, + "array/max mismatch"); // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; const CD3DX12_DESCRIPTOR_RANGE textureRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); @@ -252,8 +249,7 @@ AlphaTestEffect::Impl::Impl( assert(pi >= 0 && pi < AlphaTestEffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < AlphaTestEffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -262,7 +258,6 @@ AlphaTestEffect::Impl::Impl( SetDebugObjectName(mPipelineState.Get(), L"AlphaTestEffect"); } - int AlphaTestEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const noexcept { int permutation = 0; @@ -280,8 +275,7 @@ int AlphaTestEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) con } // Which alpha compare mode? - if (mAlphaFunction == D3D12_COMPARISON_FUNC_EQUAL || - mAlphaFunction == D3D12_COMPARISON_FUNC_NOT_EQUAL) + if (mAlphaFunction == D3D12_COMPARISON_FUNC_EQUAL || mAlphaFunction == D3D12_COMPARISON_FUNC_NOT_EQUAL) { permutation += 4; } @@ -289,7 +283,6 @@ int AlphaTestEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) con return permutation; } - // Sets our state onto the D3D device. void AlphaTestEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { @@ -310,66 +303,65 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) constexpr float threshold = 0.5f / 255.0f; // What to do if the alpha comparison passes or fails. Positive accepts the pixel, negative clips it. - static const XMVECTORF32 selectIfTrue = { { { 1, -1 } } }; - static const XMVECTORF32 selectIfFalse = { { { -1, 1 } } }; - static const XMVECTORF32 selectNever = { { { -1, -1 } } }; - static const XMVECTORF32 selectAlways = { { { 1, 1 } } }; + static const XMVECTORF32 selectIfTrue = { { { 1, -1 } } }; + static const XMVECTORF32 selectIfFalse = { { { -1, 1 } } }; + static const XMVECTORF32 selectNever = { { { -1, -1 } } }; + static const XMVECTORF32 selectAlways = { { { 1, 1 } } }; - float compareTo; + float compareTo; XMVECTOR resultSelector; switch (mAlphaFunction) { case D3D12_COMPARISON_FUNC_LESS: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference - threshold; + compareTo = reference - threshold; resultSelector = selectIfTrue; break; case D3D12_COMPARISON_FUNC_LESS_EQUAL: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference + threshold; + compareTo = reference + threshold; resultSelector = selectIfTrue; break; case D3D12_COMPARISON_FUNC_GREATER_EQUAL: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference - threshold; + compareTo = reference - threshold; resultSelector = selectIfFalse; break; case D3D12_COMPARISON_FUNC_GREATER: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference + threshold; + compareTo = reference + threshold; resultSelector = selectIfFalse; break; case D3D12_COMPARISON_FUNC_EQUAL: // Shader will evaluate: clip((abs(a - x) < y) ? z : w) - compareTo = reference; + compareTo = reference; resultSelector = selectIfTrue; break; case D3D12_COMPARISON_FUNC_NOT_EQUAL: // Shader will evaluate: clip((abs(a - x) < y) ? z : w) - compareTo = reference; + compareTo = reference; resultSelector = selectIfFalse; break; case D3D12_COMPARISON_FUNC_NEVER: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = 0; + compareTo = 0; resultSelector = selectNever; break; case D3D12_COMPARISON_FUNC_ALWAYS: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = 0; + compareTo = 0; resultSelector = selectAlways; break; - default: - throw std::runtime_error("Unknown alpha test function"); + default: throw std::runtime_error("Unknown alpha test function"); } // x = compareTo, y = threshold, zw = resultSelector. @@ -389,7 +381,8 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) throw std::runtime_error("AlphaTestEffect"); } - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heaps. commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSampler, textureSampler); @@ -401,19 +394,16 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) } // Public constructor. -AlphaTestEffect::AlphaTestEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - D3D12_COMPARISON_FUNC alphaFunction) +AlphaTestEffect::AlphaTestEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + D3D12_COMPARISON_FUNC alphaFunction) : pImpl(std::make_unique(device, effectFlags, pipelineDescription, alphaFunction)) {} - -AlphaTestEffect::AlphaTestEffect(AlphaTestEffect&&) noexcept = default; -AlphaTestEffect& AlphaTestEffect::operator= (AlphaTestEffect&&) noexcept = default; -AlphaTestEffect::~AlphaTestEffect() = default; - +AlphaTestEffect::AlphaTestEffect(AlphaTestEffect&&) noexcept = default; +AlphaTestEffect& AlphaTestEffect::operator=(AlphaTestEffect&&) noexcept = default; +AlphaTestEffect::~AlphaTestEffect() = default; // IEffect methods void AlphaTestEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -421,7 +411,6 @@ void AlphaTestEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings void XM_CALLCONV AlphaTestEffect::SetWorld(FXMMATRIX value) { @@ -430,7 +419,6 @@ void XM_CALLCONV AlphaTestEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::FogVector; } - void XM_CALLCONV AlphaTestEffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -438,7 +426,6 @@ void XM_CALLCONV AlphaTestEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; } - void XM_CALLCONV AlphaTestEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -446,17 +433,16 @@ void XM_CALLCONV AlphaTestEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV AlphaTestEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; - pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; + pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition + | EffectDirtyFlags::FogVector; } - // Material settings void XM_CALLCONV AlphaTestEffect::SetDiffuseColor(FXMVECTOR value) { @@ -465,7 +451,6 @@ void XM_CALLCONV AlphaTestEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void AlphaTestEffect::SetAlpha(float value) { pImpl->color.alpha = value; @@ -473,16 +458,14 @@ void AlphaTestEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV AlphaTestEffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->color.diffuseColor = value; - pImpl->color.alpha = XMVectorGetW(value); + pImpl->color.alpha = XMVectorGetW(value); pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - // Fog settings. void AlphaTestEffect::SetFogStart(float value) { @@ -491,7 +474,6 @@ void AlphaTestEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void AlphaTestEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -499,7 +481,6 @@ void AlphaTestEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV AlphaTestEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -507,15 +488,13 @@ void XM_CALLCONV AlphaTestEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void AlphaTestEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { - pImpl->texture = srvDescriptor; + pImpl->texture = srvDescriptor; pImpl->textureSampler = samplerDescriptor; } - void AlphaTestEffect::SetReferenceAlpha(int value) { pImpl->referenceAlpha = value; diff --git a/Src/BasicEffect.cpp b/Src/BasicEffect.cpp index 65a401aa..2f3c1e43 100644 --- a/Src/BasicEffect.cpp +++ b/Src/BasicEffect.cpp @@ -37,18 +37,17 @@ namespace static_assert((sizeof(BasicEffectConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct BasicEffectTraits { using ConstantBufferType = BasicEffectConstants; - static constexpr int VertexShaderCount = 24; - static constexpr int PixelShaderCount = 10; + static constexpr int VertexShaderCount = 24; + static constexpr int PixelShaderCount = 10; static constexpr int ShaderPermutationCount = 40; - static constexpr int RootSignatureCount = 2; + static constexpr int RootSignatureCount = 2; }; -} +} // namespace // Internal BasicEffect implementation class. class BasicEffect::Impl : public EffectBase @@ -56,10 +55,10 @@ class BasicEffect::Impl : public EffectBase public: Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; enum RootParameterIndex @@ -83,7 +82,6 @@ class BasicEffect::Impl : public EffectBase void Apply(_In_ ID3D12GraphicsCommandList* commandList); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -257,158 +255,150 @@ namespace #include "BasicEffect_PSBasicPixelLighting.inc" #include "BasicEffect_PSBasicPixelLightingTx.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { BasicEffect_VSBasic, sizeof(BasicEffect_VSBasic) }, - { BasicEffect_VSBasicNoFog, sizeof(BasicEffect_VSBasicNoFog) }, - { BasicEffect_VSBasicVc, sizeof(BasicEffect_VSBasicVc) }, - { BasicEffect_VSBasicVcNoFog, sizeof(BasicEffect_VSBasicVcNoFog) }, - { BasicEffect_VSBasicTx, sizeof(BasicEffect_VSBasicTx) }, - { BasicEffect_VSBasicTxNoFog, sizeof(BasicEffect_VSBasicTxNoFog) }, - { BasicEffect_VSBasicTxVc, sizeof(BasicEffect_VSBasicTxVc) }, - { BasicEffect_VSBasicTxVcNoFog, sizeof(BasicEffect_VSBasicTxVcNoFog) }, - - { BasicEffect_VSBasicVertexLighting, sizeof(BasicEffect_VSBasicVertexLighting) }, - { BasicEffect_VSBasicVertexLightingVc, sizeof(BasicEffect_VSBasicVertexLightingVc) }, - { BasicEffect_VSBasicVertexLightingTx, sizeof(BasicEffect_VSBasicVertexLightingTx) }, - { BasicEffect_VSBasicVertexLightingTxVc, sizeof(BasicEffect_VSBasicVertexLightingTxVc) }, - - { BasicEffect_VSBasicPixelLighting, sizeof(BasicEffect_VSBasicPixelLighting) }, - { BasicEffect_VSBasicPixelLightingVc, sizeof(BasicEffect_VSBasicPixelLightingVc) }, - { BasicEffect_VSBasicPixelLightingTx, sizeof(BasicEffect_VSBasicPixelLightingTx) }, - { BasicEffect_VSBasicPixelLightingTxVc, sizeof(BasicEffect_VSBasicPixelLightingTxVc) }, - - { BasicEffect_VSBasicVertexLightingBn, sizeof(BasicEffect_VSBasicVertexLightingBn) }, - { BasicEffect_VSBasicVertexLightingVcBn, sizeof(BasicEffect_VSBasicVertexLightingVcBn) }, - { BasicEffect_VSBasicVertexLightingTxBn, sizeof(BasicEffect_VSBasicVertexLightingTxBn) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { BasicEffect_VSBasic, sizeof(BasicEffect_VSBasic) }, + { BasicEffect_VSBasicNoFog, sizeof(BasicEffect_VSBasicNoFog) }, + { BasicEffect_VSBasicVc, sizeof(BasicEffect_VSBasicVc) }, + { BasicEffect_VSBasicVcNoFog, sizeof(BasicEffect_VSBasicVcNoFog) }, + { BasicEffect_VSBasicTx, sizeof(BasicEffect_VSBasicTx) }, + { BasicEffect_VSBasicTxNoFog, sizeof(BasicEffect_VSBasicTxNoFog) }, + { BasicEffect_VSBasicTxVc, sizeof(BasicEffect_VSBasicTxVc) }, + { BasicEffect_VSBasicTxVcNoFog, sizeof(BasicEffect_VSBasicTxVcNoFog) }, + + { BasicEffect_VSBasicVertexLighting, sizeof(BasicEffect_VSBasicVertexLighting) }, + { BasicEffect_VSBasicVertexLightingVc, sizeof(BasicEffect_VSBasicVertexLightingVc) }, + { BasicEffect_VSBasicVertexLightingTx, sizeof(BasicEffect_VSBasicVertexLightingTx) }, + { BasicEffect_VSBasicVertexLightingTxVc, sizeof(BasicEffect_VSBasicVertexLightingTxVc) }, + + { BasicEffect_VSBasicPixelLighting, sizeof(BasicEffect_VSBasicPixelLighting) }, + { BasicEffect_VSBasicPixelLightingVc, sizeof(BasicEffect_VSBasicPixelLightingVc) }, + { BasicEffect_VSBasicPixelLightingTx, sizeof(BasicEffect_VSBasicPixelLightingTx) }, + { BasicEffect_VSBasicPixelLightingTxVc, sizeof(BasicEffect_VSBasicPixelLightingTxVc) }, + + { BasicEffect_VSBasicVertexLightingBn, sizeof(BasicEffect_VSBasicVertexLightingBn) }, + { BasicEffect_VSBasicVertexLightingVcBn, sizeof(BasicEffect_VSBasicVertexLightingVcBn) }, + { BasicEffect_VSBasicVertexLightingTxBn, sizeof(BasicEffect_VSBasicVertexLightingTxBn) }, { BasicEffect_VSBasicVertexLightingTxVcBn, sizeof(BasicEffect_VSBasicVertexLightingTxVcBn) }, - { BasicEffect_VSBasicPixelLightingBn, sizeof(BasicEffect_VSBasicPixelLightingBn) }, - { BasicEffect_VSBasicPixelLightingVcBn, sizeof(BasicEffect_VSBasicPixelLightingVcBn) }, - { BasicEffect_VSBasicPixelLightingTxBn, sizeof(BasicEffect_VSBasicPixelLightingTxBn) }, - { BasicEffect_VSBasicPixelLightingTxVcBn, sizeof(BasicEffect_VSBasicPixelLightingTxVcBn) }, + { BasicEffect_VSBasicPixelLightingBn, sizeof(BasicEffect_VSBasicPixelLightingBn) }, + { BasicEffect_VSBasicPixelLightingVcBn, sizeof(BasicEffect_VSBasicPixelLightingVcBn) }, + { BasicEffect_VSBasicPixelLightingTxBn, sizeof(BasicEffect_VSBasicPixelLightingTxBn) }, + { BasicEffect_VSBasicPixelLightingTxVcBn, sizeof(BasicEffect_VSBasicPixelLightingTxVcBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // basic - 1, // no fog - 2, // vertex color - 3, // vertex color, no fog - 4, // texture - 5, // texture, no fog - 6, // texture + vertex color - 7, // texture + vertex color, no fog - - 8, // vertex lighting - 8, // vertex lighting, no fog - 9, // vertex lighting + vertex color - 9, // vertex lighting + vertex color, no fog - 10, // vertex lighting + texture - 10, // vertex lighting + texture, no fog - 11, // vertex lighting + texture + vertex color - 11, // vertex lighting + texture + vertex color, no fog - - 12, // pixel lighting - 12, // pixel lighting, no fog - 13, // pixel lighting + vertex color - 13, // pixel lighting + vertex color, no fog - 14, // pixel lighting + texture - 14, // pixel lighting + texture, no fog - 15, // pixel lighting + texture + vertex color - 15, // pixel lighting + texture + vertex color, no fog - - 16, // vertex lighting (biased vertex normals) - 16, // vertex lighting (biased vertex normals), no fog - 17, // vertex lighting (biased vertex normals) + vertex color - 17, // vertex lighting (biased vertex normals) + vertex color, no fog - 18, // vertex lighting (biased vertex normals) + texture - 18, // vertex lighting (biased vertex normals) + texture, no fog - 19, // vertex lighting (biased vertex normals) + texture + vertex color - 19, // vertex lighting (biased vertex normals) + texture + vertex color, no fog - - 20, // pixel lighting (biased vertex normals) - 20, // pixel lighting (biased vertex normals), no fog - 21, // pixel lighting (biased vertex normals) + vertex color - 21, // pixel lighting (biased vertex normals) + vertex color, no fog - 22, // pixel lighting (biased vertex normals) + texture - 22, // pixel lighting (biased vertex normals) + texture, no fog - 23, // pixel lighting (biased vertex normals) + texture + vertex color - 23, // pixel lighting (biased vertex normals) + texture + vertex color, no fog +const int EffectBase::VertexShaderIndices[] = { + 0, // basic + 1, // no fog + 2, // vertex color + 3, // vertex color, no fog + 4, // texture + 5, // texture, no fog + 6, // texture + vertex color + 7, // texture + vertex color, no fog + + 8, // vertex lighting + 8, // vertex lighting, no fog + 9, // vertex lighting + vertex color + 9, // vertex lighting + vertex color, no fog + 10, // vertex lighting + texture + 10, // vertex lighting + texture, no fog + 11, // vertex lighting + texture + vertex color + 11, // vertex lighting + texture + vertex color, no fog + + 12, // pixel lighting + 12, // pixel lighting, no fog + 13, // pixel lighting + vertex color + 13, // pixel lighting + vertex color, no fog + 14, // pixel lighting + texture + 14, // pixel lighting + texture, no fog + 15, // pixel lighting + texture + vertex color + 15, // pixel lighting + texture + vertex color, no fog + + 16, // vertex lighting (biased vertex normals) + 16, // vertex lighting (biased vertex normals), no fog + 17, // vertex lighting (biased vertex normals) + vertex color + 17, // vertex lighting (biased vertex normals) + vertex color, no fog + 18, // vertex lighting (biased vertex normals) + texture + 18, // vertex lighting (biased vertex normals) + texture, no fog + 19, // vertex lighting (biased vertex normals) + texture + vertex color + 19, // vertex lighting (biased vertex normals) + texture + vertex color, no fog + + 20, // pixel lighting (biased vertex normals) + 20, // pixel lighting (biased vertex normals), no fog + 21, // pixel lighting (biased vertex normals) + vertex color + 21, // pixel lighting (biased vertex normals) + vertex color, no fog + 22, // pixel lighting (biased vertex normals) + texture + 22, // pixel lighting (biased vertex normals) + texture, no fog + 23, // pixel lighting (biased vertex normals) + texture + vertex color + 23, // pixel lighting (biased vertex normals) + texture + vertex color, no fog }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { BasicEffect_PSBasic, sizeof(BasicEffect_PSBasic) }, - { BasicEffect_PSBasicNoFog, sizeof(BasicEffect_PSBasicNoFog) }, - { BasicEffect_PSBasicTx, sizeof(BasicEffect_PSBasicTx) }, - { BasicEffect_PSBasicTxNoFog, sizeof(BasicEffect_PSBasicTxNoFog) }, - - { BasicEffect_PSBasicVertexLighting, sizeof(BasicEffect_PSBasicVertexLighting) }, - { BasicEffect_PSBasicVertexLightingNoFog, sizeof(BasicEffect_PSBasicVertexLightingNoFog) }, - { BasicEffect_PSBasicVertexLightingTx, sizeof(BasicEffect_PSBasicVertexLightingTx) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { BasicEffect_PSBasic, sizeof(BasicEffect_PSBasic) }, + { BasicEffect_PSBasicNoFog, sizeof(BasicEffect_PSBasicNoFog) }, + { BasicEffect_PSBasicTx, sizeof(BasicEffect_PSBasicTx) }, + { BasicEffect_PSBasicTxNoFog, sizeof(BasicEffect_PSBasicTxNoFog) }, + + { BasicEffect_PSBasicVertexLighting, sizeof(BasicEffect_PSBasicVertexLighting) }, + { BasicEffect_PSBasicVertexLightingNoFog, sizeof(BasicEffect_PSBasicVertexLightingNoFog) }, + { BasicEffect_PSBasicVertexLightingTx, sizeof(BasicEffect_PSBasicVertexLightingTx) }, { BasicEffect_PSBasicVertexLightingTxNoFog, sizeof(BasicEffect_PSBasicVertexLightingTxNoFog) }, - { BasicEffect_PSBasicPixelLighting, sizeof(BasicEffect_PSBasicPixelLighting) }, - { BasicEffect_PSBasicPixelLightingTx, sizeof(BasicEffect_PSBasicPixelLightingTx) }, + { BasicEffect_PSBasicPixelLighting, sizeof(BasicEffect_PSBasicPixelLighting) }, + { BasicEffect_PSBasicPixelLightingTx, sizeof(BasicEffect_PSBasicPixelLightingTx) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // basic - 1, // no fog - 0, // vertex color - 1, // vertex color, no fog - 2, // texture - 3, // texture, no fog - 2, // texture + vertex color - 3, // texture + vertex color, no fog - - 4, // vertex lighting - 5, // vertex lighting, no fog - 4, // vertex lighting + vertex color - 5, // vertex lighting + vertex color, no fog - 6, // vertex lighting + texture - 7, // vertex lighting + texture, no fog - 6, // vertex lighting + texture + vertex color - 7, // vertex lighting + texture + vertex color, no fog - - 8, // pixel lighting - 8, // pixel lighting, no fog - 8, // pixel lighting + vertex color - 8, // pixel lighting + vertex color, no fog - 9, // pixel lighting + texture - 9, // pixel lighting + texture, no fog - 9, // pixel lighting + texture + vertex color - 9, // pixel lighting + texture + vertex color, no fog - - 4, // vertex lighting (biased vertex normals) - 5, // vertex lighting (biased vertex normals), no fog - 4, // vertex lighting (biased vertex normals) + vertex color - 5, // vertex lighting (biased vertex normals) + vertex color, no fog - 6, // vertex lighting (biased vertex normals) + texture - 7, // vertex lighting (biased vertex normals) + texture, no fog - 6, // vertex lighting (biased vertex normals) + texture + vertex color - 7, // vertex lighting (biased vertex normals) + texture + vertex color, no fog - - 8, // pixel lighting (biased vertex normals) - 8, // pixel lighting (biased vertex normals), no fog - 8, // pixel lighting (biased vertex normals) + vertex color - 8, // pixel lighting (biased vertex normals) + vertex color, no fog - 9, // pixel lighting (biased vertex normals) + texture - 9, // pixel lighting (biased vertex normals) + texture, no fog - 9, // pixel lighting (biased vertex normals) + texture + vertex color - 9, // pixel lighting (biased vertex normals) + texture + vertex color, no fog +const int EffectBase::PixelShaderIndices[] = { + 0, // basic + 1, // no fog + 0, // vertex color + 1, // vertex color, no fog + 2, // texture + 3, // texture, no fog + 2, // texture + vertex color + 3, // texture + vertex color, no fog + + 4, // vertex lighting + 5, // vertex lighting, no fog + 4, // vertex lighting + vertex color + 5, // vertex lighting + vertex color, no fog + 6, // vertex lighting + texture + 7, // vertex lighting + texture, no fog + 6, // vertex lighting + texture + vertex color + 7, // vertex lighting + texture + vertex color, no fog + + 8, // pixel lighting + 8, // pixel lighting, no fog + 8, // pixel lighting + vertex color + 8, // pixel lighting + vertex color, no fog + 9, // pixel lighting + texture + 9, // pixel lighting + texture, no fog + 9, // pixel lighting + texture + vertex color + 9, // pixel lighting + texture + vertex color, no fog + + 4, // vertex lighting (biased vertex normals) + 5, // vertex lighting (biased vertex normals), no fog + 4, // vertex lighting (biased vertex normals) + vertex color + 5, // vertex lighting (biased vertex normals) + vertex color, no fog + 6, // vertex lighting (biased vertex normals) + texture + 7, // vertex lighting (biased vertex normals) + texture, no fog + 6, // vertex lighting (biased vertex normals) + texture + vertex color + 7, // vertex lighting (biased vertex normals) + texture + vertex color, no fog + + 8, // pixel lighting (biased vertex normals) + 8, // pixel lighting (biased vertex normals), no fog + 8, // pixel lighting (biased vertex normals) + vertex color + 8, // pixel lighting (biased vertex normals) + vertex color, no fog + 9, // pixel lighting (biased vertex normals) + texture + 9, // pixel lighting (biased vertex normals) + texture, no fog + 9, // pixel lighting (biased vertex normals) + texture + vertex color + 9, // pixel lighting (biased vertex normals) + texture + vertex color, no fog }; #pragma endregion @@ -416,20 +406,22 @@ const int EffectBase::PixelShaderIndices[] = template<> SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - // Constructor. -BasicEffect::Impl::Impl( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) +BasicEffect::Impl::Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription) : EffectBase(device), - texture{}, - sampler{} -{ - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == BasicEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == BasicEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); + texture{}, + sampler{} +{ + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) + == BasicEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == BasicEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == BasicEffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) + == BasicEffectTraits::ShaderPermutationCount, + "array/max mismatch"); if (effectFlags & EffectFlags::Instancing) { @@ -437,23 +429,23 @@ BasicEffect::Impl::Impl( throw std::invalid_argument("Instancing effect flag is invalid"); } - lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); + lights.InitializeConstants(constants.specularColorAndPower, + constants.lightDirection, + constants.lightDiffuseColor, + constants.lightSpecularColor); - fog.enabled = (effectFlags & EffectFlags::Fog) != 0; + fog.enabled = (effectFlags & EffectFlags::Fog) != 0; lightingEnabled = (effectFlags & EffectFlags::Lighting) != 0; - textureEnabled = (effectFlags & EffectFlags::Texture) != 0; + textureEnabled = (effectFlags & EffectFlags::Texture) != 0; // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; // Create root parameters and initialize first (constants) @@ -500,8 +492,7 @@ BasicEffect::Impl::Impl( assert(pi >= 0 && pi < BasicEffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < BasicEffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -510,7 +501,6 @@ BasicEffect::Impl::Impl( SetDebugObjectName(mPipelineState.Get(), L"BasicEffect"); } - int BasicEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const noexcept { int permutation = 0; @@ -555,14 +545,20 @@ int BasicEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const n return permutation; } - // Sets our state onto the D3D device. void BasicEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { // Compute derived parameter values. matrices.SetConstants(dirtyFlags, constants.worldViewProj); fog.SetConstants(dirtyFlags, matrices.worldView, constants.fogVector); - lights.SetConstants(dirtyFlags, matrices, constants.world, constants.worldInverseTranspose, constants.eyePosition, constants.diffuseColor, constants.emissiveColor, lightingEnabled); + lights.SetConstants(dirtyFlags, + matrices, + constants.world, + constants.worldInverseTranspose, + constants.eyePosition, + constants.diffuseColor, + constants.emissiveColor, + lightingEnabled); UpdateConstants(); @@ -578,7 +574,8 @@ void BasicEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) throw std::runtime_error("BasicEffect"); } - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heaps. commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSampler, sampler); } @@ -590,21 +587,15 @@ void BasicEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - // Public constructor. -BasicEffect::BasicEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) +BasicEffect::BasicEffect(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription) : pImpl(std::make_unique(device, effectFlags, pipelineDescription)) {} - // Move constructor. -BasicEffect::BasicEffect(BasicEffect&&) noexcept = default; -BasicEffect& BasicEffect::operator= (BasicEffect&&) noexcept = default; -BasicEffect::~BasicEffect() = default; - +BasicEffect::BasicEffect(BasicEffect&&) noexcept = default; +BasicEffect& BasicEffect::operator=(BasicEffect&&) noexcept = default; +BasicEffect::~BasicEffect() = default; // IEffect methods void BasicEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -612,7 +603,6 @@ void BasicEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings void XM_CALLCONV BasicEffect::SetWorld(FXMMATRIX value) { @@ -621,7 +611,6 @@ void XM_CALLCONV BasicEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::FogVector; } - void XM_CALLCONV BasicEffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -629,7 +618,6 @@ void XM_CALLCONV BasicEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; } - void XM_CALLCONV BasicEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -637,17 +625,16 @@ void XM_CALLCONV BasicEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV BasicEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; - pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; + pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition + | EffectDirtyFlags::FogVector; } - // Material settings void XM_CALLCONV BasicEffect::SetDiffuseColor(FXMVECTOR value) { @@ -656,7 +643,6 @@ void XM_CALLCONV BasicEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV BasicEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -664,7 +650,6 @@ void XM_CALLCONV BasicEffect::SetEmissiveColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV BasicEffect::SetSpecularColor(FXMVECTOR value) { // Set xyz to new value, but preserve existing w (specular power). @@ -673,7 +658,6 @@ void XM_CALLCONV BasicEffect::SetSpecularColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void BasicEffect::SetSpecularPower(float value) { // Set w to new value, but preserve existing xyz (specular color). @@ -682,7 +666,6 @@ void BasicEffect::SetSpecularPower(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void BasicEffect::DisableSpecular() { // Set specular color to black, power to 1 @@ -693,7 +676,6 @@ void BasicEffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void BasicEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -701,16 +683,14 @@ void BasicEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV BasicEffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->lights.diffuseColor = value; - pImpl->lights.alpha = XMVectorGetW(value); + pImpl->lights.alpha = XMVectorGetW(value); pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - // Light settings void XM_CALLCONV BasicEffect::SetAmbientLightColor(FXMVECTOR value) { @@ -719,13 +699,12 @@ void XM_CALLCONV BasicEffect::SetAmbientLightColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void BasicEffect::SetLightEnabled(int whichLight, bool value) { - pImpl->dirtyFlags |= pImpl->lights.SetLightEnabled(whichLight, value, pImpl->constants.lightDiffuseColor, pImpl->constants.lightSpecularColor); + pImpl->dirtyFlags + |= pImpl->lights.SetLightEnabled(whichLight, value, pImpl->constants.lightDiffuseColor, pImpl->constants.lightSpecularColor); } - void XM_CALLCONV BasicEffect::SetLightDirection(int whichLight, FXMVECTOR value) { EffectLights::ValidateLightIndex(whichLight); @@ -735,25 +714,21 @@ void XM_CALLCONV BasicEffect::SetLightDirection(int whichLight, FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV BasicEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR value) { pImpl->dirtyFlags |= pImpl->lights.SetLightDiffuseColor(whichLight, value, pImpl->constants.lightDiffuseColor); } - void XM_CALLCONV BasicEffect::SetLightSpecularColor(int whichLight, FXMVECTOR value) { pImpl->dirtyFlags |= pImpl->lights.SetLightSpecularColor(whichLight, value, pImpl->constants.lightSpecularColor); } - void BasicEffect::EnableDefaultLighting() { EffectLights::EnableDefaultLighting(this); } - // Fog settings. void BasicEffect::SetFogStart(float value) { @@ -762,7 +737,6 @@ void BasicEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void BasicEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -770,7 +744,6 @@ void BasicEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV BasicEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -778,7 +751,6 @@ void XM_CALLCONV BasicEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void BasicEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { diff --git a/Src/BasicPostProcess.cpp b/Src/BasicPostProcess.cpp index 6c9102cc..6043ea56 100644 --- a/Src/BasicPostProcess.cpp +++ b/Src/BasicPostProcess.cpp @@ -28,7 +28,7 @@ namespace constexpr int c_MaxSamples = 16; constexpr int Dirty_ConstantBuffer = 0x01; - constexpr int Dirty_Parameters = 0x02; + constexpr int Dirty_Parameters = 0x02; constexpr int RootSignatureCount = 2; @@ -46,7 +46,7 @@ namespace { return expf(-(x * x + y * y) / (2 * rho * rho)) / sqrtf(2 * XM_PI * rho * rho); } -} +} // namespace #pragma region Shaders // Include the precompiled shader code. @@ -101,26 +101,24 @@ namespace #include "PostProcess_PSBloomExtract.inc" #include "PostProcess_PSBloomBlur.inc" #endif -} +} // namespace namespace { - const D3D12_SHADER_BYTECODE vertexShader[] = - { - { PostProcess_VSQuadNoCB, sizeof(PostProcess_VSQuadNoCB) }, - { PostProcess_VSQuad, sizeof(PostProcess_VSQuad) }, + const D3D12_SHADER_BYTECODE vertexShader[] = { + { PostProcess_VSQuadNoCB, sizeof(PostProcess_VSQuadNoCB) }, + { PostProcess_VSQuad, sizeof(PostProcess_VSQuad) }, }; - const D3D12_SHADER_BYTECODE pixelShaders[] = - { - { PostProcess_PSCopy, sizeof(PostProcess_PSCopy) }, - { PostProcess_PSMonochrome, sizeof(PostProcess_PSMonochrome) }, - { PostProcess_PSSepia, sizeof(PostProcess_PSSepia) }, - { PostProcess_PSDownScale2x2, sizeof(PostProcess_PSDownScale2x2) }, - { PostProcess_PSDownScale4x4, sizeof(PostProcess_PSDownScale4x4) }, - { PostProcess_PSGaussianBlur5x5, sizeof(PostProcess_PSGaussianBlur5x5) }, - { PostProcess_PSBloomExtract, sizeof(PostProcess_PSBloomExtract) }, - { PostProcess_PSBloomBlur, sizeof(PostProcess_PSBloomBlur) }, + const D3D12_SHADER_BYTECODE pixelShaders[] = { + { PostProcess_PSCopy, sizeof(PostProcess_PSCopy) }, + { PostProcess_PSMonochrome, sizeof(PostProcess_PSMonochrome) }, + { PostProcess_PSSepia, sizeof(PostProcess_PSSepia) }, + { PostProcess_PSDownScale2x2, sizeof(PostProcess_PSDownScale2x2) }, + { PostProcess_PSDownScale4x4, sizeof(PostProcess_PSDownScale4x4) }, + { PostProcess_PSGaussianBlur5x5, sizeof(PostProcess_PSGaussianBlur5x5) }, + { PostProcess_PSBloomExtract, sizeof(PostProcess_PSBloomExtract) }, + { PostProcess_PSBloomBlur, sizeof(PostProcess_PSBloomBlur) }, }; static_assert(static_cast(std::size(pixelShaders)) == BasicPostProcess::Effect_Max, "array/max mismatch"); @@ -131,14 +129,14 @@ namespace public: DeviceResources(_In_ ID3D12Device* device) noexcept : mDevice(device), - mRootSignature{}, - mMutex{} + mRootSignature{}, + mMutex{} {} - DeviceResources(const DeviceResources&) = delete; + DeviceResources(const DeviceResources&) = delete; DeviceResources& operator=(const DeviceResources&) = delete; - DeviceResources(DeviceResources&&) = delete; + DeviceResources(DeviceResources&&) = delete; DeviceResources& operator=(DeviceResources&&) = delete; ID3D12RootSignature* GetRootSignature(int slot, const D3D12_ROOT_SIGNATURE_DESC& desc) @@ -146,7 +144,9 @@ namespace assert(slot >= 0 && slot < RootSignatureCount); _Analysis_assume_(slot >= 0 && slot < RootSignatureCount); - return DemandCreate(mRootSignature[slot], mMutex, [&](ID3D12RootSignature** pResult) noexcept -> HRESULT + return DemandCreate(mRootSignature[slot], + mMutex, + [&](ID3D12RootSignature** pResult) noexcept -> HRESULT { HRESULT hr = CreateRootSignature(mDevice.Get(), &desc, pResult); @@ -164,7 +164,7 @@ namespace ComPtr mRootSignature[RootSignatureCount]; std::mutex mMutex; }; -} +} // namespace #pragma endregion class BasicPostProcess::Impl : public AlignedNew @@ -172,10 +172,10 @@ class BasicPostProcess::Impl : public AlignedNew public: Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect ifx); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; void Process(_In_ ID3D12GraphicsCommandList* commandList); @@ -190,25 +190,25 @@ class BasicPostProcess::Impl : public AlignedNew }; // Fields. - BasicPostProcess::Effect fx; - PostProcessConstants constants; - D3D12_GPU_DESCRIPTOR_HANDLE texture; - unsigned texWidth; - unsigned texHeight; - float guassianMultiplier; - float bloomSize; - float bloomBrightness; - float bloomThreshold; - bool bloomHorizontal; + BasicPostProcess::Effect fx; + PostProcessConstants constants; + D3D12_GPU_DESCRIPTOR_HANDLE texture; + unsigned texWidth; + unsigned texHeight; + float guassianMultiplier; + float bloomSize; + float bloomBrightness; + float bloomThreshold; + bool bloomHorizontal; private: - bool mUseConstants; - int mDirtyFlags; + bool mUseConstants; + int mDirtyFlags; - void DownScale2x2(); - void DownScale4x4(); - void GaussianBlur5x5(float multiplier); - void Bloom(bool horizontal, float size, float brightness); + void DownScale2x2(); + void DownScale4x4(); + void GaussianBlur5x5(float multiplier); + void Bloom(bool horizontal, float size, float brightness); // D3D constant buffer holds a copy of the same data as the public 'constants' field. GraphicsResource mConstantBuffer; @@ -225,24 +225,22 @@ class BasicPostProcess::Impl : public AlignedNew static SharedResourcePool deviceResourcesPool; }; - // Global pool of per-device BasicPostProcess resources. SharedResourcePool BasicPostProcess::Impl::deviceResourcesPool; - // Constructor. BasicPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect ifx) : fx(ifx), - constants{}, - texture{}, - texWidth(0), - texHeight(0), - guassianMultiplier(1.f), - bloomSize(1.f), - bloomBrightness(1.f), - bloomThreshold(0.25f), - bloomHorizontal(true), - mDirtyFlags(INT_MAX) + constants{}, + texture{}, + texWidth(0), + texHeight(0), + guassianMultiplier(1.f), + bloomSize(1.f), + bloomBrightness(1.f), + bloomThreshold(0.25f), + bloomHorizontal(true), + mDirtyFlags(INT_MAX) { if (ifx >= Effect_Max) throw std::invalid_argument("Effect not defined"); @@ -261,29 +259,23 @@ BasicPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& mUseConstants = false; break; - default: - mUseConstants = true; - break; + default: mUseConstants = true; break; } // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; const CD3DX12_DESCRIPTOR_RANGE textureSRVs(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); // Same as CommonStates::StaticLinearClamp - const CD3DX12_STATIC_SAMPLER_DESC sampler( - 0, // register + const CD3DX12_STATIC_SAMPLER_DESC sampler(0, // register D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -331,17 +323,11 @@ BasicPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE); - psd.CreatePipelineState( - device, - mRootSignature, - vertexShader[mUseConstants ? 1 : 0], - pixelShaders[ifx], - mPipelineState.GetAddressOf()); + psd.CreatePipelineState(device, mRootSignature, vertexShader[mUseConstants ? 1 : 0], pixelShaders[ifx], mPipelineState.GetAddressOf()); SetDebugObjectName(mPipelineState.Get(), L"BasicPostProcess"); } - // Sets our state onto the D3D device. void BasicPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList) { @@ -366,28 +352,17 @@ void BasicPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList switch (fx) { - case DownScale_2x2: - DownScale2x2(); - break; + case DownScale_2x2: DownScale2x2(); break; - case DownScale_4x4: - DownScale4x4(); - break; + case DownScale_4x4: DownScale4x4(); break; - case GaussianBlur_5x5: - GaussianBlur5x5(guassianMultiplier); - break; + case GaussianBlur_5x5: GaussianBlur5x5(guassianMultiplier); break; - case BloomExtract: - constants.sampleWeights[0] = XMVectorReplicate(bloomThreshold); - break; + case BloomExtract: constants.sampleWeights[0] = XMVectorReplicate(bloomThreshold); break; - case BloomBlur: - Bloom(bloomHorizontal, bloomSize, bloomBrightness); - break; + case BloomBlur: Bloom(bloomHorizontal, bloomSize, bloomBrightness); break; - default: - break; + default: break; } } @@ -408,7 +383,6 @@ void BasicPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList commandList->DrawInstanced(3, 1, 0, 0); } - void BasicPostProcess::Impl::DownScale2x2() { mUseConstants = true; @@ -435,7 +409,6 @@ void BasicPostProcess::Impl::DownScale2x2() } } - void BasicPostProcess::Impl::DownScale4x4() { mUseConstants = true; @@ -460,10 +433,8 @@ void BasicPostProcess::Impl::DownScale4x4() ++ptr; } } - } - void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) { mUseConstants = true; @@ -476,10 +447,10 @@ void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) const float tu = 1.0f / float(texWidth); const float tv = 1.0f / float(texHeight); - float totalWeight = 0.0f; - size_t index = 0; - auto offsets = reinterpret_cast(constants.sampleOffsets); - auto weights = constants.sampleWeights; + float totalWeight = 0.0f; + size_t index = 0; + auto offsets = reinterpret_cast(constants.sampleOffsets); + auto weights = constants.sampleWeights; for (int x = -2; x <= 2; ++x) { for (int y = -2; y <= 2; ++y) @@ -497,7 +468,7 @@ void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) offsets[index].z = 0.0f; offsets[index].w = 0.0f; - const float g = GaussianDistribution(float(x), float(y), 1.0f); + const float g = GaussianDistribution(float(x), float(y), 1.0f); weights[index] = XMVectorReplicate(g); totalWeight += XMVectorGetX(weights[index]); @@ -511,16 +482,15 @@ void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) // changed when the blur occurs. An optional multiplier variable is used to // add or remove image intensity during the blur. const XMVECTOR vtw = XMVectorReplicate(totalWeight); - const XMVECTOR vm = XMVectorReplicate(multiplier); + const XMVECTOR vm = XMVectorReplicate(multiplier); for (size_t i = 0; i < index; ++i) { const XMVECTOR w = XMVectorDivide(weights[i], vtw); - weights[i] = XMVectorMultiply(w, vm); + weights[i] = XMVectorMultiply(w, vm); } } - -void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightness) +void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightness) { mUseConstants = true; @@ -545,14 +515,14 @@ void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightnes // Fill the center texel float weight = brightness * GaussianDistribution(0, 0, size); - weights[0] = XMFLOAT4(weight, weight, weight, 1.0f); + weights[0] = XMFLOAT4(weight, weight, weight, 1.0f); offsets[0].x = offsets[0].y = offsets[0].z = offsets[0].w = 0.f; // Fill the first half for (int i = 1; i < 8; ++i) { // Get the Gaussian intensity for this offset - weight = brightness * GaussianDistribution(float(i), 0, size); + weight = brightness * GaussianDistribution(float(i), 0, size); weights[i] = XMFLOAT4(weight, weight, weight, 1.0f); offsets[i] = XMFLOAT4(float(i) * tu, float(i) * tv, 0.f, 0.f); } @@ -565,18 +535,15 @@ void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightnes } } - // Public constructor. BasicPostProcess::BasicPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx) : pImpl(std::make_unique(device, rtState, fx)) {} - // Move constructor. -BasicPostProcess::BasicPostProcess(BasicPostProcess&&) noexcept = default; -BasicPostProcess& BasicPostProcess::operator= (BasicPostProcess&&) noexcept = default; -BasicPostProcess::~BasicPostProcess() = default; - +BasicPostProcess::BasicPostProcess(BasicPostProcess&&) noexcept = default; +BasicPostProcess& BasicPostProcess::operator=(BasicPostProcess&&) noexcept = default; +BasicPostProcess::~BasicPostProcess() = default; // IPostProcess methods. void BasicPostProcess::Process(_In_ ID3D12GraphicsCommandList* commandList) @@ -584,7 +551,6 @@ void BasicPostProcess::Process(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Process(commandList); } - // Properties void BasicPostProcess::SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, _In_opt_ ID3D12Resource* resource) { @@ -592,13 +558,13 @@ void BasicPostProcess::SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescripto if (resource) { - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const auto desc = resource->GetDesc(); - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *resource->GetDesc(&tmpDesc); - #endif - pImpl->texWidth = static_cast(desc.Width); + const auto& desc = *resource->GetDesc(&tmpDesc); +#endif + pImpl->texWidth = static_cast(desc.Width); pImpl->texHeight = desc.Height; } else @@ -607,24 +573,21 @@ void BasicPostProcess::SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescripto } } - void BasicPostProcess::SetGaussianParameter(float multiplier) { pImpl->guassianMultiplier = multiplier; pImpl->SetDirtyFlag(); } - void BasicPostProcess::SetBloomExtractParameter(float threshold) { pImpl->bloomThreshold = threshold; pImpl->SetDirtyFlag(); } - void BasicPostProcess::SetBloomBlurParameters(bool horizontal, float size, float brightness) { - pImpl->bloomSize = size; + pImpl->bloomSize = size; pImpl->bloomBrightness = brightness; pImpl->bloomHorizontal = horizontal; pImpl->SetDirtyFlag(); diff --git a/Src/Bezier.h b/Src/Bezier.h index 22e954f6..524ca56b 100644 --- a/Src/Bezier.h +++ b/Src/Bezier.h @@ -14,7 +14,6 @@ #include #include - namespace Bezier { // Performs a cubic bezier interpolation between four control points, @@ -22,14 +21,15 @@ namespace Bezier template inline T CubicInterpolate(T const& p1, T const& p2, T const& p3, T const& p4, float t) noexcept { - return p1 * (1 - t) * (1 - t) * (1 - t) + - p2 * 3 * t * (1 - t) * (1 - t) + - p3 * 3 * t * t * (1 - t) + - p4 * t * t * t; + return p1 * (1 - t) * (1 - t) * (1 - t) + p2 * 3 * t * (1 - t) * (1 - t) + p3 * 3 * t * t * (1 - t) + p4 * t * t * t; } template<> - inline DirectX::XMVECTOR CubicInterpolate(DirectX::XMVECTOR const& p1, DirectX::XMVECTOR const& p2, DirectX::XMVECTOR const& p3, DirectX::XMVECTOR const& p4, float t) noexcept + inline DirectX::XMVECTOR CubicInterpolate(DirectX::XMVECTOR const& p1, + DirectX::XMVECTOR const& p2, + DirectX::XMVECTOR const& p3, + DirectX::XMVECTOR const& p4, + float t) noexcept { using namespace DirectX; @@ -39,26 +39,26 @@ namespace Bezier const XMVECTOR T3 = XMVectorReplicate(t * t * t); XMVECTOR Result = XMVectorMultiply(p1, T0); - Result = XMVectorMultiplyAdd(p2, T1, Result); - Result = XMVectorMultiplyAdd(p3, T2, Result); - Result = XMVectorMultiplyAdd(p4, T3, Result); + Result = XMVectorMultiplyAdd(p2, T1, Result); + Result = XMVectorMultiplyAdd(p3, T2, Result); + Result = XMVectorMultiplyAdd(p4, T3, Result); return Result; } - // Computes the tangent of a cubic bezier curve at the specified time. template inline T CubicTangent(T const& p1, T const& p2, T const& p3, T const& p4, float t) noexcept { - return p1 * (-1 + 2 * t - t * t) + - p2 * (1 - 4 * t + 3 * t * t) + - p3 * (2 * t - 3 * t * t) + - p4 * (t * t); + return p1 * (-1 + 2 * t - t * t) + p2 * (1 - 4 * t + 3 * t * t) + p3 * (2 * t - 3 * t * t) + p4 * (t * t); } template<> - inline DirectX::XMVECTOR CubicTangent(DirectX::XMVECTOR const& p1, DirectX::XMVECTOR const& p2, DirectX::XMVECTOR const& p3, DirectX::XMVECTOR const& p4, float t) noexcept + inline DirectX::XMVECTOR CubicTangent(DirectX::XMVECTOR const& p1, + DirectX::XMVECTOR const& p2, + DirectX::XMVECTOR const& p3, + DirectX::XMVECTOR const& p4, + float t) noexcept { using namespace DirectX; @@ -68,19 +68,19 @@ namespace Bezier const XMVECTOR T3 = XMVectorReplicate(t * t); XMVECTOR Result = XMVectorMultiply(p1, T0); - Result = XMVectorMultiplyAdd(p2, T1, Result); - Result = XMVectorMultiplyAdd(p3, T2, Result); - Result = XMVectorMultiplyAdd(p4, T3, Result); + Result = XMVectorMultiplyAdd(p2, T1, Result); + Result = XMVectorMultiplyAdd(p3, T2, Result); + Result = XMVectorMultiplyAdd(p4, T3, Result); return Result; } - // Creates vertices for a patch that is tessellated at the specified level. // Calls the specified outputVertex function for each generated vertex, // passing the position, normal, and texture coordinate as parameters. template - void CreatePatchVertices(_In_reads_(16) const DirectX::XMVECTOR patch[16], size_t tessellation, bool isMirrored, TOutputFunc outputVertex) + void + CreatePatchVertices(_In_reads_(16) const DirectX::XMVECTOR patch[16], size_t tessellation, bool isMirrored, TOutputFunc outputVertex) { using namespace DirectX; @@ -155,7 +155,6 @@ namespace Bezier } } - // Creates indices for a patch that is tessellated at the specified level. // Calls the specified outputIndex function for each generated index value. template @@ -168,8 +167,7 @@ namespace Bezier for (size_t j = 0; j < tessellation; j++) { // Make a list of six index values (two triangles). - std::array indices = - { + std::array indices = { i * stride + j, (i + 1) * stride + j, (i + 1) * stride + j + 1, @@ -190,4 +188,4 @@ namespace Bezier } } } -} +} // namespace Bezier diff --git a/Src/BinaryReader.cpp b/Src/BinaryReader.cpp index 0fbc91fe..ccda5b72 100644 --- a/Src/BinaryReader.cpp +++ b/Src/BinaryReader.cpp @@ -14,19 +14,17 @@ using namespace DirectX; - // Constructor reads from the filesystem. -BinaryReader::BinaryReader(_In_z_ wchar_t const* fileName) noexcept(false) : - mPos(nullptr), - mEnd(nullptr) +BinaryReader::BinaryReader(_In_z_ wchar_t const* fileName) noexcept(false) + : mPos(nullptr), + mEnd(nullptr) { size_t dataSize; HRESULT hr = ReadEntireFile(fileName, mOwnedData, &dataSize); if (FAILED(hr)) { - DebugTrace("ERROR: BinaryReader failed (%08X) to load '%ls'\n", - static_cast(hr), fileName); + DebugTrace("ERROR: BinaryReader failed (%08X) to load '%ls'\n", static_cast(hr), fileName); throw std::runtime_error("BinaryReader"); } @@ -34,19 +32,14 @@ BinaryReader::BinaryReader(_In_z_ wchar_t const* fileName) noexcept(false) : mEnd = mOwnedData.get() + dataSize; } - // Constructor reads from an existing memory buffer. -BinaryReader::BinaryReader(_In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize) noexcept : - mPos(dataBlob), - mEnd(dataBlob + dataSize) +BinaryReader::BinaryReader(_In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize) noexcept + : mPos(dataBlob), + mEnd(dataBlob + dataSize) {} - // Reads from the filesystem into memory. -HRESULT BinaryReader::ReadEntireFile( - _In_z_ wchar_t const* fileName, - _Inout_ std::unique_ptr& data, - _Out_ size_t* dataSize) +HRESULT BinaryReader::ReadEntireFile(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr& data, _Out_ size_t* dataSize) { if (!fileName || !dataSize) return E_INVALIDARG; @@ -54,10 +47,7 @@ HRESULT BinaryReader::ReadEntireFile( *dataSize = 0; // Open the file. - ScopedHandle hFile(safe_handle(CreateFile2( - fileName, - GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, - nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); if (!hFile) return HRESULT_FROM_WIN32(GetLastError()); diff --git a/Src/BinaryReader.h b/Src/BinaryReader.h index d95146ee..3e107873 100644 --- a/Src/BinaryReader.h +++ b/Src/BinaryReader.h @@ -18,7 +18,6 @@ #include "PlatformHelpers.h" - namespace DirectX { // Helper for reading binary data, either from the filesystem a memory buffer. @@ -29,20 +28,21 @@ namespace DirectX BinaryReader(_In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize) noexcept; BinaryReader(BinaryReader&&) noexcept; - BinaryReader& operator= (BinaryReader&&) noexcept; + BinaryReader& operator=(BinaryReader&&) noexcept; - BinaryReader(BinaryReader const&) = delete; - BinaryReader& operator= (BinaryReader const&) = delete; + BinaryReader(BinaryReader const&) = delete; + BinaryReader& operator=(BinaryReader const&) = delete; // Reads a single value. - template T const& Read() + template + T const& Read() { return *ReadArray(1); } - // Reads an array of values. - template T const* ReadArray(size_t elementCount) + template + T const* ReadArray(size_t elementCount) { static_assert(std::is_standard_layout::value, "Can only read plain-old-data types"); @@ -65,11 +65,9 @@ namespace DirectX return result; } - // Lower level helper reads directly from the filesystem into memory. static HRESULT ReadEntireFile(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr& data, _Out_ size_t* dataSize); - private: // The data currently being read. uint8_t const* mPos; @@ -77,4 +75,4 @@ namespace DirectX std::unique_ptr mOwnedData; }; -} +} // namespace DirectX diff --git a/Src/BufferHelpers.cpp b/Src/BufferHelpers.cpp index 7d4e5ef3..d7bc2fdd 100644 --- a/Src/BufferHelpers.cpp +++ b/Src/BufferHelpers.cpp @@ -14,21 +14,18 @@ #include "LoaderHelpers.h" #include "PlatformHelpers.h" - using namespace DirectX; using Microsoft::WRL::ComPtr; //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateStaticBuffer( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const void* ptr, - size_t count, - size_t stride, - D3D12_RESOURCE_STATES afterState, - ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateStaticBuffer(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const void* ptr, + size_t count, + size_t stride, + D3D12_RESOURCE_STATES afterState, + ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags) noexcept { if (!pBuffer) return E_INVALIDARG; @@ -53,8 +50,7 @@ HRESULT DirectX::CreateStaticBuffer( const CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_DEFAULT); ComPtr res; - HRESULT hr = device->CreateCommittedResource( - &heapProperties, + HRESULT hr = device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, @@ -85,15 +81,12 @@ HRESULT DirectX::CreateStaticBuffer( return S_OK; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateUAVBuffer( - ID3D12Device* device, - uint64_t bufferSize, - ID3D12Resource** pBuffer, - D3D12_RESOURCE_STATES initialState, - D3D12_RESOURCE_FLAGS additionalResFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateUAVBuffer(ID3D12Device* device, + uint64_t bufferSize, + ID3D12Resource** pBuffer, + D3D12_RESOURCE_STATES initialState, + D3D12_RESOURCE_FLAGS additionalResFlags) noexcept { if (!pBuffer) return E_INVALIDARG; @@ -116,8 +109,7 @@ HRESULT DirectX::CreateUAVBuffer( const CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_DEFAULT); ComPtr res; - HRESULT hr = device->CreateCommittedResource( - &heapProperties, + HRESULT hr = device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, initialState, @@ -131,16 +123,13 @@ HRESULT DirectX::CreateUAVBuffer( return S_OK; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateUploadBuffer( - ID3D12Device* device, - const void* ptr, - size_t count, - size_t stride, - ID3D12Resource** pBuffer, - D3D12_RESOURCE_FLAGS resFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateUploadBuffer(ID3D12Device* device, + const void* ptr, + size_t count, + size_t stride, + ID3D12Resource** pBuffer, + D3D12_RESOURCE_FLAGS resFlags) noexcept { if (!pBuffer) return E_INVALIDARG; @@ -165,8 +154,7 @@ HRESULT DirectX::CreateUploadBuffer( const CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_UPLOAD); ComPtr res; - HRESULT hr = device->CreateCommittedResource( - &heapProperties, + HRESULT hr = device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, @@ -178,7 +166,7 @@ HRESULT DirectX::CreateUploadBuffer( if (ptr) { void* mappedPtr = nullptr; - hr = res->Map(0, nullptr, &mappedPtr); + hr = res->Map(0, nullptr, &mappedPtr); if (FAILED(hr)) return hr; @@ -191,18 +179,15 @@ HRESULT DirectX::CreateUploadBuffer( return S_OK; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateTextureFromMemory( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - size_t width, - DXGI_FORMAT format, - const D3D12_SUBRESOURCE_DATA& initData, - ID3D12Resource** texture, - D3D12_RESOURCE_STATES afterState, - D3D12_RESOURCE_FLAGS resFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateTextureFromMemory(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + size_t width, + DXGI_FORMAT format, + const D3D12_SUBRESOURCE_DATA& initData, + ID3D12Resource** texture, + D3D12_RESOURCE_STATES afterState, + D3D12_RESOURCE_FLAGS resFlags) noexcept { if (!texture) return E_INVALIDARG; @@ -225,8 +210,7 @@ HRESULT DirectX::CreateTextureFromMemory( const CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_DEFAULT); ComPtr res; - HRESULT hr = device->CreateCommittedResource( - &heapProperties, + HRESULT hr = device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, @@ -255,32 +239,28 @@ HRESULT DirectX::CreateTextureFromMemory( return S_OK; } -_Use_decl_annotations_ -HRESULT DirectX::CreateTextureFromMemory( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - size_t width, - size_t height, - DXGI_FORMAT format, - const D3D12_SUBRESOURCE_DATA& initData, - ID3D12Resource** texture, - bool generateMips, - D3D12_RESOURCE_STATES afterState, - D3D12_RESOURCE_FLAGS resFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateTextureFromMemory(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + size_t width, + size_t height, + DXGI_FORMAT format, + const D3D12_SUBRESOURCE_DATA& initData, + ID3D12Resource** texture, + bool generateMips, + D3D12_RESOURCE_STATES afterState, + D3D12_RESOURCE_FLAGS resFlags) noexcept { if (!texture) return E_INVALIDARG; *texture = nullptr; - if (!device || !width || !height - || !initData.pData || !initData.RowPitch) + if (!device || !width || !height || !initData.pData || !initData.RowPitch) return E_INVALIDARG; static_assert(D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION <= UINT32_MAX, "Exceeded integer limits"); - if ((width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) - || (height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + if ((width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) || (height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (2D: size %zu by %zu)\n", width, height); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -296,14 +276,13 @@ HRESULT DirectX::CreateTextureFromMemory( } } - const auto desc = CD3DX12_RESOURCE_DESC::Tex2D(format, static_cast(width), static_cast(height), - 1u, mipCount, 1u, 0u, resFlags); + const auto desc + = CD3DX12_RESOURCE_DESC::Tex2D(format, static_cast(width), static_cast(height), 1u, mipCount, 1u, 0u, resFlags); const CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_DEFAULT); ComPtr res; - HRESULT hr = device->CreateCommittedResource( - &heapProperties, + HRESULT hr = device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, @@ -337,31 +316,28 @@ HRESULT DirectX::CreateTextureFromMemory( return S_OK; } - -_Use_decl_annotations_ -HRESULT DirectX::CreateTextureFromMemory( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - size_t width, size_t height, size_t depth, - DXGI_FORMAT format, - const D3D12_SUBRESOURCE_DATA& initData, - ID3D12Resource** texture, - D3D12_RESOURCE_STATES afterState, - D3D12_RESOURCE_FLAGS resFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateTextureFromMemory(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + size_t width, + size_t height, + size_t depth, + DXGI_FORMAT format, + const D3D12_SUBRESOURCE_DATA& initData, + ID3D12Resource** texture, + D3D12_RESOURCE_STATES afterState, + D3D12_RESOURCE_FLAGS resFlags) noexcept { if (!texture) return E_INVALIDARG; *texture = nullptr; - if (!device || !width || !height || !depth - || !initData.pData || !initData.RowPitch || !initData.SlicePitch) + if (!device || !width || !height || !depth || !initData.pData || !initData.RowPitch || !initData.SlicePitch) return E_INVALIDARG; static_assert(D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION <= UINT16_MAX, "Exceeded integer limits"); - if ((width > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) - || (height > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) + if ((width > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (depth > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (3D: size %zu by %zu by %zu)\n", width, height, depth); @@ -369,14 +345,16 @@ HRESULT DirectX::CreateTextureFromMemory( } const auto desc = CD3DX12_RESOURCE_DESC::Tex3D(format, - static_cast(width), static_cast(height), static_cast(depth), - 1u, resFlags); + static_cast(width), + static_cast(height), + static_cast(depth), + 1u, + resFlags); const CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_DEFAULT); ComPtr res; - HRESULT hr = device->CreateCommittedResource( - &heapProperties, + HRESULT hr = device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, diff --git a/Src/CMO.h b/Src/CMO.h index 7af35e75..05de395c 100644 --- a/Src/CMO.h +++ b/Src/CMO.h @@ -20,7 +20,6 @@ #include - namespace VSD3DStarter { // .CMO files @@ -82,7 +81,7 @@ namespace VSD3DStarter // } // } -#pragma pack(push,1) +#pragma pack(push, 1) struct Material { @@ -114,14 +113,14 @@ namespace VSD3DStarter DirectX::XMFLOAT3 position; DirectX::XMFLOAT3 normal; DirectX::XMFLOAT4 tangent; - uint32_t color; + uint32_t color; DirectX::XMFLOAT2 textureCoordinate; }; struct SkinningVertex { uint32_t boneIndex[NUM_BONE_INFLUENCES]; - float boneWeight[NUM_BONE_INFLUENCES]; + float boneWeight[NUM_BONE_INFLUENCES]; }; struct MeshExtents @@ -135,7 +134,7 @@ namespace VSD3DStarter struct Bone { - int32_t ParentIndex; + int32_t ParentIndex; DirectX::XMFLOAT4X4 InvBindPos; DirectX::XMFLOAT4X4 BindPos; DirectX::XMFLOAT4X4 LocalTransform; @@ -143,35 +142,29 @@ namespace VSD3DStarter struct Clip { - float StartTime; - float EndTime; + float StartTime; + float EndTime; uint32_t keys; }; struct Keyframe { - uint32_t BoneIndex; - float Time; + uint32_t BoneIndex; + float Time; DirectX::XMFLOAT4X4 Transform; }; #pragma pack(pop) - const Material s_defMaterial = - { + const Material s_defMaterial = { { 0.2f, 0.2f, 0.2f, 1.f }, { 0.8f, 0.8f, 0.8f, 1.f }, { 0.0f, 0.0f, 0.0f, 1.f }, 1.f, { 0.0f, 0.0f, 0.0f, 1.0f }, - { - 1.f, 0.f, 0.f, 0.f, - 0.f, 1.f, 0.f, 0.f, - 0.f, 0.f, 1.f, 0.f, - 0.f, 0.f, 0.f, 1.f - }, + { 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f }, }; -} // namespace +} // namespace VSD3DStarter static_assert(sizeof(VSD3DStarter::Material) == 132, "CMO Mesh structure size incorrect"); static_assert(sizeof(VSD3DStarter::SubMesh) == 20, "CMO Mesh structure size incorrect"); diff --git a/Src/CommonStates.cpp b/Src/CommonStates.cpp index 5fde888b..3f8d7a24 100644 --- a/Src/CommonStates.cpp +++ b/Src/CommonStates.cpp @@ -18,428 +18,378 @@ using namespace DirectX; // Blend States // -------------------------------------------------------------------------- -const D3D12_BLEND_DESC CommonStates::Opaque = -{ - FALSE, // AlphaToCoverageEnable - FALSE, // IndependentBlendEnable - { { - FALSE, // BlendEnable - FALSE, // LogicOpEnable - D3D12_BLEND_ONE, // SrcBlend - D3D12_BLEND_ZERO, // DestBlend - D3D12_BLEND_OP_ADD, // BlendOp - D3D12_BLEND_ONE, // SrcBlendAlpha - D3D12_BLEND_ZERO, // DestBlendAlpha - D3D12_BLEND_OP_ADD, // BlendOpAlpha +const D3D12_BLEND_DESC CommonStates::Opaque = { FALSE, // AlphaToCoverageEnable + FALSE, // IndependentBlendEnable + { { FALSE, // BlendEnable + FALSE, // LogicOpEnable + D3D12_BLEND_ONE, // SrcBlend + D3D12_BLEND_ZERO, // DestBlend + D3D12_BLEND_OP_ADD, // BlendOp + D3D12_BLEND_ONE, // SrcBlendAlpha + D3D12_BLEND_ZERO, // DestBlendAlpha + D3D12_BLEND_OP_ADD, // BlendOpAlpha D3D12_LOGIC_OP_NOOP, - D3D12_COLOR_WRITE_ENABLE_ALL - } } -}; - -const D3D12_BLEND_DESC CommonStates::AlphaBlend = -{ - FALSE, // AlphaToCoverageEnable - FALSE, // IndependentBlendEnable - { { - TRUE, // BlendEnable - FALSE, // LogicOpEnable - D3D12_BLEND_ONE, // SrcBlend - D3D12_BLEND_INV_SRC_ALPHA, // DestBlend - D3D12_BLEND_OP_ADD, // BlendOp - D3D12_BLEND_ONE, // SrcBlendAlpha - D3D12_BLEND_INV_SRC_ALPHA, // DestBlendAlpha - D3D12_BLEND_OP_ADD, // BlendOpAlpha + D3D12_COLOR_WRITE_ENABLE_ALL } } }; + +const D3D12_BLEND_DESC CommonStates::AlphaBlend = { FALSE, // AlphaToCoverageEnable + FALSE, // IndependentBlendEnable + { { TRUE, // BlendEnable + FALSE, // LogicOpEnable + D3D12_BLEND_ONE, // SrcBlend + D3D12_BLEND_INV_SRC_ALPHA, // DestBlend + D3D12_BLEND_OP_ADD, // BlendOp + D3D12_BLEND_ONE, // SrcBlendAlpha + D3D12_BLEND_INV_SRC_ALPHA, // DestBlendAlpha + D3D12_BLEND_OP_ADD, // BlendOpAlpha D3D12_LOGIC_OP_NOOP, - D3D12_COLOR_WRITE_ENABLE_ALL - } } -}; - -const D3D12_BLEND_DESC CommonStates::Additive = -{ - FALSE, // AlphaToCoverageEnable - FALSE, // IndependentBlendEnable - { { - TRUE, // BlendEnable - FALSE, // LogicOpEnable - D3D12_BLEND_SRC_ALPHA, // SrcBlend - D3D12_BLEND_ONE, // DestBlend - D3D12_BLEND_OP_ADD, // BlendOp - D3D12_BLEND_SRC_ALPHA, // SrcBlendAlpha - D3D12_BLEND_ONE, // DestBlendAlpha - D3D12_BLEND_OP_ADD, // BlendOpAlpha + D3D12_COLOR_WRITE_ENABLE_ALL } } }; + +const D3D12_BLEND_DESC CommonStates::Additive = { FALSE, // AlphaToCoverageEnable + FALSE, // IndependentBlendEnable + { { TRUE, // BlendEnable + FALSE, // LogicOpEnable + D3D12_BLEND_SRC_ALPHA, // SrcBlend + D3D12_BLEND_ONE, // DestBlend + D3D12_BLEND_OP_ADD, // BlendOp + D3D12_BLEND_SRC_ALPHA, // SrcBlendAlpha + D3D12_BLEND_ONE, // DestBlendAlpha + D3D12_BLEND_OP_ADD, // BlendOpAlpha D3D12_LOGIC_OP_NOOP, - D3D12_COLOR_WRITE_ENABLE_ALL - } } -}; - -const D3D12_BLEND_DESC CommonStates::NonPremultiplied = -{ - FALSE, // AlphaToCoverageEnable - FALSE, // IndependentBlendEnable - { { - TRUE, // BlendEnable - FALSE, // LogicOpEnable - D3D12_BLEND_SRC_ALPHA, // SrcBlend - D3D12_BLEND_INV_SRC_ALPHA, // DestBlend - D3D12_BLEND_OP_ADD, // BlendOp - D3D12_BLEND_SRC_ALPHA, // SrcBlendAlpha - D3D12_BLEND_INV_SRC_ALPHA, // DestBlendAlpha - D3D12_BLEND_OP_ADD, // BlendOpAlpha + D3D12_COLOR_WRITE_ENABLE_ALL } } }; + +const D3D12_BLEND_DESC CommonStates::NonPremultiplied = { FALSE, // AlphaToCoverageEnable + FALSE, // IndependentBlendEnable + { { TRUE, // BlendEnable + FALSE, // LogicOpEnable + D3D12_BLEND_SRC_ALPHA, // SrcBlend + D3D12_BLEND_INV_SRC_ALPHA, // DestBlend + D3D12_BLEND_OP_ADD, // BlendOp + D3D12_BLEND_SRC_ALPHA, // SrcBlendAlpha + D3D12_BLEND_INV_SRC_ALPHA, // DestBlendAlpha + D3D12_BLEND_OP_ADD, // BlendOpAlpha D3D12_LOGIC_OP_NOOP, - D3D12_COLOR_WRITE_ENABLE_ALL - } } -}; - + D3D12_COLOR_WRITE_ENABLE_ALL } } }; // -------------------------------------------------------------------------- // Depth-Stencil States // -------------------------------------------------------------------------- -const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthNone = -{ - FALSE, // DepthEnable +const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthNone = { + FALSE, // DepthEnable D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_LESS_EQUAL, // DepthFunc - FALSE, // StencilEnable + FALSE, // StencilEnable D3D12_DEFAULT_STENCIL_READ_MASK, D3D12_DEFAULT_STENCIL_WRITE_MASK, { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc - }, // FrontFace + }, // FrontFace { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc } // BackFace }; -const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthDefault = -{ - TRUE, // DepthEnable +const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthDefault = { + TRUE, // DepthEnable D3D12_DEPTH_WRITE_MASK_ALL, D3D12_COMPARISON_FUNC_LESS_EQUAL, // DepthFunc - FALSE, // StencilEnable + FALSE, // StencilEnable D3D12_DEFAULT_STENCIL_READ_MASK, D3D12_DEFAULT_STENCIL_WRITE_MASK, { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc - }, // FrontFace + }, // FrontFace { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc } // BackFace }; -const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthRead = -{ - TRUE, // DepthEnable +const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthRead = { + TRUE, // DepthEnable D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_LESS_EQUAL, // DepthFunc - FALSE, // StencilEnable + FALSE, // StencilEnable D3D12_DEFAULT_STENCIL_READ_MASK, D3D12_DEFAULT_STENCIL_WRITE_MASK, { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc - }, // FrontFace + }, // FrontFace { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc } // BackFace }; -const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthReverseZ = -{ - TRUE, // DepthEnable +const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthReverseZ = { + TRUE, // DepthEnable D3D12_DEPTH_WRITE_MASK_ALL, D3D12_COMPARISON_FUNC_GREATER_EQUAL, // DepthFunc - FALSE, // StencilEnable + FALSE, // StencilEnable D3D12_DEFAULT_STENCIL_READ_MASK, D3D12_DEFAULT_STENCIL_WRITE_MASK, { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc - }, // FrontFace + }, // FrontFace { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc } // BackFace }; -const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthReadReverseZ = -{ - TRUE, // DepthEnable +const D3D12_DEPTH_STENCIL_DESC CommonStates::DepthReadReverseZ = { + TRUE, // DepthEnable D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_GREATER_EQUAL, // DepthFunc - FALSE, // StencilEnable + FALSE, // StencilEnable D3D12_DEFAULT_STENCIL_READ_MASK, D3D12_DEFAULT_STENCIL_WRITE_MASK, { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc - }, // FrontFace + }, // FrontFace { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc } // BackFace }; - // -------------------------------------------------------------------------- // Rasterizer States // -------------------------------------------------------------------------- -const D3D12_RASTERIZER_DESC CommonStates::CullNone = -{ - D3D12_FILL_MODE_SOLID, +const D3D12_RASTERIZER_DESC CommonStates::CullNone = { D3D12_FILL_MODE_SOLID, D3D12_CULL_MODE_NONE, FALSE, // FrontCounterClockwise D3D12_DEFAULT_DEPTH_BIAS, D3D12_DEFAULT_DEPTH_BIAS_CLAMP, D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS, - TRUE, // DepthClipEnable - TRUE, // MultisampleEnable + TRUE, // DepthClipEnable + TRUE, // MultisampleEnable FALSE, // AntialiasedLineEnable - 0, // ForcedSampleCount - D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF -}; + 0, // ForcedSampleCount + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF }; -const D3D12_RASTERIZER_DESC CommonStates::CullClockwise = -{ - D3D12_FILL_MODE_SOLID, +const D3D12_RASTERIZER_DESC CommonStates::CullClockwise = { D3D12_FILL_MODE_SOLID, D3D12_CULL_MODE_FRONT, FALSE, // FrontCounterClockwise D3D12_DEFAULT_DEPTH_BIAS, D3D12_DEFAULT_DEPTH_BIAS_CLAMP, D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS, - TRUE, // DepthClipEnable - TRUE, // MultisampleEnable + TRUE, // DepthClipEnable + TRUE, // MultisampleEnable FALSE, // AntialiasedLineEnable - 0, // ForcedSampleCount - D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF -}; + 0, // ForcedSampleCount + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF }; -const D3D12_RASTERIZER_DESC CommonStates::CullCounterClockwise = -{ - D3D12_FILL_MODE_SOLID, +const D3D12_RASTERIZER_DESC CommonStates::CullCounterClockwise = { D3D12_FILL_MODE_SOLID, D3D12_CULL_MODE_BACK, FALSE, // FrontCounterClockwise D3D12_DEFAULT_DEPTH_BIAS, D3D12_DEFAULT_DEPTH_BIAS_CLAMP, D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS, - TRUE, // DepthClipEnable - TRUE, // MultisampleEnable + TRUE, // DepthClipEnable + TRUE, // MultisampleEnable FALSE, // AntialiasedLineEnable - 0, // ForcedSampleCount - D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF -}; + 0, // ForcedSampleCount + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF }; -const D3D12_RASTERIZER_DESC CommonStates::Wireframe = -{ - D3D12_FILL_MODE_WIREFRAME, +const D3D12_RASTERIZER_DESC CommonStates::Wireframe = { D3D12_FILL_MODE_WIREFRAME, D3D12_CULL_MODE_NONE, FALSE, // FrontCounterClockwise D3D12_DEFAULT_DEPTH_BIAS, D3D12_DEFAULT_DEPTH_BIAS_CLAMP, D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS, - TRUE, // DepthClipEnable - TRUE, // MultisampleEnable + TRUE, // DepthClipEnable + TRUE, // MultisampleEnable FALSE, // AntialiasedLineEnable - 0, // ForcedSampleCount - D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF -}; - + 0, // ForcedSampleCount + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF }; // -------------------------------------------------------------------------- // Static sampler States // -------------------------------------------------------------------------- -const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticPointWrap( - unsigned int shaderRegister, - D3D12_SHADER_VISIBILITY shaderVisibility, - unsigned int registerSpace) noexcept +const D3D12_STATIC_SAMPLER_DESC +CommonStates::StaticPointWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility, unsigned int registerSpace) noexcept { static const D3D12_STATIC_SAMPLER_DESC s_desc = { D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, - 0, // MinLOD + 0, // MinLOD FLT_MAX, // MaxLOD - 0, // ShaderRegister - 0, // RegisterSpace + 0, // ShaderRegister + 0, // RegisterSpace D3D12_SHADER_VISIBILITY_ALL, }; D3D12_STATIC_SAMPLER_DESC desc = s_desc; - desc.ShaderRegister = shaderRegister; - desc.ShaderVisibility = shaderVisibility; - desc.RegisterSpace = registerSpace; + desc.ShaderRegister = shaderRegister; + desc.ShaderVisibility = shaderVisibility; + desc.RegisterSpace = registerSpace; return desc; } -const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticPointClamp( - unsigned int shaderRegister, - D3D12_SHADER_VISIBILITY shaderVisibility, - unsigned int registerSpace) noexcept +const D3D12_STATIC_SAMPLER_DESC +CommonStates::StaticPointClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility, unsigned int registerSpace) noexcept { static const D3D12_STATIC_SAMPLER_DESC s_desc = { D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, - 0, // MinLOD + 0, // MinLOD FLT_MAX, // MaxLOD - 0, // ShaderRegister - 0, // RegisterSpace + 0, // ShaderRegister + 0, // RegisterSpace D3D12_SHADER_VISIBILITY_ALL, }; D3D12_STATIC_SAMPLER_DESC desc = s_desc; - desc.ShaderRegister = shaderRegister; - desc.ShaderVisibility = shaderVisibility; - desc.RegisterSpace = registerSpace; + desc.ShaderRegister = shaderRegister; + desc.ShaderVisibility = shaderVisibility; + desc.RegisterSpace = registerSpace; return desc; }; -const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticLinearWrap( - unsigned int shaderRegister, - D3D12_SHADER_VISIBILITY shaderVisibility, - unsigned int registerSpace) noexcept +const D3D12_STATIC_SAMPLER_DESC +CommonStates::StaticLinearWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility, unsigned int registerSpace) noexcept { static const D3D12_STATIC_SAMPLER_DESC s_desc = { D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, - 0, // MinLOD + 0, // MinLOD FLT_MAX, // MaxLOD - 0, // ShaderRegister - 0, // RegisterSpace + 0, // ShaderRegister + 0, // RegisterSpace D3D12_SHADER_VISIBILITY_ALL, }; D3D12_STATIC_SAMPLER_DESC desc = s_desc; - desc.ShaderRegister = shaderRegister; - desc.ShaderVisibility = shaderVisibility; - desc.RegisterSpace = registerSpace; + desc.ShaderRegister = shaderRegister; + desc.ShaderVisibility = shaderVisibility; + desc.RegisterSpace = registerSpace; return desc; }; -const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticLinearClamp( - unsigned int shaderRegister, - D3D12_SHADER_VISIBILITY shaderVisibility, - unsigned int registerSpace) noexcept +const D3D12_STATIC_SAMPLER_DESC +CommonStates::StaticLinearClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility, unsigned int registerSpace) noexcept { static const D3D12_STATIC_SAMPLER_DESC s_desc = { D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, - 0, // MinLOD + 0, // MinLOD FLT_MAX, // MaxLOD - 0, // ShaderRegister - 0, // RegisterSpace + 0, // ShaderRegister + 0, // RegisterSpace D3D12_SHADER_VISIBILITY_ALL, }; D3D12_STATIC_SAMPLER_DESC desc = s_desc; - desc.ShaderRegister = shaderRegister; - desc.ShaderVisibility = shaderVisibility; - desc.RegisterSpace = registerSpace; + desc.ShaderRegister = shaderRegister; + desc.ShaderVisibility = shaderVisibility; + desc.RegisterSpace = registerSpace; return desc; }; -const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticAnisotropicWrap( - unsigned int shaderRegister, - D3D12_SHADER_VISIBILITY shaderVisibility, - unsigned int registerSpace) noexcept +const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticAnisotropicWrap(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility, + unsigned int registerSpace) noexcept { static const D3D12_STATIC_SAMPLER_DESC s_desc = { D3D12_FILTER_ANISOTROPIC, D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, - 0, // MinLOD + 0, // MinLOD FLT_MAX, // MaxLOD - 0, // ShaderRegister - 0, // RegisterSpace + 0, // ShaderRegister + 0, // RegisterSpace D3D12_SHADER_VISIBILITY_ALL, }; D3D12_STATIC_SAMPLER_DESC desc = s_desc; - desc.ShaderRegister = shaderRegister; - desc.ShaderVisibility = shaderVisibility; - desc.RegisterSpace = registerSpace; + desc.ShaderRegister = shaderRegister; + desc.ShaderVisibility = shaderVisibility; + desc.RegisterSpace = registerSpace; return desc; }; -const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticAnisotropicClamp( - unsigned int shaderRegister, - D3D12_SHADER_VISIBILITY shaderVisibility, - unsigned int registerSpace) noexcept +const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticAnisotropicClamp(unsigned int shaderRegister, + D3D12_SHADER_VISIBILITY shaderVisibility, + unsigned int registerSpace) noexcept { static const D3D12_STATIC_SAMPLER_DESC s_desc = { D3D12_FILTER_ANISOTROPIC, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, - 0, // MinLOD + 0, // MinLOD FLT_MAX, // MaxLOD - 0, // ShaderRegister - 0, // RegisterSpace + 0, // ShaderRegister + 0, // RegisterSpace D3D12_SHADER_VISIBILITY_ALL, }; D3D12_STATIC_SAMPLER_DESC desc = s_desc; - desc.ShaderRegister = shaderRegister; - desc.ShaderVisibility = shaderVisibility; - desc.RegisterSpace = registerSpace; + desc.ShaderRegister = shaderRegister; + desc.ShaderVisibility = shaderVisibility; + desc.RegisterSpace = registerSpace; return desc; }; @@ -450,11 +400,13 @@ const D3D12_STATIC_SAMPLER_DESC CommonStates::StaticAnisotropicClamp( class CommonStates::Impl { public: - static const D3D12_SAMPLER_DESC SamplerDescs[static_cast(SamplerIndex::Count)]; explicit Impl(_In_ ID3D12Device* device) - : mDescriptors(device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, static_cast(SamplerIndex::Count)) + : mDescriptors(device, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + static_cast(SamplerIndex::Count)) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -467,40 +419,33 @@ class CommonStates::Impl } } - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; - D3D12_GPU_DESCRIPTOR_HANDLE Get(SamplerIndex i) const - { - return mDescriptors.GetGpuHandle(static_cast(i)); - } + D3D12_GPU_DESCRIPTOR_HANDLE Get(SamplerIndex i) const { return mDescriptors.GetGpuHandle(static_cast(i)); } - ID3D12DescriptorHeap* Heap() const noexcept - { - return mDescriptors.Heap(); - } + ID3D12DescriptorHeap* Heap() const noexcept { return mDescriptors.Heap(); } private: DescriptorHeap mDescriptors; }; -const D3D12_SAMPLER_DESC CommonStates::Impl::SamplerDescs[] = -{ +const D3D12_SAMPLER_DESC CommonStates::Impl::SamplerDescs[] = { // PointWrap { D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, - { 0, 0, 0, 0 }, // BorderColor - 0, // MinLOD - FLT_MAX // MaxLOD + { 0, 0, 0, 0 }, // BorderColor + 0, // MinLOD + FLT_MAX // MaxLOD }, // PointClamp { @@ -508,12 +453,12 @@ const D3D12_SAMPLER_DESC CommonStates::Impl::SamplerDescs[] = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, - { 0, 0, 0, 0 }, // BorderColor - 0, // MinLOD - FLT_MAX // MaxLOD + { 0, 0, 0, 0 }, // BorderColor + 0, // MinLOD + FLT_MAX // MaxLOD }, // LinearWrap { @@ -521,12 +466,12 @@ const D3D12_SAMPLER_DESC CommonStates::Impl::SamplerDescs[] = D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, - { 0, 0, 0, 0 }, // BorderColor - 0, // MinLOD - FLT_MAX // MaxLOD + { 0, 0, 0, 0 }, // BorderColor + 0, // MinLOD + FLT_MAX // MaxLOD }, // LinearClamp { @@ -534,12 +479,12 @@ const D3D12_SAMPLER_DESC CommonStates::Impl::SamplerDescs[] = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, - { 0, 0, 0, 0 }, // BorderColor - 0, // MinLOD - FLT_MAX // MaxLOD + { 0, 0, 0, 0 }, // BorderColor + 0, // MinLOD + FLT_MAX // MaxLOD }, // AnisotropicWrap { @@ -547,12 +492,12 @@ const D3D12_SAMPLER_DESC CommonStates::Impl::SamplerDescs[] = D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_WRAP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, - { 0, 0, 0, 0 }, // BorderColor - 0, // MinLOD - FLT_MAX // MaxLOD + { 0, 0, 0, 0 }, // BorderColor + 0, // MinLOD + FLT_MAX // MaxLOD }, // AnisotropicClamp { @@ -560,31 +505,49 @@ const D3D12_SAMPLER_DESC CommonStates::Impl::SamplerDescs[] = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressU D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressV D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressW - 0, // MipLODBias + 0, // MipLODBias D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER, - { 0, 0, 0, 0 }, // BorderColor - 0, // MinLOD - FLT_MAX // MaxLOD + { 0, 0, 0, 0 }, // BorderColor + 0, // MinLOD + FLT_MAX // MaxLOD } }; - -_Use_decl_annotations_ -CommonStates::CommonStates(ID3D12Device* device) : - pImpl(std::make_unique(device)) +_Use_decl_annotations_ CommonStates::CommonStates(ID3D12Device* device) + : pImpl(std::make_unique(device)) {} -CommonStates::CommonStates(CommonStates&&) noexcept = default; -CommonStates& CommonStates::operator = (CommonStates&&) noexcept = default; -CommonStates::~CommonStates() = default; +CommonStates::CommonStates(CommonStates&&) noexcept = default; +CommonStates& CommonStates::operator=(CommonStates&&) noexcept = default; +CommonStates::~CommonStates() = default; +D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::PointWrap() const +{ + return pImpl->Get(SamplerIndex::PointWrap); +} +D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::PointClamp() const +{ + return pImpl->Get(SamplerIndex::PointClamp); +} +D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::LinearWrap() const +{ + return pImpl->Get(SamplerIndex::LinearWrap); +} +D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::LinearClamp() const +{ + return pImpl->Get(SamplerIndex::LinearClamp); +} +D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::AnisotropicWrap() const +{ + return pImpl->Get(SamplerIndex::AnisotropicWrap); +} +D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::AnisotropicClamp() const +{ + return pImpl->Get(SamplerIndex::AnisotropicClamp); +} -D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::PointWrap() const { return pImpl->Get(SamplerIndex::PointWrap); } -D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::PointClamp() const { return pImpl->Get(SamplerIndex::PointClamp); } -D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::LinearWrap() const { return pImpl->Get(SamplerIndex::LinearWrap); } -D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::LinearClamp() const { return pImpl->Get(SamplerIndex::LinearClamp); } -D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::AnisotropicWrap() const { return pImpl->Get(SamplerIndex::AnisotropicWrap); } -D3D12_GPU_DESCRIPTOR_HANDLE CommonStates::AnisotropicClamp() const { return pImpl->Get(SamplerIndex::AnisotropicClamp); } - -ID3D12DescriptorHeap* CommonStates::Heap() const noexcept { return pImpl->Heap(); } +ID3D12DescriptorHeap* CommonStates::Heap() const noexcept +{ + return pImpl->Heap(); +} diff --git a/Src/DDSTextureLoader.cpp b/Src/DDSTextureLoader.cpp index 5732dfd7..d25dbfdc 100644 --- a/Src/DDSTextureLoader.cpp +++ b/Src/DDSTextureLoader.cpp @@ -47,24 +47,20 @@ namespace case DXGI_FORMAT_X24_TYPELESS_G8_UINT: case DXGI_FORMAT_D16_UNORM: - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) case DXGI_FORMAT_D16_UNORM_S8_UINT: case DXGI_FORMAT_R16_UNORM_X8_TYPELESS: case DXGI_FORMAT_X16_TYPELESS_G8_UINT: - #endif +#endif return true; - default: - return false; + default: return false; } } //-------------------------------------------------------------------------------------- - inline void AdjustPlaneResource( - _In_ DXGI_FORMAT fmt, - _In_ size_t height, - _In_ size_t slicePlane, - _Inout_ D3D12_SUBRESOURCE_DATA& res) noexcept + inline void + AdjustPlaneResource(_In_ DXGI_FORMAT fmt, _In_ size_t height, _In_ size_t slicePlane, _Inout_ D3D12_SUBRESOURCE_DATA& res) noexcept { switch (fmt) { @@ -72,11 +68,11 @@ namespace case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) case DXGI_FORMAT_D16_UNORM_S8_UINT: case DXGI_FORMAT_R16_UNORM_X8_TYPELESS: case DXGI_FORMAT_X16_TYPELESS_G8_UINT: - #endif +#endif if (!slicePlane) { // Plane 0 @@ -85,7 +81,7 @@ namespace else { // Plane 1 - res.pData = static_cast(res.pData) + uintptr_t(res.RowPitch) * height; + res.pData = static_cast(res.pData) + uintptr_t(res.RowPitch) * height; res.SlicePitch = res.RowPitch * ((static_cast(height) + 1) >> 1); } break; @@ -99,33 +95,32 @@ namespace else { // Plane 1 - res.pData = static_cast(res.pData) + uintptr_t(res.RowPitch) * height; - res.RowPitch = (res.RowPitch >> 1); + res.pData = static_cast(res.pData) + uintptr_t(res.RowPitch) * height; + res.RowPitch = (res.RowPitch >> 1); res.SlicePitch = res.RowPitch * static_cast(height); } break; - default: - break; + default: break; } } //-------------------------------------------------------------------------------------- - HRESULT FillInitData(_In_ size_t width, - _In_ size_t height, - _In_ size_t depth, - _In_ size_t mipCount, - _In_ size_t arraySize, - _In_ size_t numberOfPlanes, - _In_ DXGI_FORMAT format, - _In_ size_t maxsize, - _In_ size_t bitSize, + HRESULT FillInitData(_In_ size_t width, + _In_ size_t height, + _In_ size_t depth, + _In_ size_t mipCount, + _In_ size_t arraySize, + _In_ size_t numberOfPlanes, + _In_ DXGI_FORMAT format, + _In_ size_t maxsize, + _In_ size_t bitSize, _In_reads_bytes_(bitSize) const uint8_t* bitData, - _Out_ size_t& twidth, - _Out_ size_t& theight, - _Out_ size_t& tdepth, - _Out_ size_t& skipMip, - std::vector& initData) + _Out_ size_t& twidth, + _Out_ size_t& theight, + _Out_ size_t& tdepth, + _Out_ size_t& skipMip, + std::vector& initData) { if (!bitData) { @@ -133,12 +128,12 @@ namespace } skipMip = 0; - twidth = 0; + twidth = 0; theight = 0; - tdepth = 0; + tdepth = 0; - size_t NumBytes = 0; - size_t RowBytes = 0; + size_t NumBytes = 0; + size_t RowBytes = 0; const uint8_t* pEndBits = bitData + bitSize; initData.clear(); @@ -165,17 +160,12 @@ namespace { if (!twidth) { - twidth = w; + twidth = w; theight = h; - tdepth = d; + tdepth = d; } - D3D12_SUBRESOURCE_DATA res = - { - pSrcBits, - static_cast(RowBytes), - static_cast(NumBytes) - }; + D3D12_SUBRESOURCE_DATA res = { pSrcBits, static_cast(RowBytes), static_cast(NumBytes) }; AdjustPlaneResource(format, h, p, res); @@ -187,7 +177,7 @@ namespace ++skipMip; } - if (pSrcBits + (NumBytes*d) > pEndBits) + if (pSrcBits + (NumBytes * d) > pEndBits) { return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } @@ -217,18 +207,17 @@ namespace } //-------------------------------------------------------------------------------------- - HRESULT CreateTextureResource( - _In_ ID3D12Device* device, - D3D12_RESOURCE_DIMENSION resDim, - size_t width, - size_t height, - size_t depth, - size_t mipCount, - size_t arraySize, - DXGI_FORMAT format, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture) noexcept + HRESULT CreateTextureResource(_In_ ID3D12Device* device, + D3D12_RESOURCE_DIMENSION resDim, + size_t width, + size_t height, + size_t depth, + size_t mipCount, + size_t arraySize, + DXGI_FORMAT format, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture) noexcept { if (!device) return E_POINTER; @@ -245,20 +234,20 @@ namespace } D3D12_RESOURCE_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.MipLevels = static_cast(mipCount); - desc.DepthOrArraySize = (resDim == D3D12_RESOURCE_DIMENSION_TEXTURE3D) ? static_cast(depth) : static_cast(arraySize); - desc.Format = format; - desc.Flags = resFlags; - desc.SampleDesc.Count = 1; + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.MipLevels = static_cast(mipCount); + desc.DepthOrArraySize + = (resDim == D3D12_RESOURCE_DIMENSION_TEXTURE3D) ? static_cast(depth) : static_cast(arraySize); + desc.Format = format; + desc.Flags = resFlags; + desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; - desc.Dimension = resDim; + desc.Dimension = resDim; const CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT); - hr = device->CreateCommittedResource( - &defaultHeapProperties, + hr = device->CreateCommittedResource(&defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, @@ -277,26 +266,26 @@ namespace //-------------------------------------------------------------------------------------- HRESULT CreateTextureFromDDS(_In_ ID3D12Device* device, - _In_ const DDS_HEADER* header, - _In_reads_bytes_(bitSize) const uint8_t* bitData, - size_t bitSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::vector& subresources, - _Out_opt_ bool* outIsCubeMap) noexcept(false) + _In_ const DDS_HEADER* header, + _In_reads_bytes_(bitSize) const uint8_t* bitData, + size_t bitSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::vector& subresources, + _Out_opt_ bool* outIsCubeMap) noexcept(false) { HRESULT hr = S_OK; - const UINT width = header->width; - UINT height = header->height; - UINT depth = header->depth; + const UINT width = header->width; + UINT height = header->height; + UINT depth = header->depth; - D3D12_RESOURCE_DIMENSION resDim = D3D12_RESOURCE_DIMENSION_UNKNOWN; - UINT arraySize = 1; - DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; - bool isCubeMap = false; + D3D12_RESOURCE_DIMENSION resDim = D3D12_RESOURCE_DIMENSION_UNKNOWN; + UINT arraySize = 1; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + bool isCubeMap = false; size_t mipCount = header->mipMapCount; if ((0 == mipCount) || (loadFlags & DDS_LOADER_IGNORE_MIPS)) @@ -304,8 +293,7 @@ namespace mipCount = 1; } - if ((header->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) + if ((header->ddspf.flags & DDS_FOURCC) && (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) { auto d3d10ext = reinterpret_cast(reinterpret_cast(header) + sizeof(DDS_HEADER)); @@ -321,8 +309,7 @@ namespace case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: case DXGI_FORMAT_420_OPAQUE: - if ((d3d10ext->resourceDimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) - || (width % 2) != 0 || (height % 2) != 0) + if ((d3d10ext->resourceDimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) || (width % 2) != 0 || (height % 2) != 0) { DebugTrace("ERROR: Video texture does not meet width/height requirements.\n"); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -356,8 +343,7 @@ namespace return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); case DXGI_FORMAT_V208: - if ((d3d10ext->resourceDimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) - || (height % 2) != 0) + if ((d3d10ext->resourceDimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) || (height % 2) != 0) { DebugTrace("ERROR: Video texture does not meet height requirements.\n"); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -449,7 +435,7 @@ namespace isCubeMap = true; } - depth = 1; + depth = 1; resDim = D3D12_RESOURCE_DIMENSION_TEXTURE2D; // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture @@ -468,8 +454,7 @@ namespace switch (resDim) { case D3D12_RESOURCE_DIMENSION_TEXTURE1D: - if ((arraySize > D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || - (width > D3D12_REQ_TEXTURE1D_U_DIMENSION)) + if ((arraySize > D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || (width > D3D12_REQ_TEXTURE1D_U_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (1D: array %u, size %u)\n", arraySize, width); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -480,17 +465,18 @@ namespace if (isCubeMap) { // This is the right bound because we set arraySize to (NumCubes*6) above - if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D12_REQ_TEXTURECUBE_DIMENSION) || - (height > D3D12_REQ_TEXTURECUBE_DIMENSION)) + if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D12_REQ_TEXTURECUBE_DIMENSION) + || (height > D3D12_REQ_TEXTURECUBE_DIMENSION)) { - DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (2D cubemap: array %u, size %u by %u)\n", arraySize, width, height); + DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (2D cubemap: array %u, size %u by %u)\n", + arraySize, + width, + height); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } - else if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) || - (height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + else if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) + || (height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (2D: array %u, size %u by %u)\n", arraySize, width, height); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -498,12 +484,14 @@ namespace break; case D3D12_RESOURCE_DIMENSION_TEXTURE3D: - if ((arraySize > 1) || - (width > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (height > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (depth > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) + if ((arraySize > 1) || (width > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) + || (depth > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) { - DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (3D: array %u, size %u by %u by %u)\n", arraySize, width, height, depth); + DebugTrace("ERROR: Resource dimensions too large for DirectX 12 (3D: array %u, size %u by %u by %u)\n", + arraySize, + width, + height, + depth); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; @@ -533,8 +521,7 @@ namespace } // Create the texture - size_t numberOfResources = (resDim == D3D12_RESOURCE_DIMENSION_TEXTURE3D) - ? 1 : arraySize; + size_t numberOfResources = (resDim == D3D12_RESOURCE_DIMENSION_TEXTURE3D) ? 1 : arraySize; numberOfResources *= mipCount; numberOfResources *= numberOfPlanes; @@ -544,43 +531,80 @@ namespace subresources.reserve(numberOfResources); size_t skipMip = 0; - size_t twidth = 0; + size_t twidth = 0; size_t theight = 0; - size_t tdepth = 0; - hr = FillInitData(width, height, depth, mipCount, arraySize, - numberOfPlanes, format, - maxsize, bitSize, bitData, - twidth, theight, tdepth, skipMip, subresources); + size_t tdepth = 0; + hr = FillInitData(width, + height, + depth, + mipCount, + arraySize, + numberOfPlanes, + format, + maxsize, + bitSize, + bitData, + twidth, + theight, + tdepth, + skipMip, + subresources); if (SUCCEEDED(hr)) { size_t reservedMips = mipCount; if (loadFlags & (DDS_LOADER_MIP_AUTOGEN | DDS_LOADER_MIP_RESERVE)) { - reservedMips = std::min(D3D12_REQ_MIP_LEVELS, - LoaderHelpers::CountMips(width, height)); + reservedMips = std::min(D3D12_REQ_MIP_LEVELS, LoaderHelpers::CountMips(width, height)); } - hr = CreateTextureResource(device, resDim, twidth, theight, tdepth, reservedMips - skipMip, arraySize, - format, resFlags, loadFlags, texture); + hr = CreateTextureResource(device, + resDim, + twidth, + theight, + tdepth, + reservedMips - skipMip, + arraySize, + format, + resFlags, + loadFlags, + texture); if (FAILED(hr) && !maxsize && (mipCount > 1)) { subresources.clear(); - maxsize = static_cast( - (resDim == D3D12_RESOURCE_DIMENSION_TEXTURE3D) - ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION - : D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); - - hr = FillInitData(width, height, depth, mipCount, arraySize, - numberOfPlanes, format, - maxsize, bitSize, bitData, - twidth, theight, tdepth, skipMip, subresources); + maxsize = static_cast((resDim == D3D12_RESOURCE_DIMENSION_TEXTURE3D) ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : + D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + + hr = FillInitData(width, + height, + depth, + mipCount, + arraySize, + numberOfPlanes, + format, + maxsize, + bitSize, + bitData, + twidth, + theight, + tdepth, + skipMip, + subresources); if (SUCCEEDED(hr)) { - hr = CreateTextureResource(device, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, - format, resFlags, loadFlags, texture); + hr = CreateTextureResource(device, + resDim, + twidth, + theight, + tdepth, + mipCount - skipMip, + arraySize, + format, + resFlags, + loadFlags, + texture); } } } @@ -594,11 +618,9 @@ namespace } //-------------------------------------------------------------------------------------- - void SetDebugTextureInfo( - _In_z_ const wchar_t* fileName, - _In_ ID3D12Resource* texture) noexcept + void SetDebugTextureInfo(_In_z_ const wchar_t* fileName, _In_ ID3D12Resource* texture) noexcept { - #if !defined(NO_D3D12_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D12_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) const wchar_t* pstrName = wcsrchr(fileName, '\\'); if (!pstrName) { @@ -609,17 +631,16 @@ namespace pstrName++; } texture->SetName(pstrName); - #else +#else UNREFERENCED_PARAMETER(fileName); UNREFERENCED_PARAMETER(texture); - #endif +#endif } //-------------------------------------------------------------------------------------- DXGI_FORMAT GetPixelFormat(const DDS_HEADER* header) noexcept { - if ((header->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) + if ((header->ddspf.flags & DDS_FOURCC) && (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) { auto d3d10ext = reinterpret_cast(reinterpret_cast(header) + sizeof(DDS_HEADER)); return d3d10ext->dxgiFormat; @@ -629,21 +650,17 @@ namespace } } // anonymous namespace - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadDDSTextureFromMemory( - ID3D12Device* device, - const uint8_t* ddsData, - size_t ddsDataSize, - ID3D12Resource** texture, - std::vector& subresources, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::LoadDDSTextureFromMemory(ID3D12Device* device, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D12Resource** texture, + std::vector& subresources, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { - return LoadDDSTextureFromMemoryEx( - device, + return LoadDDSTextureFromMemoryEx(device, ddsData, ddsDataSize, maxsize, @@ -655,19 +672,16 @@ HRESULT DirectX::LoadDDSTextureFromMemory( isCubeMap); } - -_Use_decl_annotations_ -HRESULT DirectX::LoadDDSTextureFromMemoryEx( - ID3D12Device* device, - const uint8_t* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D12Resource** texture, - std::vector& subresources, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::LoadDDSTextureFromMemoryEx(ID3D12Device* device, + const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D12Resource** texture, + std::vector& subresources, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { if (texture) { @@ -688,25 +702,17 @@ HRESULT DirectX::LoadDDSTextureFromMemoryEx( } // Validate DDS file in memory - const DDS_HEADER* header = nullptr; - const uint8_t* bitData = nullptr; - size_t bitSize = 0; + const DDS_HEADER* header = nullptr; + const uint8_t* bitData = nullptr; + size_t bitSize = 0; - HRESULT hr = LoadTextureDataFromMemory(ddsData, - ddsDataSize, - &header, - &bitData, - &bitSize - ); + HRESULT hr = LoadTextureDataFromMemory(ddsData, ddsDataSize, &header, &bitData, &bitSize); if (FAILED(hr)) { return hr; } - hr = CreateTextureFromDDS(device, - header, bitData, bitSize, maxsize, - resFlags, loadFlags, - texture, subresources, isCubeMap); + hr = CreateTextureFromDDS(device, header, bitData, bitSize, maxsize, resFlags, loadFlags, texture, subresources, isCubeMap); if (SUCCEEDED(hr)) { SetDebugObjectName(*texture, L"DDSTextureLoader"); @@ -718,21 +724,17 @@ HRESULT DirectX::LoadDDSTextureFromMemoryEx( return hr; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadDDSTextureFromFile( - ID3D12Device* device, - const wchar_t* fileName, - ID3D12Resource** texture, - std::unique_ptr& ddsData, - std::vector& subresources, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::LoadDDSTextureFromFile(ID3D12Device* device, + const wchar_t* fileName, + ID3D12Resource** texture, + std::unique_ptr& ddsData, + std::vector& subresources, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { - return LoadDDSTextureFromFileEx( - device, + return LoadDDSTextureFromFileEx(device, fileName, maxsize, D3D12_RESOURCE_FLAG_NONE, @@ -744,18 +746,16 @@ HRESULT DirectX::LoadDDSTextureFromFile( isCubeMap); } -_Use_decl_annotations_ -HRESULT DirectX::LoadDDSTextureFromFileEx( - ID3D12Device* device, - const wchar_t* fileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D12Resource** texture, - std::unique_ptr& ddsData, - std::vector& subresources, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::LoadDDSTextureFromFileEx(ID3D12Device* device, + const wchar_t* fileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D12Resource** texture, + std::unique_ptr& ddsData, + std::vector& subresources, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { if (texture) { @@ -775,25 +775,17 @@ HRESULT DirectX::LoadDDSTextureFromFileEx( return E_INVALIDARG; } - const DDS_HEADER* header = nullptr; - const uint8_t* bitData = nullptr; - size_t bitSize = 0; + const DDS_HEADER* header = nullptr; + const uint8_t* bitData = nullptr; + size_t bitSize = 0; - HRESULT hr = LoadTextureDataFromFile(fileName, - ddsData, - &header, - &bitData, - &bitSize - ); + HRESULT hr = LoadTextureDataFromFile(fileName, ddsData, &header, &bitData, &bitSize); if (FAILED(hr)) { return hr; } - hr = CreateTextureFromDDS(device, - header, bitData, bitSize, maxsize, - resFlags, loadFlags, - texture, subresources, isCubeMap); + hr = CreateTextureFromDDS(device, header, bitData, bitSize, maxsize, resFlags, loadFlags, texture, subresources, isCubeMap); if (SUCCEEDED(hr)) { @@ -807,20 +799,17 @@ HRESULT DirectX::LoadDDSTextureFromFileEx( } //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromMemory( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const uint8_t* ddsData, - size_t ddsDataSize, - ID3D12Resource** texture, - bool generateMipsIfMissing, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemory(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D12Resource** texture, + bool generateMipsIfMissing, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { - return CreateDDSTextureFromMemoryEx( - device, + return CreateDDSTextureFromMemoryEx(device, resourceUpload, ddsData, ddsDataSize, @@ -832,19 +821,16 @@ HRESULT DirectX::CreateDDSTextureFromMemory( isCubeMap); } - -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromMemoryEx( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const uint8_t* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D12Resource** texture, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D12Resource** texture, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { if (texture) { @@ -865,16 +851,11 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( } // Validate DDS file in memory - const DDS_HEADER* header = nullptr; - const uint8_t* bitData = nullptr; - size_t bitSize = 0; + const DDS_HEADER* header = nullptr; + const uint8_t* bitData = nullptr; + size_t bitSize = 0; - HRESULT hr = LoadTextureDataFromMemory(ddsData, - ddsDataSize, - &header, - &bitData, - &bitSize - ); + HRESULT hr = LoadTextureDataFromMemory(ddsData, ddsDataSize, &header, &bitData, &bitSize); if (FAILED(hr)) { return hr; @@ -885,16 +866,14 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( const DXGI_FORMAT fmt = GetPixelFormat(header); if (!resourceUpload.IsSupportedForGenerateMips(fmt)) { - DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", static_cast(fmt)); + DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", + static_cast(fmt)); loadFlags &= ~DDS_LOADER_MIP_AUTOGEN; } } std::vector subresources; - hr = CreateTextureFromDDS(device, - header, bitData, bitSize, maxsize, - resFlags, loadFlags, - texture, subresources, isCubeMap); + hr = CreateTextureFromDDS(device, header, bitData, bitSize, maxsize, resFlags, loadFlags, texture, subresources, isCubeMap); if (SUCCEEDED(hr)) { @@ -903,24 +882,17 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( if (alphaMode) *alphaMode = GetAlphaMode(header); - resourceUpload.Upload( - *texture, - 0, - subresources.data(), - static_cast(subresources.size())); + resourceUpload.Upload(*texture, 0, subresources.data(), static_cast(subresources.size())); - resourceUpload.Transition( - *texture, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + resourceUpload.Transition(*texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); // If it's missing mips, let's generate them - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const size_t mipLevels = (*texture)->GetDesc().MipLevels; - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const size_t mipLevels = (*texture)->GetDesc(&tmpDesc)->MipLevels; - #endif + const size_t mipLevels = (*texture)->GetDesc(&tmpDesc)->MipLevels; +#endif if ((loadFlags & DDS_LOADER_MIP_AUTOGEN) && subresources.size() != mipLevels) { @@ -931,21 +903,17 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( return hr; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromFile( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const wchar_t* fileName, - ID3D12Resource** texture, - bool generateMipsIfMissing, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFile(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const wchar_t* fileName, + ID3D12Resource** texture, + bool generateMipsIfMissing, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { - return CreateDDSTextureFromFileEx( - device, + return CreateDDSTextureFromFileEx(device, resourceUpload, fileName, maxsize, @@ -956,17 +924,15 @@ HRESULT DirectX::CreateDDSTextureFromFile( isCubeMap); } -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromFileEx( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const wchar_t* fileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D12Resource** texture, - DDS_ALPHA_MODE* alphaMode, - bool* isCubeMap) +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const wchar_t* fileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D12Resource** texture, + DDS_ALPHA_MODE* alphaMode, + bool* isCubeMap) { if (texture) { @@ -986,17 +952,12 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( return E_INVALIDARG; } - const DDS_HEADER* header = nullptr; - const uint8_t* bitData = nullptr; - size_t bitSize = 0; + const DDS_HEADER* header = nullptr; + const uint8_t* bitData = nullptr; + size_t bitSize = 0; std::unique_ptr ddsData; - HRESULT hr = LoadTextureDataFromFile(fileName, - ddsData, - &header, - &bitData, - &bitSize - ); + HRESULT hr = LoadTextureDataFromFile(fileName, ddsData, &header, &bitData, &bitSize); if (FAILED(hr)) { return hr; @@ -1007,16 +968,14 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( const DXGI_FORMAT fmt = GetPixelFormat(header); if (!resourceUpload.IsSupportedForGenerateMips(fmt)) { - DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", static_cast(fmt)); + DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", + static_cast(fmt)); loadFlags &= ~DDS_LOADER_MIP_AUTOGEN; } } std::vector subresources; - hr = CreateTextureFromDDS(device, - header, bitData, bitSize, maxsize, - resFlags, loadFlags, - texture, subresources, isCubeMap); + hr = CreateTextureFromDDS(device, header, bitData, bitSize, maxsize, resFlags, loadFlags, texture, subresources, isCubeMap); if (SUCCEEDED(hr)) { @@ -1025,24 +984,17 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( if (alphaMode) *alphaMode = GetAlphaMode(header); - resourceUpload.Upload( - *texture, - 0, - subresources.data(), - static_cast(subresources.size())); + resourceUpload.Upload(*texture, 0, subresources.data(), static_cast(subresources.size())); - resourceUpload.Transition( - *texture, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + resourceUpload.Transition(*texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); // If it's missing mips, let's generate them - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const size_t mipLevels = (*texture)->GetDesc().MipLevels; - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const size_t mipLevels = (*texture)->GetDesc(&tmpDesc)->MipLevels; - #endif + const size_t mipLevels = (*texture)->GetDesc(&tmpDesc)->MipLevels; +#endif if ((loadFlags & DDS_LOADER_MIP_AUTOGEN) && subresources.size() != mipLevels) { @@ -1053,7 +1005,6 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( return hr; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients @@ -1061,68 +1012,87 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( namespace DirectX { - HRESULT __cdecl LoadDDSTextureFromFile( - _In_ ID3D12Device* device, - _In_z_ const __wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& ddsData, - std::vector& subresources, - size_t maxsize, - _Out_opt_ DDS_ALPHA_MODE* alphaMode, - _Out_opt_ bool* isCubeMap) + HRESULT __cdecl LoadDDSTextureFromFile(_In_ ID3D12Device* device, + _In_z_ const __wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& ddsData, + std::vector& subresources, + size_t maxsize, + _Out_opt_ DDS_ALPHA_MODE* alphaMode, + _Out_opt_ bool* isCubeMap) { return LoadDDSTextureFromFile(device, reinterpret_cast(szFileName), - texture, ddsData, subresources, maxsize, alphaMode, isCubeMap); + texture, + ddsData, + subresources, + maxsize, + alphaMode, + isCubeMap); } - HRESULT __cdecl CreateDDSTextureFromFile( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const __wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - bool generateMipsIfMissing, - size_t maxsize, - _Out_opt_ DDS_ALPHA_MODE* alphaMode, - _Out_opt_ bool* isCubeMap) + HRESULT __cdecl CreateDDSTextureFromFile(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const __wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + bool generateMipsIfMissing, + size_t maxsize, + _Out_opt_ DDS_ALPHA_MODE* alphaMode, + _Out_opt_ bool* isCubeMap) { - return CreateDDSTextureFromFile(device, resourceUpload, + return CreateDDSTextureFromFile(device, + resourceUpload, reinterpret_cast(szFileName), - texture, generateMipsIfMissing, maxsize, alphaMode, isCubeMap); + texture, + generateMipsIfMissing, + maxsize, + alphaMode, + isCubeMap); } - HRESULT __cdecl LoadDDSTextureFromFileEx( - _In_ ID3D12Device* device, - _In_z_ const __wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& ddsData, - std::vector& subresources, - _Out_opt_ DDS_ALPHA_MODE* alphaMode, - _Out_opt_ bool* isCubeMap) + HRESULT __cdecl LoadDDSTextureFromFileEx(_In_ ID3D12Device* device, + _In_z_ const __wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& ddsData, + std::vector& subresources, + _Out_opt_ DDS_ALPHA_MODE* alphaMode, + _Out_opt_ bool* isCubeMap) { return LoadDDSTextureFromFileEx(device, reinterpret_cast(szFileName), - maxsize, resFlags, loadFlags, texture, ddsData, subresources, alphaMode, isCubeMap); + maxsize, + resFlags, + loadFlags, + texture, + ddsData, + subresources, + alphaMode, + isCubeMap); } - HRESULT __cdecl CreateDDSTextureFromFileEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const __wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - DDS_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - _Out_opt_ DDS_ALPHA_MODE* alphaMode, - _Out_opt_ bool* isCubeMap) + HRESULT __cdecl CreateDDSTextureFromFileEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const __wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + DDS_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + _Out_opt_ DDS_ALPHA_MODE* alphaMode, + _Out_opt_ bool* isCubeMap) { - return CreateDDSTextureFromFileEx(device, resourceUpload, + return CreateDDSTextureFromFileEx(device, + resourceUpload, reinterpret_cast(szFileName), - maxsize, resFlags, loadFlags, texture, alphaMode, isCubeMap); + maxsize, + resFlags, + loadFlags, + texture, + alphaMode, + isCubeMap); } -} +} // namespace DirectX #endif // !_NATIVE_WCHAR_T_DEFINED diff --git a/Src/DebugEffect.cpp b/Src/DebugEffect.cpp index 02329903..f0bfc453 100644 --- a/Src/DebugEffect.cpp +++ b/Src/DebugEffect.cpp @@ -27,30 +27,31 @@ namespace static_assert((sizeof(DebugEffectConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct DebugEffectTraits { using ConstantBufferType = DebugEffectConstants; - static constexpr int VertexShaderCount = 8; - static constexpr int PixelShaderCount = 4; + static constexpr int VertexShaderCount = 8; + static constexpr int PixelShaderCount = 4; static constexpr int ShaderPermutationCount = 32; - static constexpr int RootSignatureCount = 1; + static constexpr int RootSignatureCount = 1; }; -} +} // namespace // Internal DebugEffect implementation class. class DebugEffect::Impl : public EffectBase { public: - Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - DebugEffect::Mode debugMode); + Impl(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + DebugEffect::Mode debugMode); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; enum RootParameterIndex @@ -64,7 +65,6 @@ class DebugEffect::Impl : public EffectBase void Apply(_In_ ID3D12GraphicsCommandList* commandList); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -138,119 +138,112 @@ namespace #include "DebugEffect_PSRGBTangents.inc" #include "DebugEffect_PSRGBBiTangents.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { DebugEffect_VSDebug, sizeof(DebugEffect_VSDebug) }, - { DebugEffect_VSDebugVc, sizeof(DebugEffect_VSDebugVc) }, - { DebugEffect_VSDebugBn, sizeof(DebugEffect_VSDebugBn) }, - { DebugEffect_VSDebugVcBn, sizeof(DebugEffect_VSDebugVcBn) }, - { DebugEffect_VSDebugInst, sizeof(DebugEffect_VSDebugInst) }, - { DebugEffect_VSDebugVcInst, sizeof(DebugEffect_VSDebugVcInst) }, - { DebugEffect_VSDebugBnInst, sizeof(DebugEffect_VSDebugBnInst) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { DebugEffect_VSDebug, sizeof(DebugEffect_VSDebug) }, + { DebugEffect_VSDebugVc, sizeof(DebugEffect_VSDebugVc) }, + { DebugEffect_VSDebugBn, sizeof(DebugEffect_VSDebugBn) }, + { DebugEffect_VSDebugVcBn, sizeof(DebugEffect_VSDebugVcBn) }, + { DebugEffect_VSDebugInst, sizeof(DebugEffect_VSDebugInst) }, + { DebugEffect_VSDebugVcInst, sizeof(DebugEffect_VSDebugVcInst) }, + { DebugEffect_VSDebugBnInst, sizeof(DebugEffect_VSDebugBnInst) }, { DebugEffect_VSDebugVcBnInst, sizeof(DebugEffect_VSDebugVcBnInst) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // default - 0, // normals - 0, // tangents - 0, // bitangents - - 1, // vertex color + default - 1, // vertex color + normals - 1, // vertex color + tangents - 1, // vertex color + bitangents - - 2, // default (biased vertex normal) - 2, // normals (biased vertex normal) - 2, // tangents (biased vertex normal) - 2, // bitangents (biased vertex normal) - - 3, // vertex color (biased vertex normal) - 3, // vertex color (biased vertex normal) + normals - 3, // vertex color (biased vertex normal) + tangents - 3, // vertex color (biased vertex normal) + bitangents - - 4, // instancing - 4, // instancing + normals - 4, // instancing + tangents - 4, // instancing + bitangents - - 5, // instancing + vertex color + default - 5, // instancing + vertex color + normals - 5, // instancing + vertex color + tangents - 5, // instancing + vertex color + bitangents - - 6, // instancing (biased vertex normal) - 6, // instancing + normals (biased vertex normal) - 6, // instancing + tangents (biased vertex normal) - 6, // instancing + bitangents (biased vertex normal) - - 7, // instancing + vertex color (biased vertex normal) - 7, // instancing + vertex color (biased vertex normal) + normals - 7, // instancing + vertex color (biased vertex normal) + tangents - 7, // instancing + vertex color (biased vertex normal) + bitangents}; +const int EffectBase::VertexShaderIndices[] = { + 0, // default + 0, // normals + 0, // tangents + 0, // bitangents + + 1, // vertex color + default + 1, // vertex color + normals + 1, // vertex color + tangents + 1, // vertex color + bitangents + + 2, // default (biased vertex normal) + 2, // normals (biased vertex normal) + 2, // tangents (biased vertex normal) + 2, // bitangents (biased vertex normal) + + 3, // vertex color (biased vertex normal) + 3, // vertex color (biased vertex normal) + normals + 3, // vertex color (biased vertex normal) + tangents + 3, // vertex color (biased vertex normal) + bitangents + + 4, // instancing + 4, // instancing + normals + 4, // instancing + tangents + 4, // instancing + bitangents + + 5, // instancing + vertex color + default + 5, // instancing + vertex color + normals + 5, // instancing + vertex color + tangents + 5, // instancing + vertex color + bitangents + + 6, // instancing (biased vertex normal) + 6, // instancing + normals (biased vertex normal) + 6, // instancing + tangents (biased vertex normal) + 6, // instancing + bitangents (biased vertex normal) + + 7, // instancing + vertex color (biased vertex normal) + 7, // instancing + vertex color (biased vertex normal) + normals + 7, // instancing + vertex color (biased vertex normal) + tangents + 7, // instancing + vertex color (biased vertex normal) + bitangents}; }; template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { DebugEffect_PSHemiAmbient, sizeof(DebugEffect_PSHemiAmbient) }, - { DebugEffect_PSRGBNormals, sizeof(DebugEffect_PSRGBNormals) }, - { DebugEffect_PSRGBTangents, sizeof(DebugEffect_PSRGBTangents) }, - { DebugEffect_PSRGBBiTangents, sizeof(DebugEffect_PSRGBBiTangents) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { DebugEffect_PSHemiAmbient, sizeof(DebugEffect_PSHemiAmbient) }, + { DebugEffect_PSRGBNormals, sizeof(DebugEffect_PSRGBNormals) }, + { DebugEffect_PSRGBTangents, sizeof(DebugEffect_PSRGBTangents) }, + { DebugEffect_PSRGBBiTangents, sizeof(DebugEffect_PSRGBBiTangents) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // default - 1, // normals - 2, // tangents - 3, // bitangents - - 0, // vertex color + default - 1, // vertex color + normals - 2, // vertex color + tangents - 3, // vertex color + bitangents - - 0, // default (biased vertex normal) - 1, // normals (biased vertex normal) - 2, // tangents (biased vertex normal) - 3, // bitangents (biased vertex normal) - - 0, // vertex color (biased vertex normal) - 1, // vertex color (biased vertex normal) + normals - 2, // vertex color (biased vertex normal) + tangents - 3, // vertex color (biased vertex normal) + bitangents - - 0, // instancing - 1, // instancing + normals - 2, // instancing + tangents - 3, // instancing + bitangents - - 0, // instancing + vertex color + default - 1, // instancing + vertex color + normals - 2, // instancing + vertex color + tangents - 3, // instancing + vertex color + bitangents - - 0, // instancing (biased vertex normal) - 1, // instancing + normals (biased vertex normal) - 2, // instancing + tangents (biased vertex normal) - 3, // instancing + bitangents (biased vertex normal) - - 0, // instancing + vertex color (biased vertex normal) - 1, // instancing + vertex color (biased vertex normal) + normals - 2, // instancing + vertex color (biased vertex normal) + tangents - 3, // instancing + vertex color (biased vertex normal) + bitangents +const int EffectBase::PixelShaderIndices[] = { + 0, // default + 1, // normals + 2, // tangents + 3, // bitangents + + 0, // vertex color + default + 1, // vertex color + normals + 2, // vertex color + tangents + 3, // vertex color + bitangents + + 0, // default (biased vertex normal) + 1, // normals (biased vertex normal) + 2, // tangents (biased vertex normal) + 3, // bitangents (biased vertex normal) + + 0, // vertex color (biased vertex normal) + 1, // vertex color (biased vertex normal) + normals + 2, // vertex color (biased vertex normal) + tangents + 3, // vertex color (biased vertex normal) + bitangents + + 0, // instancing + 1, // instancing + normals + 2, // instancing + tangents + 3, // instancing + bitangents + + 0, // instancing + vertex color + default + 1, // instancing + vertex color + normals + 2, // instancing + vertex color + tangents + 3, // instancing + vertex color + bitangents + + 0, // instancing (biased vertex normal) + 1, // instancing + normals (biased vertex normal) + 2, // instancing + tangents (biased vertex normal) + 3, // instancing + bitangents (biased vertex normal) + + 0, // instancing + vertex color (biased vertex normal) + 1, // instancing + vertex color (biased vertex normal) + normals + 2, // instancing + vertex color (biased vertex normal) + tangents + 3, // instancing + vertex color (biased vertex normal) + bitangents }; #pragma endregion @@ -258,48 +251,47 @@ const int EffectBase::PixelShaderIndices[] = template<> SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - // Constructor. -DebugEffect::Impl::Impl( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - DebugEffect::Mode debugMode) +DebugEffect::Impl::Impl(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + DebugEffect::Mode debugMode) : EffectBase(device) { - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == DebugEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == DebugEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) + == DebugEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == DebugEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == DebugEffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) + == DebugEffectTraits::ShaderPermutationCount, + "array/max mismatch"); static const XMVECTORF32 s_lower = { { { 0.f, 0.f, 0.f, 1.f } } }; constants.ambientDownAndAlpha = s_lower; - constants.ambientRange = g_XMOne; + constants.ambientRange = g_XMOne; - switch(debugMode) + switch (debugMode) { - case Mode_Default: - case Mode_Normals: - case Mode_Tangents: - case Mode_BiTangents: - break; - - default: - throw std::invalid_argument("Invalid debugMode"); + case Mode_Default: + case Mode_Normals: + case Mode_Tangents: + case Mode_BiTangents: break; + + default: throw std::invalid_argument("Invalid debugMode"); } // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; // Create root parameters and initialize first (constants) @@ -328,8 +320,7 @@ DebugEffect::Impl::Impl( assert(pi >= 0 && pi < DebugEffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < DebugEffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -338,7 +329,6 @@ DebugEffect::Impl::Impl( SetDebugObjectName(mPipelineState.Get(), L"DebugEffect"); } - int DebugEffect::Impl::GetPipelineStatePermutation(DebugEffect::Mode debugMode, uint32_t effectFlags) const noexcept { int permutation = static_cast(debugMode); @@ -364,18 +354,12 @@ int DebugEffect::Impl::GetPipelineStatePermutation(DebugEffect::Mode debugMode, return permutation; } - // Sets our state onto the D3D device. void DebugEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { // Compute derived parameter values. XMVECTOR eyePosition{}; - matrices.SetConstants( - dirtyFlags, - constants.world, - constants.worldInverseTranspose, - constants.worldViewProj, - eyePosition); + matrices.SetConstants(dirtyFlags, constants.world, constants.worldInverseTranspose, constants.worldViewProj, eyePosition); UpdateConstants(); @@ -389,21 +373,17 @@ void DebugEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - // Public constructor. -DebugEffect::DebugEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - Mode debugMode) +DebugEffect::DebugEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + Mode debugMode) : pImpl(std::make_unique(device, effectFlags, pipelineDescription, debugMode)) {} - -DebugEffect::DebugEffect(DebugEffect&&) noexcept = default; -DebugEffect& DebugEffect::operator= (DebugEffect&&) noexcept = default; -DebugEffect::~DebugEffect() = default; - +DebugEffect::DebugEffect(DebugEffect&&) noexcept = default; +DebugEffect& DebugEffect::operator=(DebugEffect&&) noexcept = default; +DebugEffect::~DebugEffect() = default; // IEffect methods. void DebugEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -411,7 +391,6 @@ void DebugEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings. void XM_CALLCONV DebugEffect::SetWorld(FXMMATRIX value) { @@ -420,7 +399,6 @@ void XM_CALLCONV DebugEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose; } - void XM_CALLCONV DebugEffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -428,7 +406,6 @@ void XM_CALLCONV DebugEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV DebugEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -436,17 +413,15 @@ void XM_CALLCONV DebugEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV DebugEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose; } - // Material settings. void XM_CALLCONV DebugEffect::SetHemisphericalAmbientColor(FXMVECTOR upper, FXMVECTOR lower) { diff --git a/Src/DemandCreate.h b/Src/DemandCreate.h index 7f124a76..90d9cc77 100644 --- a/Src/DemandCreate.h +++ b/Src/DemandCreate.h @@ -12,7 +12,6 @@ #include "PlatformHelpers.h" - namespace DirectX { // Helper for lazily creating a D3D resource. @@ -22,13 +21,13 @@ namespace DirectX T* result = comPtr.Get(); // Double-checked lock pattern. - #ifdef _MSC_VER +#ifdef _MSC_VER MemoryBarrier(); - #elif defined(__GNUC__) +#elif defined(__GNUC__) __sync_synchronize(); - #else - #error Unknown memory barrier syntax - #endif +#else +#error Unknown memory barrier syntax +#endif if (!result) { @@ -39,15 +38,13 @@ namespace DirectX if (!result) { // Create the new object. - ThrowIfFailed( - createFunc(&result) - ); + ThrowIfFailed(createFunc(&result)); - #ifdef _MSC_VER +#ifdef _MSC_VER MemoryBarrier(); - #elif defined(__GNUC__) +#elif defined(__GNUC__) __sync_synchronize(); - #endif +#endif comPtr.Attach(result); } @@ -55,4 +52,4 @@ namespace DirectX return result; } -} +} // namespace DirectX diff --git a/Src/DescriptorHeap.cpp b/Src/DescriptorHeap.cpp index 6e4f9a8c..3132b77a 100644 --- a/Src/DescriptorHeap.cpp +++ b/Src/DescriptorHeap.cpp @@ -19,22 +19,18 @@ namespace { struct DescriptorHeapDesc { - D3D12_DESCRIPTOR_HEAP_TYPE Type; + D3D12_DESCRIPTOR_HEAP_TYPE Type; D3D12_DESCRIPTOR_HEAP_FLAGS Flags; }; - static const DescriptorHeapDesc c_DescriptorHeapDescs[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES] = - { - { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, - { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, - { D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE }, - { D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE } - }; -} + static const DescriptorHeapDesc c_DescriptorHeapDescs[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES] + = { { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, + { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, + { D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE }, + { D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE } }; +} // namespace -_Use_decl_annotations_ -DescriptorHeap::DescriptorHeap( - ID3D12DescriptorHeap* pExistingHeap) +_Use_decl_annotations_ DescriptorHeap::DescriptorHeap(ID3D12DescriptorHeap* pExistingHeap) : m_pHeap(pExistingHeap) { if (!pExistingHeap) @@ -56,54 +52,44 @@ DescriptorHeap::DescriptorHeap( m_increment = device->GetDescriptorHandleIncrementSize(m_desc.Type); } -_Use_decl_annotations_ -DescriptorHeap::DescriptorHeap( - ID3D12Device* device, - const D3D12_DESCRIPTOR_HEAP_DESC* pDesc) : - m_desc{}, - m_hCPU{}, - m_hGPU{}, - m_increment(0) +_Use_decl_annotations_ DescriptorHeap::DescriptorHeap(ID3D12Device* device, const D3D12_DESCRIPTOR_HEAP_DESC* pDesc) + : m_desc{}, + m_hCPU{}, + m_hGPU{}, + m_increment(0) { Create(device, pDesc); } _Use_decl_annotations_ -DescriptorHeap::DescriptorHeap( - ID3D12Device* device, - D3D12_DESCRIPTOR_HEAP_TYPE type, - D3D12_DESCRIPTOR_HEAP_FLAGS flags, - size_t count) : - m_desc{}, - m_hCPU{}, - m_hGPU{}, - m_increment(0) +DescriptorHeap::DescriptorHeap(ID3D12Device* device, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags, size_t count) + : m_desc{}, + m_hCPU{}, + m_hGPU{}, + m_increment(0) { if (count > UINT32_MAX) throw std::invalid_argument("Too many descriptors"); D3D12_DESCRIPTOR_HEAP_DESC desc = {}; - desc.Flags = flags; - desc.NumDescriptors = static_cast(count); - desc.Type = type; + desc.Flags = flags; + desc.NumDescriptors = static_cast(count); + desc.Type = type; Create(device, &desc); } -_Use_decl_annotations_ -D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors( - ID3D12Device* device, - uint32_t offsetIntoHeap, - uint32_t totalDescriptorCount, - const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, - const uint32_t* pDescriptorRangeSizes, - uint32_t descriptorRangeCount) +_Use_decl_annotations_ D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors(ID3D12Device* device, + uint32_t offsetIntoHeap, + uint32_t totalDescriptorCount, + const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, + const uint32_t* pDescriptorRangeSizes, + uint32_t descriptorRangeCount) { assert((size_t(offsetIntoHeap) + size_t(totalDescriptorCount)) <= size_t(m_desc.NumDescriptors)); const D3D12_CPU_DESCRIPTOR_HANDLE cpuHandle = GetCpuHandle(offsetIntoHeap); - device->CopyDescriptors( - 1, + device->CopyDescriptors(1, &cpuHandle, &totalDescriptorCount, descriptorRangeCount, @@ -116,20 +102,17 @@ D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors( return gpuHandle; } -_Use_decl_annotations_ -D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors( - ID3D12Device* device, - uint32_t offsetIntoHeap, - const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, - const uint32_t* pDescriptorRangeSizes, - uint32_t descriptorRangeCount) +_Use_decl_annotations_ D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors(ID3D12Device* device, + uint32_t offsetIntoHeap, + const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptorRangeStarts, + const uint32_t* pDescriptorRangeSizes, + uint32_t descriptorRangeCount) { uint32_t totalDescriptorCount = 0; for (uint32_t i = 0; i < descriptorRangeCount; ++i) totalDescriptorCount += pDescriptorRangeSizes[i]; - return WriteDescriptors( - device, + return WriteDescriptors(device, offsetIntoHeap, totalDescriptorCount, pDescriptorRangeStarts, @@ -137,33 +120,22 @@ D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors( descriptorRangeCount); } -_Use_decl_annotations_ -D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors( - ID3D12Device* device, - uint32_t offsetIntoHeap, - const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptors, - uint32_t descriptorCount) +_Use_decl_annotations_ D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::WriteDescriptors(ID3D12Device* device, + uint32_t offsetIntoHeap, + const D3D12_CPU_DESCRIPTOR_HANDLE* pDescriptors, + uint32_t descriptorCount) { - return WriteDescriptors( - device, - offsetIntoHeap, - descriptorCount, - pDescriptors, - &descriptorCount, - 1); + return WriteDescriptors(device, offsetIntoHeap, descriptorCount, pDescriptors, &descriptorCount, 1); } -_Use_decl_annotations_ -void DescriptorHeap::Create( - ID3D12Device* pDevice, - const D3D12_DESCRIPTOR_HEAP_DESC* pDesc) +_Use_decl_annotations_ void DescriptorHeap::Create(ID3D12Device* pDevice, const D3D12_DESCRIPTOR_HEAP_DESC* pDesc) { if (!pDevice) throw std::invalid_argument("Direct3D device is null"); assert(pDesc != nullptr); - m_desc = *pDesc; + m_desc = *pDesc; m_increment = pDevice->GetDescriptorHandleIncrementSize(pDesc->Type); if (pDesc->NumDescriptors == 0) @@ -174,40 +146,34 @@ void DescriptorHeap::Create( } else { - ThrowIfFailed(pDevice->CreateDescriptorHeap( - pDesc, - IID_GRAPHICS_PPV_ARGS(m_pHeap.ReleaseAndGetAddressOf()))); + ThrowIfFailed(pDevice->CreateDescriptorHeap(pDesc, IID_GRAPHICS_PPV_ARGS(m_pHeap.ReleaseAndGetAddressOf()))); SetDebugObjectName(m_pHeap.Get(), L"DescriptorHeap"); - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) m_hCPU = m_pHeap->GetCPUDescriptorHandleForHeapStart(); if (pDesc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) { m_hGPU = m_pHeap->GetGPUDescriptorHandleForHeapStart(); } - #else +#else std::ignore = m_pHeap->GetCPUDescriptorHandleForHeapStart(&m_hCPU); if (pDesc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) { std::ignore = m_pHeap->GetGPUDescriptorHandleForHeapStart(&m_hGPU); } - #endif +#endif } } -_Use_decl_annotations_ -void DescriptorHeap::DefaultDesc( - D3D12_DESCRIPTOR_HEAP_TYPE type, - D3D12_DESCRIPTOR_HEAP_DESC* pDesc) noexcept +_Use_decl_annotations_ void DescriptorHeap::DefaultDesc(D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_DESC* pDesc) noexcept { assert(c_DescriptorHeapDescs[type].Type == type); - pDesc->Flags = c_DescriptorHeapDescs[type].Flags; + pDesc->Flags = c_DescriptorHeapDescs[type].Flags; pDesc->NumDescriptors = 0; - pDesc->Type = type; + pDesc->Type = type; } - //====================================================================================== // DescriptorPile //====================================================================================== diff --git a/Src/DirectXHelpers.cpp b/Src/DirectXHelpers.cpp index 43e0d7de..8d11308e 100644 --- a/Src/DirectXHelpers.cpp +++ b/Src/DirectXHelpers.cpp @@ -14,12 +14,8 @@ using namespace DirectX; -_Use_decl_annotations_ -void DirectX::CreateShaderResourceView( - ID3D12Device* device, - ID3D12Resource* tex, - D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, - bool isCubeMap) +_Use_decl_annotations_ void +DirectX::CreateShaderResourceView(ID3D12Device* device, ID3D12Resource* tex, D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, bool isCubeMap) { if (!device || !tex) throw std::invalid_argument("Direct3D device and resource must be valid"); @@ -28,7 +24,7 @@ void DirectX::CreateShaderResourceView( const auto desc = tex->GetDesc(); #else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *tex->GetDesc(&tmpDesc); + const auto& desc = *tex->GetDesc(&tmpDesc); #endif if ((desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) != 0) @@ -38,8 +34,8 @@ void DirectX::CreateShaderResourceView( } D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; - srvDesc.Format = desc.Format; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Format = desc.Format; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; const UINT mipLevels = (desc.MipLevels) ? static_cast(desc.MipLevels) : static_cast(-1); @@ -48,13 +44,13 @@ void DirectX::CreateShaderResourceView( case D3D12_RESOURCE_DIMENSION_TEXTURE1D: if (desc.DepthOrArraySize > 1) { - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; srvDesc.Texture1DArray.MipLevels = mipLevels; srvDesc.Texture1DArray.ArraySize = static_cast(desc.DepthOrArraySize); } else { - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; srvDesc.Texture1D.MipLevels = mipLevels; } break; @@ -64,31 +60,31 @@ void DirectX::CreateShaderResourceView( { if (desc.DepthOrArraySize > 6) { - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; srvDesc.TextureCubeArray.MipLevels = mipLevels; - srvDesc.TextureCubeArray.NumCubes = static_cast(desc.DepthOrArraySize / 6); + srvDesc.TextureCubeArray.NumCubes = static_cast(desc.DepthOrArraySize / 6); } else { - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; srvDesc.TextureCube.MipLevels = mipLevels; } } else if (desc.DepthOrArraySize > 1) { - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; srvDesc.Texture2DArray.MipLevels = mipLevels; srvDesc.Texture2DArray.ArraySize = static_cast(desc.DepthOrArraySize); } else { - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = mipLevels; } break; case D3D12_RESOURCE_DIMENSION_TEXTURE3D: - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; srvDesc.Texture3D.MipLevels = mipLevels; break; @@ -105,12 +101,8 @@ void DirectX::CreateShaderResourceView( device->CreateShaderResourceView(tex, &srvDesc, srvDescriptor); } -_Use_decl_annotations_ -void DirectX::CreateUnorderedAccessView( - ID3D12Device* device, - ID3D12Resource* tex, - D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, - uint32_t mipLevel) +_Use_decl_annotations_ void +DirectX::CreateUnorderedAccessView(ID3D12Device* device, ID3D12Resource* tex, D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, uint32_t mipLevel) { if (!device || !tex) throw std::invalid_argument("Direct3D device and resource must be valid"); @@ -119,7 +111,7 @@ void DirectX::CreateUnorderedAccessView( const auto desc = tex->GetDesc(); #else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *tex->GetDesc(&tmpDesc); + const auto& desc = *tex->GetDesc(&tmpDesc); #endif if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) == 0) @@ -129,21 +121,21 @@ void DirectX::CreateUnorderedAccessView( } D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; - uavDesc.Format = desc.Format; + uavDesc.Format = desc.Format; switch (desc.Dimension) { case D3D12_RESOURCE_DIMENSION_TEXTURE1D: if (desc.DepthOrArraySize > 1) { - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; - uavDesc.Texture1DArray.MipSlice = mipLevel; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + uavDesc.Texture1DArray.MipSlice = mipLevel; uavDesc.Texture1DArray.FirstArraySlice = 0; - uavDesc.Texture1DArray.ArraySize = desc.DepthOrArraySize; + uavDesc.Texture1DArray.ArraySize = desc.DepthOrArraySize; } else { - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; uavDesc.Texture1D.MipSlice = mipLevel; } break; @@ -151,21 +143,21 @@ void DirectX::CreateUnorderedAccessView( case D3D12_RESOURCE_DIMENSION_TEXTURE2D: if (desc.DepthOrArraySize > 1) { - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; - uavDesc.Texture2DArray.MipSlice = mipLevel; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + uavDesc.Texture2DArray.MipSlice = mipLevel; uavDesc.Texture2DArray.ArraySize = desc.DepthOrArraySize; } else { - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; uavDesc.Texture2D.MipSlice = mipLevel; } break; case D3D12_RESOURCE_DIMENSION_TEXTURE3D: - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; uavDesc.Texture3D.MipSlice = mipLevel; - uavDesc.Texture3D.WSize = desc.DepthOrArraySize; + uavDesc.Texture3D.WSize = desc.DepthOrArraySize; break; case D3D12_RESOURCE_DIMENSION_BUFFER: @@ -176,17 +168,12 @@ void DirectX::CreateUnorderedAccessView( default: DebugTrace("ERROR: CreateUnorderedResourceView cannot be used with DIMENSION_UNKNOWN (%d).\n", desc.Dimension); throw std::invalid_argument("unknown resource dimension"); - } device->CreateUnorderedAccessView(tex, nullptr, &uavDesc, uavDescriptor); } -_Use_decl_annotations_ -void DirectX::CreateRenderTargetView( - ID3D12Device* device, - ID3D12Resource* tex, - D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor, - uint32_t mipLevel) +_Use_decl_annotations_ void +DirectX::CreateRenderTargetView(ID3D12Device* device, ID3D12Resource* tex, D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor, uint32_t mipLevel) { if (!device || !tex) throw std::invalid_argument("Direct3D device and resource must be valid"); @@ -195,7 +182,7 @@ void DirectX::CreateRenderTargetView( const auto desc = tex->GetDesc(); #else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *tex->GetDesc(&tmpDesc); + const auto& desc = *tex->GetDesc(&tmpDesc); #endif if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) == 0) @@ -205,21 +192,21 @@ void DirectX::CreateRenderTargetView( } D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {}; - rtvDesc.Format = desc.Format; + rtvDesc.Format = desc.Format; switch (desc.Dimension) { case D3D12_RESOURCE_DIMENSION_TEXTURE1D: if (desc.DepthOrArraySize > 1) { - rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; - rtvDesc.Texture1DArray.MipSlice = mipLevel; + rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; + rtvDesc.Texture1DArray.MipSlice = mipLevel; rtvDesc.Texture1DArray.FirstArraySlice = 0; - rtvDesc.Texture1DArray.ArraySize = desc.DepthOrArraySize; + rtvDesc.Texture1DArray.ArraySize = desc.DepthOrArraySize; } else { - rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; + rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; rtvDesc.Texture1D.MipSlice = mipLevel; } break; @@ -229,7 +216,7 @@ void DirectX::CreateRenderTargetView( { if (desc.DepthOrArraySize > 1) { - rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; + rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; rtvDesc.Texture2DMSArray.ArraySize = desc.DepthOrArraySize; } else @@ -239,21 +226,21 @@ void DirectX::CreateRenderTargetView( } else if (desc.DepthOrArraySize > 1) { - rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; - rtvDesc.Texture2DArray.MipSlice = mipLevel; + rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + rtvDesc.Texture2DArray.MipSlice = mipLevel; rtvDesc.Texture2DArray.ArraySize = desc.DepthOrArraySize; } else { - rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = mipLevel; } break; case D3D12_RESOURCE_DIMENSION_TEXTURE3D: - rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; + rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; rtvDesc.Texture3D.MipSlice = mipLevel; - rtvDesc.Texture3D.WSize = desc.DepthOrArraySize; + rtvDesc.Texture3D.WSize = desc.DepthOrArraySize; break; case D3D12_RESOURCE_DIMENSION_BUFFER: @@ -264,17 +251,14 @@ void DirectX::CreateRenderTargetView( default: DebugTrace("ERROR: CreateRenderTargetView cannot be used with DIMENSION_UNKNOWN (%d).\n", desc.Dimension); throw std::invalid_argument("unknown resource dimension"); - } device->CreateRenderTargetView(tex, &rtvDesc, rtvDescriptor); } -_Use_decl_annotations_ -void DirectX::CreateBufferShaderResourceView( - ID3D12Device* device, - ID3D12Resource* buffer, - D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, - uint32_t stride) +_Use_decl_annotations_ void DirectX::CreateBufferShaderResourceView(ID3D12Device* device, + ID3D12Resource* buffer, + D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor, + uint32_t stride) { if (!device || !buffer) throw std::invalid_argument("Direct3D device and resource must be valid"); @@ -283,38 +267,33 @@ void DirectX::CreateBufferShaderResourceView( const auto desc = buffer->GetDesc(); #else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *buffer->GetDesc(&tmpDesc); + const auto& desc = *buffer->GetDesc(&tmpDesc); #endif - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER - || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) != 0) + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) != 0) { DebugTrace("ERROR: CreateBufferShaderResourceView called on an unsupported resource.\n"); throw std::runtime_error("invalid buffer resource"); } D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; - srvDesc.Format = DXGI_FORMAT_UNKNOWN; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Buffer.FirstElement = 0; - srvDesc.Buffer.NumElements = (stride > 0) - ? static_cast(desc.Width / stride) - : static_cast(desc.Width); - srvDesc.Buffer.StructureByteStride = stride; + srvDesc.Format = DXGI_FORMAT_UNKNOWN; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Buffer.FirstElement = 0; + srvDesc.Buffer.NumElements = (stride > 0) ? static_cast(desc.Width / stride) : static_cast(desc.Width); + srvDesc.Buffer.StructureByteStride = stride; device->CreateShaderResourceView(buffer, &srvDesc, srvDescriptor); } -_Use_decl_annotations_ -void DirectX::CreateBufferUnorderedAccessView( - ID3D12Device* device, - ID3D12Resource* buffer, - D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, - uint32_t stride, - D3D12_BUFFER_UAV_FLAGS flag, - uint32_t counterOffset, - ID3D12Resource* counterResource) +_Use_decl_annotations_ void DirectX::CreateBufferUnorderedAccessView(ID3D12Device* device, + ID3D12Resource* buffer, + D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptor, + uint32_t stride, + D3D12_BUFFER_UAV_FLAGS flag, + uint32_t counterOffset, + ID3D12Resource* counterResource) { if (!device || !buffer) throw std::invalid_argument("Direct3D device and resource must be valid"); @@ -323,26 +302,23 @@ void DirectX::CreateBufferUnorderedAccessView( const auto desc = buffer->GetDesc(); #else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *buffer->GetDesc(&tmpDesc); + const auto& desc = *buffer->GetDesc(&tmpDesc); #endif - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER - || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) == 0) + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) == 0) { DebugTrace("ERROR: CreateBufferUnorderedAccessView called on an unsupported resource.\n"); throw std::runtime_error("invalid buffer resource"); } D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; - uavDesc.Format = DXGI_FORMAT_UNKNOWN; - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uavDesc.Buffer.FirstElement = 0; - uavDesc.Buffer.NumElements = (stride > 0) - ? static_cast(desc.Width / stride) - : static_cast(desc.Width); - uavDesc.Buffer.StructureByteStride = stride; - uavDesc.Buffer.CounterOffsetInBytes = counterOffset; - uavDesc.Buffer.Flags = flag; + uavDesc.Format = DXGI_FORMAT_UNKNOWN; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uavDesc.Buffer.FirstElement = 0; + uavDesc.Buffer.NumElements = (stride > 0) ? static_cast(desc.Width / stride) : static_cast(desc.Width); + uavDesc.Buffer.StructureByteStride = stride; + uavDesc.Buffer.CounterOffsetInBytes = counterOffset; + uavDesc.Buffer.Flags = flag; device->CreateUnorderedAccessView(buffer, counterResource, &uavDesc, uavDescriptor); } diff --git a/Src/DualPostProcess.cpp b/Src/DualPostProcess.cpp index 397999fe..0d0814c4 100644 --- a/Src/DualPostProcess.cpp +++ b/Src/DualPostProcess.cpp @@ -28,7 +28,7 @@ namespace constexpr int c_MaxSamples = 16; constexpr int Dirty_ConstantBuffer = 0x01; - constexpr int Dirty_Parameters = 0x02; + constexpr int Dirty_Parameters = 0x02; // Constant buffer layout. Must match the shader! XM_ALIGNED_STRUCT(16) PostProcessConstants @@ -38,7 +38,7 @@ namespace }; static_assert((sizeof(PostProcessConstants) % 16) == 0, "CB size not padded correctly"); -} +} // namespace #pragma region Shaders // Include the precompiled shader code. @@ -65,17 +65,15 @@ namespace #include "PostProcess_PSMerge.inc" #include "PostProcess_PSBloomCombine.inc" #endif -} +} // namespace namespace { - const D3D12_SHADER_BYTECODE vertexShader = - { PostProcess_VSQuadDual, sizeof(PostProcess_VSQuadDual) }; + const D3D12_SHADER_BYTECODE vertexShader = { PostProcess_VSQuadDual, sizeof(PostProcess_VSQuadDual) }; - const D3D12_SHADER_BYTECODE pixelShaders[] = - { - { PostProcess_PSMerge, sizeof(PostProcess_PSMerge) }, - { PostProcess_PSBloomCombine, sizeof(PostProcess_PSBloomCombine) }, + const D3D12_SHADER_BYTECODE pixelShaders[] = { + { PostProcess_PSMerge, sizeof(PostProcess_PSMerge) }, + { PostProcess_PSBloomCombine, sizeof(PostProcess_PSBloomCombine) }, }; static_assert(std::size(pixelShaders) == DualPostProcess::Effect_Max, "array/max mismatch"); @@ -88,15 +86,17 @@ namespace : mDevice(device) {} - DeviceResources(const DeviceResources&) = delete; + DeviceResources(const DeviceResources&) = delete; DeviceResources& operator=(const DeviceResources&) = delete; - DeviceResources(DeviceResources&&) = delete; + DeviceResources(DeviceResources&&) = delete; DeviceResources& operator=(DeviceResources&&) = delete; ID3D12RootSignature* GetRootSignature(const D3D12_ROOT_SIGNATURE_DESC& desc) { - return DemandCreate(mRootSignature, mMutex, [&](ID3D12RootSignature** pResult) noexcept -> HRESULT + return DemandCreate(mRootSignature, + mMutex, + [&](ID3D12RootSignature** pResult) noexcept -> HRESULT { HRESULT hr = CreateRootSignature(mDevice.Get(), &desc, pResult); @@ -114,7 +114,7 @@ namespace ComPtr mRootSignature; std::mutex mMutex; }; -} +} // namespace #pragma endregion class DualPostProcess::Impl : public AlignedNew @@ -122,10 +122,10 @@ class DualPostProcess::Impl : public AlignedNew public: Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect ifx); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; void Process(_In_ ID3D12GraphicsCommandList* commandList); @@ -141,19 +141,19 @@ class DualPostProcess::Impl : public AlignedNew }; // Fields. - DualPostProcess::Effect fx; - PostProcessConstants constants; - D3D12_GPU_DESCRIPTOR_HANDLE texture; - D3D12_GPU_DESCRIPTOR_HANDLE texture2; - float mergeWeight1; - float mergeWeight2; - float bloomIntensity; - float bloomBaseIntensity; - float bloomSaturation; - float bloomBaseSaturation; + DualPostProcess::Effect fx; + PostProcessConstants constants; + D3D12_GPU_DESCRIPTOR_HANDLE texture; + D3D12_GPU_DESCRIPTOR_HANDLE texture2; + float mergeWeight1; + float mergeWeight2; + float bloomIntensity; + float bloomBaseIntensity; + float bloomSaturation; + float bloomBaseSaturation; private: - int mDirtyFlags; + int mDirtyFlags; // D3D constant buffer holds a copy of the same data as the public 'constants' field. GraphicsResource mConstantBuffer; @@ -170,24 +170,22 @@ class DualPostProcess::Impl : public AlignedNew static SharedResourcePool deviceResourcesPool; }; - // Global pool of per-device DualPostProcess resources. SharedResourcePool DualPostProcess::Impl::deviceResourcesPool; - // Constructor. DualPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect ifx) : fx(ifx), - constants{}, - texture{}, - texture2{}, - mergeWeight1(0.5f), - mergeWeight2(0.5f), - bloomIntensity(1.25f), - bloomBaseIntensity(1.f), - bloomSaturation(1.f), - bloomBaseSaturation(1.f), - mDirtyFlags(INT_MAX) + constants{}, + texture{}, + texture2{}, + mergeWeight1(0.5f), + mergeWeight2(0.5f), + bloomIntensity(1.25f), + bloomBaseIntensity(1.f), + bloomSaturation(1.f), + bloomBaseSaturation(1.f), + mDirtyFlags(INT_MAX) { if (ifx >= Effect_Max) throw std::invalid_argument("Effect not defined"); @@ -199,20 +197,16 @@ DualPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; // Same as CommonStates::StaticLinearClamp - const CD3DX12_STATIC_SAMPLER_DESC sampler( - 0, // register + const CD3DX12_STATIC_SAMPLER_DESC sampler(0, // register D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -254,17 +248,11 @@ DualPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE); - psd.CreatePipelineState( - device, - mRootSignature, - vertexShader, - pixelShaders[ifx], - mPipelineState.GetAddressOf()); + psd.CreatePipelineState(device, mRootSignature, vertexShader, pixelShaders[ifx], mPipelineState.GetAddressOf()); SetDebugObjectName(mPipelineState.Get(), L"DualPostProcess"); } - // Sets our state onto the D3D device. void DualPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList) { @@ -299,8 +287,7 @@ void DualPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList) constants.sampleWeights[2] = XMVectorReplicate(bloomIntensity); break; - default: - break; + default: break; } } @@ -320,17 +307,14 @@ void DualPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList) commandList->DrawInstanced(3, 1, 0, 0); } - // Public constructor. DualPostProcess::DualPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx) : pImpl(std::make_unique(device, rtState, fx)) {} - -DualPostProcess::DualPostProcess(DualPostProcess&&) noexcept = default; -DualPostProcess& DualPostProcess::operator= (DualPostProcess&&) noexcept = default; -DualPostProcess::~DualPostProcess() = default; - +DualPostProcess::DualPostProcess(DualPostProcess&&) noexcept = default; +DualPostProcess& DualPostProcess::operator=(DualPostProcess&&) noexcept = default; +DualPostProcess::~DualPostProcess() = default; // IPostProcess methods. void DualPostProcess::Process(_In_ ID3D12GraphicsCommandList* commandList) @@ -338,20 +322,17 @@ void DualPostProcess::Process(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Process(commandList); } - // Properties void DualPostProcess::SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { pImpl->texture = srvDescriptor; } - void DualPostProcess::SetSourceTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { pImpl->texture2 = srvDescriptor; } - void DualPostProcess::SetMergeParameters(float weight1, float weight2) { pImpl->mergeWeight1 = weight1; @@ -359,12 +340,11 @@ void DualPostProcess::SetMergeParameters(float weight1, float weight2) pImpl->SetDirtyFlag(); } - void DualPostProcess::SetBloomCombineParameters(float bloom, float base, float bloomSaturation, float baseSaturation) { - pImpl->bloomIntensity = bloom; - pImpl->bloomBaseIntensity = base; - pImpl->bloomSaturation = bloomSaturation; + pImpl->bloomIntensity = bloom; + pImpl->bloomBaseIntensity = base; + pImpl->bloomSaturation = bloomSaturation; pImpl->bloomBaseSaturation = baseSaturation; pImpl->SetDirtyFlag(); } diff --git a/Src/DualTextureEffect.cpp b/Src/DualTextureEffect.cpp index cbd67e57..c359266a 100644 --- a/Src/DualTextureEffect.cpp +++ b/Src/DualTextureEffect.cpp @@ -26,18 +26,17 @@ namespace static_assert((sizeof(DualTextureEffectConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct DualTextureEffectTraits { using ConstantBufferType = DualTextureEffectConstants; - static constexpr int VertexShaderCount = 4; - static constexpr int PixelShaderCount = 2; + static constexpr int VertexShaderCount = 4; + static constexpr int PixelShaderCount = 2; static constexpr int ShaderPermutationCount = 4; - static constexpr int RootSignatureCount = 1; + static constexpr int RootSignatureCount = 1; }; -} +} // namespace // Internal DualTextureEffect implementation class. class DualTextureEffect::Impl : public EffectBase @@ -45,10 +44,10 @@ class DualTextureEffect::Impl : public EffectBase public: Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; enum RootParameterIndex @@ -73,7 +72,6 @@ class DualTextureEffect::Impl : public EffectBase void Apply(_In_ ID3D12GraphicsCommandList* commandList); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -111,81 +109,75 @@ namespace #include "DualTextureEffect_PSDualTexture.inc" #include "DualTextureEffect_PSDualTextureNoFog.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { DualTextureEffect_VSDualTexture, sizeof(DualTextureEffect_VSDualTexture) }, - { DualTextureEffect_VSDualTextureNoFog, sizeof(DualTextureEffect_VSDualTextureNoFog) }, - { DualTextureEffect_VSDualTextureVc, sizeof(DualTextureEffect_VSDualTextureVc) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { DualTextureEffect_VSDualTexture, sizeof(DualTextureEffect_VSDualTexture) }, + { DualTextureEffect_VSDualTextureNoFog, sizeof(DualTextureEffect_VSDualTextureNoFog) }, + { DualTextureEffect_VSDualTextureVc, sizeof(DualTextureEffect_VSDualTextureVc) }, { DualTextureEffect_VSDualTextureVcNoFog, sizeof(DualTextureEffect_VSDualTextureVcNoFog) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // basic - 1, // no fog - 2, // vertex color - 3, // vertex color, no fog +const int EffectBase::VertexShaderIndices[] = { + 0, // basic + 1, // no fog + 2, // vertex color + 3, // vertex color, no fog }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { DualTextureEffect_PSDualTexture, sizeof(DualTextureEffect_PSDualTexture) }, - { DualTextureEffect_PSDualTextureNoFog, sizeof(DualTextureEffect_PSDualTextureNoFog) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { DualTextureEffect_PSDualTexture, sizeof(DualTextureEffect_PSDualTexture) }, + { DualTextureEffect_PSDualTextureNoFog, sizeof(DualTextureEffect_PSDualTextureNoFog) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // basic - 1, // no fog - 0, // vertex color - 1, // vertex color, no fog +const int EffectBase::PixelShaderIndices[] = { + 0, // basic + 1, // no fog + 0, // vertex color + 1, // vertex color, no fog }; #pragma endregion // Global pool of per-device DualTextureEffect resources. template<> -SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - +SharedResourcePool::DeviceResources> + EffectBase::deviceResourcesPool = {}; // Constructor. -DualTextureEffect::Impl::Impl( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) +DualTextureEffect::Impl::Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription) : EffectBase(device), - texture1{}, - texture1Sampler{}, - texture2{}, - texture2Sampler{} + texture1{}, + texture1Sampler{}, + texture2{}, + texture2Sampler{} { - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == DualTextureEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == DualTextureEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) + == DualTextureEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) + == DualTextureEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) + == DualTextureEffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) + == DualTextureEffectTraits::ShaderPermutationCount, + "array/max mismatch"); // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; CD3DX12_ROOT_PARAMETER rootParameters[RootParameterIndex::RootParameterCount] = {}; @@ -243,8 +235,7 @@ DualTextureEffect::Impl::Impl( assert(pi >= 0 && pi < DualTextureEffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < DualTextureEffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -253,7 +244,6 @@ DualTextureEffect::Impl::Impl( SetDebugObjectName(mPipelineState.Get(), L"DualTextureEffect"); } - int DualTextureEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const noexcept { int permutation = 0; @@ -273,7 +263,6 @@ int DualTextureEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) c return permutation; } - // Sets our state onto the D3D device. void DualTextureEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { @@ -297,11 +286,14 @@ void DualTextureEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) } if (!texture1Sampler.ptr || !texture2Sampler.ptr) { - DebugTrace("ERROR: Missing sampler(s) for DualTextureEffect (samplers1 %llu, samplers2 %llu)\n", texture2Sampler.ptr, texture2Sampler.ptr); + DebugTrace("ERROR: Missing sampler(s) for DualTextureEffect (samplers1 %llu, samplers2 %llu)\n", + texture2Sampler.ptr, + texture2Sampler.ptr); throw std::runtime_error("DualTextureEffect"); } - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heaps. commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::Texture1SRV, texture1); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::Texture1Sampler, texture1Sampler); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::Texture2SRV, texture2); @@ -314,20 +306,16 @@ void DualTextureEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - // Public constructor. -DualTextureEffect::DualTextureEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) +DualTextureEffect::DualTextureEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription) : pImpl(std::make_unique(device, effectFlags, pipelineDescription)) {} - -DualTextureEffect::DualTextureEffect(DualTextureEffect&&) noexcept = default; -DualTextureEffect& DualTextureEffect::operator= (DualTextureEffect&&) noexcept = default; -DualTextureEffect::~DualTextureEffect() = default; - +DualTextureEffect::DualTextureEffect(DualTextureEffect&&) noexcept = default; +DualTextureEffect& DualTextureEffect::operator=(DualTextureEffect&&) noexcept = default; +DualTextureEffect::~DualTextureEffect() = default; // IEffect methods void DualTextureEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -335,7 +323,6 @@ void DualTextureEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings void XM_CALLCONV DualTextureEffect::SetWorld(FXMMATRIX value) { @@ -344,7 +331,6 @@ void XM_CALLCONV DualTextureEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::FogVector; } - void XM_CALLCONV DualTextureEffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -352,7 +338,6 @@ void XM_CALLCONV DualTextureEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; } - void XM_CALLCONV DualTextureEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -360,17 +345,16 @@ void XM_CALLCONV DualTextureEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV DualTextureEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; - pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; + pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition + | EffectDirtyFlags::FogVector; } - // Material settings void XM_CALLCONV DualTextureEffect::SetDiffuseColor(FXMVECTOR value) { @@ -379,7 +363,6 @@ void XM_CALLCONV DualTextureEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void DualTextureEffect::SetAlpha(float value) { pImpl->color.alpha = value; @@ -387,16 +370,14 @@ void DualTextureEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV DualTextureEffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->color.diffuseColor = value; - pImpl->color.alpha = XMVectorGetW(value); + pImpl->color.alpha = XMVectorGetW(value); pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - // Fog settings. void DualTextureEffect::SetFogStart(float value) { @@ -405,7 +386,6 @@ void DualTextureEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void DualTextureEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -413,7 +393,6 @@ void DualTextureEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV DualTextureEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -421,17 +400,15 @@ void XM_CALLCONV DualTextureEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void DualTextureEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { - pImpl->texture1 = srvDescriptor; + pImpl->texture1 = srvDescriptor; pImpl->texture1Sampler = samplerDescriptor; } - void DualTextureEffect::SetTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { - pImpl->texture2 = srvDescriptor; + pImpl->texture2 = srvDescriptor; pImpl->texture2Sampler = samplerDescriptor; } diff --git a/Src/EffectCommon.cpp b/Src/EffectCommon.cpp index 584b0816..56ae657a 100644 --- a/Src/EffectCommon.cpp +++ b/Src/EffectCommon.cpp @@ -15,7 +15,6 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - // IEffectMatrices default method void XM_CALLCONV IEffectMatrices::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { @@ -24,21 +23,18 @@ void XM_CALLCONV IEffectMatrices::SetMatrices(FXMMATRIX world, CXMMATRIX view, C SetProjection(projection); } - // Constructor initializes default matrix values. EffectMatrices::EffectMatrices() noexcept { const XMMATRIX id = XMMatrixIdentity(); - world = id; - view = id; - projection = id; - worldView = id; + world = id; + view = id; + projection = id; + worldView = id; } - // Lazily recomputes the combined world+view+projection matrix. -_Use_decl_annotations_ -void EffectMatrices::SetConstants(int& dirtyFlags, XMMATRIX& worldViewProjConstant) +_Use_decl_annotations_ void EffectMatrices::SetConstants(int& dirtyFlags, XMMATRIX& worldViewProjConstant) { if (dirtyFlags & EffectDirtyFlags::WorldViewProj) { @@ -51,16 +47,13 @@ void EffectMatrices::SetConstants(int& dirtyFlags, XMMATRIX& worldViewProjConsta } } - // Lazily recomputes the combined world+view+projection matrix, inverse, eyePosition, etc. // This version is used for effects that do not use the EffectLights helper. -_Use_decl_annotations_ -void EffectMatrices::SetConstants( - int& dirtyFlags, - XMMATRIX& worldConstant, - XMVECTOR worldInverseTransposeConstant[3], - XMMATRIX& worldViewProjConstant, - XMVECTOR& eyePositionConstant) +_Use_decl_annotations_ void EffectMatrices::SetConstants(int& dirtyFlags, + XMMATRIX& worldConstant, + XMVECTOR worldInverseTransposeConstant[3], + XMMATRIX& worldViewProjConstant, + XMVECTOR& eyePositionConstant) { // Combined world+view+projection matrix. if (dirtyFlags & EffectDirtyFlags::WorldViewProj) @@ -92,25 +85,22 @@ void EffectMatrices::SetConstants( if (dirtyFlags & EffectDirtyFlags::EyePosition) { const XMMATRIX viewInverse = XMMatrixInverse(nullptr, view); - eyePositionConstant = viewInverse.r[3]; + eyePositionConstant = viewInverse.r[3]; dirtyFlags &= ~EffectDirtyFlags::EyePosition; dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } } - // Constructor initializes default fog settings. -EffectFog::EffectFog() noexcept : - enabled(false), - start(0), - end(1.f) +EffectFog::EffectFog() noexcept + : enabled(false), + start(0), + end(1.f) {} - // Lazily recomputes the derived vector used by shader fog calculations. -_Use_decl_annotations_ -void XM_CALLCONV EffectFog::SetConstants(int& dirtyFlags, FXMMATRIX worldView, XMVECTOR& fogVectorConstant) +_Use_decl_annotations_ void XM_CALLCONV EffectFog::SetConstants(int& dirtyFlags, FXMMATRIX worldView, XMVECTOR& fogVectorConstant) { if (enabled) { @@ -131,9 +121,8 @@ void XM_CALLCONV EffectFog::SetConstants(int& dirtyFlags, FXMMATRIX worldView, X // with a single dot product, using only the Z row of the world+view matrix. // _13, _23, _33, _43 - const XMVECTOR worldViewZ = XMVectorMergeXY( - XMVectorMergeZW(worldView.r[0], worldView.r[2]), - XMVectorMergeZW(worldView.r[1], worldView.r[3])); + const XMVECTOR worldViewZ + = XMVectorMergeXY(XMVectorMergeZW(worldView.r[0], worldView.r[2]), XMVectorMergeZW(worldView.r[1], worldView.r[3])); // 0, 0, 0, fogStart const XMVECTOR wOffset = XMVectorSwizzle<1, 2, 3, 0>(XMLoadFloat(&start)); @@ -159,14 +148,12 @@ void XM_CALLCONV EffectFog::SetConstants(int& dirtyFlags, FXMMATRIX worldView, X } } - // Constructor initializes default material color settings. -EffectColor::EffectColor() noexcept : - diffuseColor(g_XMOne), - alpha(1.f) +EffectColor::EffectColor() noexcept + : diffuseColor(g_XMOne), + alpha(1.f) {} - // Lazily recomputes the material color parameter for shaders that do not support realtime lighting. void EffectColor::SetConstants(_Inout_ int& dirtyFlags, _Inout_ XMVECTOR& diffuseColorConstant) { @@ -182,37 +169,33 @@ void EffectColor::SetConstants(_Inout_ int& dirtyFlags, _Inout_ XMVECTOR& diffus } } - // Constructor initializes default light settings. -EffectLights::EffectLights() noexcept : - emissiveColor{}, - ambientLightColor{}, - lightEnabled{}, - lightDiffuseColor{}, - lightSpecularColor{} +EffectLights::EffectLights() noexcept + : emissiveColor{}, + ambientLightColor{}, + lightEnabled{}, + lightDiffuseColor{}, + lightSpecularColor{} { for (int i = 0; i < MaxDirectionalLights; i++) { - lightEnabled[i] = (i == 0); + lightEnabled[i] = (i == 0); lightDiffuseColor[i] = g_XMOne; } } - #ifdef _PREFAST_ #pragma prefast(push) -#pragma prefast(disable:22103, "PREFAST doesn't understand buffer is bounded by a static const value even with SAL" ) +#pragma prefast(disable : 22103, "PREFAST doesn't understand buffer is bounded by a static const value even with SAL") #endif // Initializes constant buffer fields to match the current lighting state. -_Use_decl_annotations_ -void EffectLights::InitializeConstants( - XMVECTOR& specularColorAndPowerConstant, - XMVECTOR* lightDirectionConstant, - XMVECTOR* lightDiffuseConstant, - XMVECTOR* lightSpecularConstant) const +_Use_decl_annotations_ void EffectLights::InitializeConstants(XMVECTOR& specularColorAndPowerConstant, + XMVECTOR* lightDirectionConstant, + XMVECTOR* lightDiffuseConstant, + XMVECTOR* lightSpecularConstant) const { - static const XMVECTORF32 defaultSpecular = { { { 1, 1, 1, 16 } } }; + static const XMVECTORF32 defaultSpecular = { { { 1, 1, 1, 16 } } }; static const XMVECTORF32 defaultLightDirection = { { { 0, -1, 0, 0 } } }; specularColorAndPowerConstant = defaultSpecular; @@ -221,7 +204,7 @@ void EffectLights::InitializeConstants( { lightDirectionConstant[i] = defaultLightDirection; - lightDiffuseConstant[i] = lightEnabled[i] ? lightDiffuseColor[i] : g_XMZero; + lightDiffuseConstant[i] = lightEnabled[i] ? lightDiffuseColor[i] : g_XMZero; lightSpecularConstant[i] = lightEnabled[i] ? lightSpecularColor[i] : g_XMZero; } } @@ -230,18 +213,15 @@ void EffectLights::InitializeConstants( #pragma prefast(pop) #endif - // Lazily recomputes derived parameter values used by shader lighting calculations. -_Use_decl_annotations_ -void EffectLights::SetConstants( - int& dirtyFlags, - EffectMatrices const& matrices, - XMMATRIX& worldConstant, - XMVECTOR worldInverseTransposeConstant[3], - XMVECTOR& eyePositionConstant, - XMVECTOR& diffuseColorConstant, - XMVECTOR& emissiveColorConstant, - bool lightingEnabled) +_Use_decl_annotations_ void EffectLights::SetConstants(int& dirtyFlags, + EffectMatrices const& matrices, + XMMATRIX& worldConstant, + XMVECTOR worldInverseTransposeConstant[3], + XMVECTOR& eyePositionConstant, + XMVECTOR& diffuseColorConstant, + XMVECTOR& emissiveColorConstant, + bool lightingEnabled) { if (lightingEnabled) { @@ -295,7 +275,7 @@ void EffectLights::SetConstants( if (dirtyFlags & EffectDirtyFlags::MaterialColor) { - XMVECTOR diffuse = diffuseColor; + XMVECTOR diffuse = diffuseColor; const XMVECTOR alphaVector = XMVectorReplicate(alpha); if (lightingEnabled) @@ -318,19 +298,14 @@ void EffectLights::SetConstants( } } - #ifdef _PREFAST_ #pragma prefast(push) -#pragma prefast(disable:26015, "PREFAST doesn't understand that ValidateLightIndex bounds whichLight" ) +#pragma prefast(disable : 26015, "PREFAST doesn't understand that ValidateLightIndex bounds whichLight") #endif // Helper for turning one of the directional lights on or off. -_Use_decl_annotations_ -int EffectLights::SetLightEnabled( - int whichLight, - bool value, - XMVECTOR* lightDiffuseConstant, - XMVECTOR* lightSpecularConstant) +_Use_decl_annotations_ int +EffectLights::SetLightEnabled(int whichLight, bool value, XMVECTOR* lightDiffuseConstant, XMVECTOR* lightSpecularConstant) { ValidateLightIndex(whichLight); @@ -342,23 +317,21 @@ int EffectLights::SetLightEnabled( if (value) { // If this light is now on, store its color in the constant buffer. - lightDiffuseConstant[whichLight] = lightDiffuseColor[whichLight]; + lightDiffuseConstant[whichLight] = lightDiffuseColor[whichLight]; lightSpecularConstant[whichLight] = lightSpecularColor[whichLight]; } else { // If the light is off, reset constant buffer colors to zero. - lightDiffuseConstant[whichLight] = g_XMZero; + lightDiffuseConstant[whichLight] = g_XMZero; lightSpecularConstant[whichLight] = g_XMZero; } return EffectDirtyFlags::ConstantBuffer; } - // Helper for setting diffuse color of one of the directional lights. -_Use_decl_annotations_ -int XM_CALLCONV EffectLights::SetLightDiffuseColor(int whichLight, FXMVECTOR value, XMVECTOR* lightDiffuseConstant) +_Use_decl_annotations_ int XM_CALLCONV EffectLights::SetLightDiffuseColor(int whichLight, FXMVECTOR value, XMVECTOR* lightDiffuseConstant) { ValidateLightIndex(whichLight); @@ -376,10 +349,8 @@ int XM_CALLCONV EffectLights::SetLightDiffuseColor(int whichLight, FXMVECTOR val return 0; } - // Helper for setting specular color of one of the directional lights. -_Use_decl_annotations_ -int XM_CALLCONV EffectLights::SetLightSpecularColor(int whichLight, FXMVECTOR value, XMVECTOR* lightSpecularConstant) +_Use_decl_annotations_ int XM_CALLCONV EffectLights::SetLightSpecularColor(int whichLight, FXMVECTOR value, XMVECTOR* lightSpecularConstant) { ValidateLightIndex(whichLight); @@ -401,7 +372,6 @@ int XM_CALLCONV EffectLights::SetLightSpecularColor(int whichLight, FXMVECTOR va #pragma prefast(pop) #endif - // Parameter validation helper. void EffectLights::ValidateLightIndex(int whichLight) { @@ -411,26 +381,22 @@ void EffectLights::ValidateLightIndex(int whichLight) } } - // Activates the default lighting rig (key, fill, and back lights). void EffectLights::EnableDefaultLighting(_In_ IEffectLights* effect) { - static const XMVECTORF32 defaultDirections[MaxDirectionalLights] = - { + static const XMVECTORF32 defaultDirections[MaxDirectionalLights] = { { { { -0.5265408f, -0.5735765f, -0.6275069f, 0 } } }, - { { { 0.7198464f, 0.3420201f, 0.6040227f, 0 } } }, - { { { 0.4545195f, -0.7660444f, 0.4545195f, 0 } } }, + { { { 0.7198464f, 0.3420201f, 0.6040227f, 0 } } }, + { { { 0.4545195f, -0.7660444f, 0.4545195f, 0 } } }, }; - static const XMVECTORF32 defaultDiffuse[MaxDirectionalLights] = - { + static const XMVECTORF32 defaultDiffuse[MaxDirectionalLights] = { { { { 1.0000000f, 0.9607844f, 0.8078432f, 0 } } }, { { { 0.9647059f, 0.7607844f, 0.4078432f, 0 } } }, { { { 0.3231373f, 0.3607844f, 0.3937255f, 0 } } }, }; - static const XMVECTORF32 defaultSpecular[MaxDirectionalLights] = - { + static const XMVECTORF32 defaultSpecular[MaxDirectionalLights] = { { { { 1.0000000f, 0.9607844f, 0.8078432f, 0 } } }, { { { 0.0000000f, 0.0000000f, 0.0000000f, 0 } } }, { { { 0.3231373f, 0.3607844f, 0.3937255f, 0 } } }, @@ -449,13 +415,13 @@ void EffectLights::EnableDefaultLighting(_In_ IEffectLights* effect) } } - // Gets or lazily creates the specified root signature. -ID3D12RootSignature* EffectDeviceResources::DemandCreateRootSig( - _Inout_ ComPtr& rootSig, - D3D12_ROOT_SIGNATURE_DESC const& desc) +ID3D12RootSignature* EffectDeviceResources::DemandCreateRootSig(_Inout_ ComPtr& rootSig, + D3D12_ROOT_SIGNATURE_DESC const& desc) { - return DemandCreate(rootSig, mMutex, [&](ID3D12RootSignature** pResult) noexcept -> HRESULT + return DemandCreate(rootSig, + mMutex, + [&](ID3D12RootSignature** pResult) noexcept -> HRESULT { HRESULT hr = CreateRootSignature(mDevice.Get(), &desc, pResult); diff --git a/Src/EffectCommon.h b/Src/EffectCommon.h index 54381752..5bddda4a 100644 --- a/Src/EffectCommon.h +++ b/Src/EffectCommon.h @@ -25,7 +25,6 @@ // out common functionality into a set of helpers which can be assembled in different // combinations to build up whatever subset is needed by each effect. - namespace DirectX { inline namespace DX12 @@ -36,21 +35,21 @@ namespace DirectX constexpr int PerPixelLightingBit = 0x04; } - static_assert(((EffectFlags::PerPixelLighting)& EffectFlags::PerPixelLightingBit) != 0, "PerPixelLighting enum flags mismatch"); - } + static_assert(((EffectFlags::PerPixelLighting)&EffectFlags::PerPixelLightingBit) != 0, "PerPixelLighting enum flags mismatch"); + } // namespace DX12 // Bitfield tracks which derived parameter values need to be recomputed. namespace EffectDirtyFlags { - constexpr int ConstantBuffer = 0x01; - constexpr int WorldViewProj = 0x02; + constexpr int ConstantBuffer = 0x01; + constexpr int WorldViewProj = 0x02; constexpr int WorldInverseTranspose = 0x04; - constexpr int EyePosition = 0x08; - constexpr int MaterialColor = 0x10; - constexpr int FogVector = 0x20; - constexpr int FogEnable = 0x40; - constexpr int AlphaTest = 0x80; - } + constexpr int EyePosition = 0x08; + constexpr int MaterialColor = 0x10; + constexpr int FogVector = 0x20; + constexpr int FogEnable = 0x40; + constexpr int AlphaTest = 0x80; + } // namespace EffectDirtyFlags // Helper stores matrix parameter values, and computes derived matrices. struct EffectMatrices @@ -65,43 +64,36 @@ namespace DirectX void SetConstants(_Inout_ int& dirtyFlags, _Inout_ XMMATRIX& worldViewProjConstant); // Helper for effects that don't use EffectLights, but have eye position. - void SetConstants( - _Inout_ int& dirtyFlags, - _Inout_ XMMATRIX& worldConstant, + void SetConstants(_Inout_ int& dirtyFlags, + _Inout_ XMMATRIX& worldConstant, _Inout_updates_(3) XMVECTOR worldInverseTransposeConstant[3], - _Inout_ XMMATRIX& worldViewProjConstant, - _Inout_ XMVECTOR& eyePositionConstant); + _Inout_ XMMATRIX& worldViewProjConstant, + _Inout_ XMVECTOR& eyePositionConstant); }; - // Helper stores the current fog settings, and computes derived shader parameters. struct EffectFog { EffectFog() noexcept; - bool enabled; + bool enabled; float start; float end; - void XM_CALLCONV SetConstants( - _Inout_ int& dirtyFlags, - _In_ FXMMATRIX worldView, - _Inout_ XMVECTOR& fogVectorConstant); + void XM_CALLCONV SetConstants(_Inout_ int& dirtyFlags, _In_ FXMMATRIX worldView, _Inout_ XMVECTOR& fogVectorConstant); }; - // Helper stores material color settings, and computes derived parameters for shaders that do not support realtime lighting. struct EffectColor { EffectColor() noexcept; XMVECTOR diffuseColor; - float alpha; + float alpha; void SetConstants(_Inout_ int& dirtyFlags, _Inout_ XMVECTOR& diffuseColorConstant); }; - // Helper stores the current light settings, and computes derived shader parameters. struct EffectLights : public EffectColor { @@ -109,44 +101,37 @@ namespace DirectX static constexpr int MaxDirectionalLights = IEffectLights::MaxDirectionalLights; - // Fields. XMVECTOR emissiveColor; XMVECTOR ambientLightColor; - bool lightEnabled[MaxDirectionalLights]; + bool lightEnabled[MaxDirectionalLights]; XMVECTOR lightDiffuseColor[MaxDirectionalLights]; XMVECTOR lightSpecularColor[MaxDirectionalLights]; - // Methods. - void InitializeConstants( - _Out_ XMVECTOR& specularColorAndPowerConstant, + void InitializeConstants(_Out_ XMVECTOR& specularColorAndPowerConstant, _Out_writes_all_(MaxDirectionalLights) XMVECTOR* lightDirectionConstant, _Out_writes_all_(MaxDirectionalLights) XMVECTOR* lightDiffuseConstant, _Out_writes_all_(MaxDirectionalLights) XMVECTOR* lightSpecularConstant) const; - void SetConstants( - _Inout_ int& dirtyFlags, - _In_ EffectMatrices const& matrices, - _Inout_ XMMATRIX& worldConstant, + void SetConstants(_Inout_ int& dirtyFlags, + _In_ EffectMatrices const& matrices, + _Inout_ XMMATRIX& worldConstant, _Inout_updates_(3) XMVECTOR worldInverseTransposeConstant[3], - _Inout_ XMVECTOR& eyePositionConstant, - _Inout_ XMVECTOR& diffuseColorConstant, - _Inout_ XMVECTOR& emissiveColorConstant, - bool lightingEnabled); - - int SetLightEnabled( - int whichLight, - bool value, - _Inout_updates_(MaxDirectionalLights) XMVECTOR* lightDiffuseConstant, - _Inout_updates_(MaxDirectionalLights) XMVECTOR* lightSpecularConstant); - int XM_CALLCONV SetLightDiffuseColor( - int whichLight, - FXMVECTOR value, + _Inout_ XMVECTOR& eyePositionConstant, + _Inout_ XMVECTOR& diffuseColorConstant, + _Inout_ XMVECTOR& emissiveColorConstant, + bool lightingEnabled); + + int SetLightEnabled(int whichLight, + bool value, + _Inout_updates_(MaxDirectionalLights) XMVECTOR* lightDiffuseConstant, + _Inout_updates_(MaxDirectionalLights) XMVECTOR* lightSpecularConstant); + int XM_CALLCONV SetLightDiffuseColor(int whichLight, + FXMVECTOR value, _Inout_updates_(MaxDirectionalLights) XMVECTOR* lightDiffuseConstant); - int XM_CALLCONV SetLightSpecularColor( - int whichLight, - FXMVECTOR value, + int XM_CALLCONV SetLightSpecularColor(int whichLight, + FXMVECTOR value, _Inout_updates_(MaxDirectionalLights) XMVECTOR* lightSpecularConstant); static void ValidateLightIndex(int whichLight); @@ -161,7 +146,8 @@ namespace DirectX : mDevice(device) {} - ID3D12RootSignature* DemandCreateRootSig(_Inout_ Microsoft::WRL::ComPtr& rootSig, D3D12_ROOT_SIGNATURE_DESC const& desc); + ID3D12RootSignature* DemandCreateRootSig(_Inout_ Microsoft::WRL::ComPtr& rootSig, + D3D12_ROOT_SIGNATURE_DESC const& desc); protected: Microsoft::WRL::ComPtr mDevice; @@ -179,8 +165,8 @@ namespace DirectX // Constructor. EffectBase(_In_ ID3D12Device* device) : constants{}, - dirtyFlags(INT_MAX), - mRootSignature(nullptr) + dirtyFlags(INT_MAX), + mRootSignature(nullptr) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -203,25 +189,19 @@ namespace DirectX } } - D3D12_GPU_VIRTUAL_ADDRESS GetConstantBufferGpuAddress() noexcept - { - return mConstantBuffer.GpuAddress(); - } + D3D12_GPU_VIRTUAL_ADDRESS GetConstantBufferGpuAddress() noexcept { return mConstantBuffer.GpuAddress(); } ID3D12RootSignature* GetRootSignature(int slot, CD3DX12_ROOT_SIGNATURE_DESC const& rootSig) { return mDeviceResources->GetRootSignature(slot, rootSig); } - ID3D12Device* GetDevice() const noexcept - { - return mDeviceResources->GetDevice(); - } + ID3D12Device* GetDevice() const noexcept { return mDeviceResources->GetDevice(); } // Fields. EffectMatrices matrices; - EffectFog fog; - int dirtyFlags; + EffectFog fog; + int dirtyFlags; protected: // Static arrays hold all the precompiled shader permutations. @@ -249,7 +229,7 @@ namespace DirectX public: DeviceResources(_In_ ID3D12Device* device) noexcept : EffectDeviceResources(device), - mRootSignature{} + mRootSignature{} {} // Gets or lazily creates the specified root signature @@ -272,4 +252,4 @@ namespace DirectX static SharedResourcePool deviceResourcesPool; }; -} +} // namespace DirectX diff --git a/Src/EffectFactory.cpp b/Src/EffectFactory.cpp index 058e7a28..f48f73c5 100644 --- a/Src/EffectFactory.cpp +++ b/Src/EffectFactory.cpp @@ -16,7 +16,6 @@ #include - using namespace DirectX; using Microsoft::WRL::ComPtr; @@ -51,23 +50,24 @@ namespace effect->SetEmissiveColor(color); } } -} +} // namespace // Internal EffectFactory implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing EffectFactory instances. class EffectFactory::Impl { public: - Impl(_In_ ID3D12Device* device, _In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept(false) - : mTextureDescriptors(nullptr) - , mSamplerDescriptors(nullptr) - , mSharing(true) - , mUseNormalMapEffect(true) - , mEnableLighting(true) - , mEnablePerPixelLighting(true) - , mEnableFog(false) - , mEnableInstancing(false) - , mDevice(device) + Impl(_In_ ID3D12Device* device, _In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept( + false) + : mTextureDescriptors(nullptr), + mSamplerDescriptors(nullptr), + mSharing(true), + mUseNormalMapEffect(true), + mEnableLighting(true), + mEnablePerPixelLighting(true), + mEnableFog(false), + mEnableInstancing(false), + mDevice(device) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -78,19 +78,18 @@ class EffectFactory::Impl mSamplerDescriptors = std::make_unique(samplerDescriptors); } - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = delete; + Impl(Impl&&) = delete; Impl& operator=(Impl&&) = delete; - std::shared_ptr CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset, - int samplerDescriptorOffset); + std::shared_ptr CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset, + int samplerDescriptorOffset); void ReleaseCache(); @@ -107,37 +106,44 @@ class EffectFactory::Impl ComPtr mDevice; private: - using EffectCache = std::map< std::wstring, std::shared_ptr >; + using EffectCache = std::map>; - EffectCache mEffectCache; - EffectCache mEffectCacheSkinning; - EffectCache mEffectCacheDualTexture; - EffectCache mEffectCacheNormalMap; - EffectCache mEffectCacheNormalMapSkinned; + EffectCache mEffectCache; + EffectCache mEffectCacheSkinning; + EffectCache mEffectCacheDualTexture; + EffectCache mEffectCacheNormalMap; + EffectCache mEffectCacheNormalMapSkinned; std::mutex mutex; }; - -std::shared_ptr EffectFactory::Impl::CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayoutDesc, - int textureDescriptorOffset, - int samplerDescriptorOffset) +std::shared_ptr EffectFactory::Impl::CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayoutDesc, + int textureDescriptorOffset, + int samplerDescriptorOffset) { // If textures are required, make sure we have a descriptor heap - if (!mTextureDescriptors && (info.diffuseTextureIndex != -1 || info.specularTextureIndex != -1 || info.normalTextureIndex != -1 || info.emissiveTextureIndex != -1)) + if (!mTextureDescriptors + && (info.diffuseTextureIndex != -1 || info.specularTextureIndex != -1 || info.normalTextureIndex != -1 + || info.emissiveTextureIndex != -1)) { - DebugTrace("ERROR: EffectFactory created without texture descriptor heap with texture index set (diffuse %d, specular %d, normal %d, emissive %d)!\n", - info.diffuseTextureIndex, info.specularTextureIndex, info.normalTextureIndex, info.emissiveTextureIndex); + DebugTrace( + "ERROR: EffectFactory created without texture descriptor heap with texture index set (diffuse %d, specular %d, normal %d, " + "emissive %d)!\n", + info.diffuseTextureIndex, + info.specularTextureIndex, + info.normalTextureIndex, + info.emissiveTextureIndex); throw std::runtime_error("EffectFactory"); } if (!mSamplerDescriptors && (info.samplerIndex != -1 || info.samplerIndex2 != -1)) { - DebugTrace("ERROR: EffectFactory created without sampler descriptor heap with sampler index set (samplerIndex %d, samplerIndex2 %d)!\n", - info.samplerIndex, info.samplerIndex2); + DebugTrace( + "ERROR: EffectFactory created without sampler descriptor heap with sampler index set (samplerIndex %d, samplerIndex2 %d)!\n", + info.samplerIndex, + info.samplerIndex2); throw std::runtime_error("EffectFactory"); } @@ -155,16 +161,21 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( throw std::runtime_error("EffectFactory"); } - const int diffuseTextureIndex = (info.diffuseTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.diffuseTextureIndex + textureDescriptorOffset : -1; - const int specularTextureIndex = (info.specularTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.specularTextureIndex + textureDescriptorOffset : -1; - const int emissiveTextureIndex = (info.emissiveTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.emissiveTextureIndex + textureDescriptorOffset : -1; - const int normalTextureIndex = (info.normalTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.normalTextureIndex + textureDescriptorOffset : -1; + const int diffuseTextureIndex + = (info.diffuseTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.diffuseTextureIndex + textureDescriptorOffset : -1; + const int specularTextureIndex + = (info.specularTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.specularTextureIndex + textureDescriptorOffset : -1; + const int emissiveTextureIndex + = (info.emissiveTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.emissiveTextureIndex + textureDescriptorOffset : -1; + const int normalTextureIndex + = (info.normalTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.normalTextureIndex + textureDescriptorOffset : -1; const int samplerIndex = (info.samplerIndex != -1 && mSamplerDescriptors != nullptr) ? info.samplerIndex + samplerDescriptorOffset : -1; - const int samplerIndex2 = (info.samplerIndex2 != -1 && mSamplerDescriptors != nullptr) ? info.samplerIndex2 + samplerDescriptorOffset : -1; + const int samplerIndex2 + = (info.samplerIndex2 != -1 && mSamplerDescriptors != nullptr) ? info.samplerIndex2 + samplerDescriptorOffset : -1; // Modify base pipeline state EffectPipelineStateDescription derivedPSD = (info.alphaValue < 1.0f) ? alphaPipelineState : opaquePipelineState; - derivedPSD.inputLayout = inputLayoutDesc; + derivedPSD.inputLayout = inputLayoutDesc; std::wstring cacheName; if (info.enableSkinning) @@ -192,7 +203,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCacheNormalMapSkinned.find(cacheName); if (mSharing && it != mEffectCacheNormalMapSkinned.end()) @@ -207,8 +218,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } @@ -225,7 +235,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCacheNormalMapSkinned.insert(v); } @@ -237,7 +247,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCacheSkinning.find(cacheName); if (mSharing && it != mEffectCacheSkinning.end()) @@ -252,15 +262,14 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCacheSkinning.insert(v); } @@ -280,7 +289,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCacheDualTexture.find(cacheName); if (mSharing && it != mEffectCacheDualTexture.end()) @@ -304,8 +313,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } @@ -317,8 +325,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( throw std::runtime_error("EffectFactory"); } - effect->SetTexture2( - mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), + effect->SetTexture2(mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex2))); } else if (specularTextureIndex != -1) @@ -330,15 +337,14 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( throw std::runtime_error("EffectFactory"); } - effect->SetTexture2( - mTextureDescriptors->GetGpuHandle(static_cast(specularTextureIndex)), + effect->SetTexture2(mTextureDescriptors->GetGpuHandle(static_cast(specularTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex2))); } if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCacheDualTexture.insert(v); } @@ -377,7 +383,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCacheNormalMap.find(cacheName); if (mSharing && it != mEffectCacheNormalMap.end()) @@ -392,8 +398,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } @@ -410,7 +415,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCacheNormalMap.insert(v); } @@ -450,7 +455,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCache.find(cacheName); if (mSharing && it != mEffectCache.end()) @@ -465,15 +470,14 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCache.insert(v); } @@ -491,32 +495,32 @@ void EffectFactory::Impl::ReleaseCache() mEffectCacheNormalMapSkinned.clear(); } - - //-------------------------------------------------------------------------------------- // EffectFactory //-------------------------------------------------------------------------------------- -EffectFactory::EffectFactory(_In_ ID3D12Device* device) : - pImpl(std::make_shared(device, nullptr, nullptr)) +EffectFactory::EffectFactory(_In_ ID3D12Device* device) + : pImpl(std::make_shared(device, nullptr, nullptr)) {} EffectFactory::EffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) { if (!textureDescriptors) { - throw std::invalid_argument("Texture descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); + throw std::invalid_argument( + "Texture descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); } if (!samplerDescriptors) { - throw std::invalid_argument("Descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); + throw std::invalid_argument( + "Descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); } #if defined(_MSC_VER) || !defined(_WIN32) const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc().Type; const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc().Type; #else - D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2; + D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2; const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc(&tmpDesc1)->Type; const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc(&tmpDesc2)->Type; #endif @@ -541,30 +545,26 @@ EffectFactory::EffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_ pImpl = std::make_shared(device.Get(), textureDescriptors, samplerDescriptors); } +EffectFactory::EffectFactory(EffectFactory&&) noexcept = default; +EffectFactory& EffectFactory::operator=(EffectFactory&&) noexcept = default; +EffectFactory::~EffectFactory() = default; -EffectFactory::EffectFactory(EffectFactory&&) noexcept = default; -EffectFactory& EffectFactory::operator= (EffectFactory&&) noexcept = default; -EffectFactory::~EffectFactory() = default; - - -std::shared_ptr EffectFactory::CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset, - int samplerDescriptorOffset) +std::shared_ptr EffectFactory::CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset, + int samplerDescriptorOffset) { - return pImpl->CreateEffect(info, opaquePipelineState, alphaPipelineState, inputLayout, textureDescriptorOffset, samplerDescriptorOffset); + return pImpl + ->CreateEffect(info, opaquePipelineState, alphaPipelineState, inputLayout, textureDescriptorOffset, samplerDescriptorOffset); } - void EffectFactory::ReleaseCache() { pImpl->ReleaseCache(); } - // Properties. void EffectFactory::SetSharing(bool enabled) noexcept { diff --git a/Src/EffectPipelineStateDescription.cpp b/Src/EffectPipelineStateDescription.cpp index c459927f..cb121fb1 100644 --- a/Src/EffectPipelineStateDescription.cpp +++ b/Src/EffectPipelineStateDescription.cpp @@ -13,60 +13,270 @@ #include "DirectXHelpers.h" #include "PlatformHelpers.h" - using namespace DirectX; namespace { // 0x04C11DB7 is the official polynomial used by PKZip, WinZip and Ethernet - static const uint32_t s_crc32[] = - { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, + static const uint32_t s_crc32[] = { + 0x00000000, + 0x77073096, + 0xee0e612c, + 0x990951ba, + 0x076dc419, + 0x706af48f, + 0xe963a535, + 0x9e6495a3, + 0x0edb8832, + 0x79dcb8a4, + 0xe0d5e91e, + 0x97d2d988, + 0x09b64c2b, + 0x7eb17cbd, + 0xe7b82d07, + 0x90bf1d91, + 0x1db71064, + 0x6ab020f2, + 0xf3b97148, + 0x84be41de, + 0x1adad47d, + 0x6ddde4eb, + 0xf4d4b551, + 0x83d385c7, + 0x136c9856, + 0x646ba8c0, + 0xfd62f97a, + 0x8a65c9ec, + 0x14015c4f, + 0x63066cd9, + 0xfa0f3d63, + 0x8d080df5, + 0x3b6e20c8, + 0x4c69105e, + 0xd56041e4, + 0xa2677172, + 0x3c03e4d1, + 0x4b04d447, + 0xd20d85fd, + 0xa50ab56b, + 0x35b5a8fa, + 0x42b2986c, + 0xdbbbc9d6, + 0xacbcf940, + 0x32d86ce3, + 0x45df5c75, + 0xdcd60dcf, + 0xabd13d59, + 0x26d930ac, + 0x51de003a, + 0xc8d75180, + 0xbfd06116, + 0x21b4f4b5, + 0x56b3c423, + 0xcfba9599, + 0xb8bda50f, + 0x2802b89e, + 0x5f058808, + 0xc60cd9b2, + 0xb10be924, + 0x2f6f7c87, + 0x58684c11, + 0xc1611dab, + 0xb6662d3d, + 0x76dc4190, + 0x01db7106, + 0x98d220bc, + 0xefd5102a, + 0x71b18589, + 0x06b6b51f, + 0x9fbfe4a5, + 0xe8b8d433, + 0x7807c9a2, + 0x0f00f934, + 0x9609a88e, + 0xe10e9818, + 0x7f6a0dbb, + 0x086d3d2d, + 0x91646c97, + 0xe6635c01, + 0x6b6b51f4, + 0x1c6c6162, + 0x856530d8, + 0xf262004e, + 0x6c0695ed, + 0x1b01a57b, + 0x8208f4c1, + 0xf50fc457, + 0x65b0d9c6, + 0x12b7e950, + 0x8bbeb8ea, + 0xfcb9887c, + 0x62dd1ddf, + 0x15da2d49, + 0x8cd37cf3, + 0xfbd44c65, + 0x4db26158, + 0x3ab551ce, + 0xa3bc0074, + 0xd4bb30e2, + 0x4adfa541, + 0x3dd895d7, + 0xa4d1c46d, + 0xd3d6f4fb, + 0x4369e96a, + 0x346ed9fc, + 0xad678846, + 0xda60b8d0, + 0x44042d73, + 0x33031de5, + 0xaa0a4c5f, + 0xdd0d7cc9, + 0x5005713c, + 0x270241aa, + 0xbe0b1010, + 0xc90c2086, + 0x5768b525, + 0x206f85b3, + 0xb966d409, + 0xce61e49f, + 0x5edef90e, + 0x29d9c998, + 0xb0d09822, + 0xc7d7a8b4, + 0x59b33d17, + 0x2eb40d81, + 0xb7bd5c3b, + 0xc0ba6cad, + 0xedb88320, + 0x9abfb3b6, + 0x03b6e20c, + 0x74b1d29a, + 0xead54739, + 0x9dd277af, + 0x04db2615, + 0x73dc1683, + 0xe3630b12, + 0x94643b84, + 0x0d6d6a3e, + 0x7a6a5aa8, + 0xe40ecf0b, + 0x9309ff9d, + 0x0a00ae27, + 0x7d079eb1, + 0xf00f9344, + 0x8708a3d2, + 0x1e01f268, + 0x6906c2fe, + 0xf762575d, + 0x806567cb, + 0x196c3671, + 0x6e6b06e7, + 0xfed41b76, + 0x89d32be0, + 0x10da7a5a, + 0x67dd4acc, + 0xf9b9df6f, + 0x8ebeeff9, + 0x17b7be43, + 0x60b08ed5, + 0xd6d6a3e8, + 0xa1d1937e, + 0x38d8c2c4, + 0x4fdff252, + 0xd1bb67f1, + 0xa6bc5767, + 0x3fb506dd, + 0x48b2364b, + 0xd80d2bda, + 0xaf0a1b4c, + 0x36034af6, + 0x41047a60, + 0xdf60efc3, + 0xa867df55, + 0x316e8eef, + 0x4669be79, + 0xcb61b38c, + 0xbc66831a, + 0x256fd2a0, + 0x5268e236, + 0xcc0c7795, + 0xbb0b4703, + 0x220216b9, + 0x5505262f, + 0xc5ba3bbe, + 0xb2bd0b28, + 0x2bb45a92, + 0x5cb36a04, + 0xc2d7ffa7, + 0xb5d0cf31, + 0x2cd99e8b, + 0x5bdeae1d, + 0x9b64c2b0, + 0xec63f226, + 0x756aa39c, + 0x026d930a, + 0x9c0906a9, + 0xeb0e363f, + 0x72076785, + 0x05005713, + 0x95bf4a82, + 0xe2b87a14, + 0x7bb12bae, + 0x0cb61b38, + 0x92d28e9b, + 0xe5d5be0d, + 0x7cdcefb7, + 0x0bdbdf21, + 0x86d3d2d4, + 0xf1d4e242, + 0x68ddb3f8, + 0x1fda836e, + 0x81be16cd, + 0xf6b9265b, + 0x6fb077e1, + 0x18b74777, + 0x88085ae6, + 0xff0f6a70, + 0x66063bca, + 0x11010b5c, + 0x8f659eff, + 0xf862ae69, + 0x616bffd3, + 0x166ccf45, + 0xa00ae278, + 0xd70dd2ee, + 0x4e048354, + 0x3903b3c2, + 0xa7672661, + 0xd06016f7, + 0x4969474d, + 0x3e6e77db, + 0xaed16a4a, + 0xd9d65adc, + 0x40df0b66, + 0x37d83bf0, + 0xa9bcae53, + 0xdebb9ec5, + 0x47b2cf7f, + 0x30b5ffe9, + 0xbdbdf21c, + 0xcabac28a, + 0x53b39330, + 0x24b4a3a6, + 0xbad03605, + 0xcdd70693, + 0x54de5729, + 0x23d967bf, + 0xb3667a2e, + 0xc4614ab8, + 0x5d681b02, + 0x2a6f2b94, + 0xb40bbe37, + 0xc30c8ea1, + 0x5a05df1b, + 0x2d02ef8d, }; -} - +} // namespace uint32_t EffectPipelineStateDescription::ComputeHash() const noexcept { @@ -83,13 +293,11 @@ uint32_t EffectPipelineStateDescription::ComputeHash() const noexcept return crc ^ 0xFFFFFFFF; } - -void EffectPipelineStateDescription::CreatePipelineState( - _In_ ID3D12Device* device, - _In_ ID3D12RootSignature* rootSignature, - const D3D12_SHADER_BYTECODE& vertexShader, - const D3D12_SHADER_BYTECODE& pixelShader, - _Outptr_ ID3D12PipelineState** pPipelineState) const +void EffectPipelineStateDescription::CreatePipelineState(_In_ ID3D12Device* device, + _In_ ID3D12RootSignature* rootSignature, + const D3D12_SHADER_BYTECODE& vertexShader, + const D3D12_SHADER_BYTECODE& pixelShader, + _Outptr_ ID3D12PipelineState** pPipelineState) const { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -98,20 +306,19 @@ void EffectPipelineStateDescription::CreatePipelineState( auto psoDesc = GetDesc(); #else D3D12_GRAPHICS_PIPELINE_STATE_DESC tmpPSODesc; - auto& psoDesc = *GetDesc(&tmpPSODesc); + auto& psoDesc = *GetDesc(&tmpPSODesc); #endif psoDesc.pRootSignature = rootSignature; - psoDesc.VS = vertexShader; - psoDesc.PS = pixelShader; + psoDesc.VS = vertexShader; + psoDesc.PS = pixelShader; - HRESULT hr = device->CreateGraphicsPipelineState( - &psoDesc, - IID_GRAPHICS_PPV_ARGS(pPipelineState)); + HRESULT hr = device->CreateGraphicsPipelineState(&psoDesc, IID_GRAPHICS_PPV_ARGS(pPipelineState)); if (FAILED(hr)) { - DebugTrace("ERROR: CreatePipelineState failed to create a PSO. Enable the Direct3D Debug Layer for more information (%08X)\n", static_cast(hr)); + DebugTrace("ERROR: CreatePipelineState failed to create a PSO. Enable the Direct3D Debug Layer for more information (%08X)\n", + static_cast(hr)); throw std::runtime_error("CreateGraphicsPipelineState"); } } diff --git a/Src/EffectTextureFactory.cpp b/Src/EffectTextureFactory.cpp index 96fa1b46..ce006458 100644 --- a/Src/EffectTextureFactory.cpp +++ b/Src/EffectTextureFactory.cpp @@ -19,36 +19,34 @@ #include - using namespace DirectX; using Microsoft::WRL::ComPtr; - class EffectTextureFactory::Impl { public: struct TextureCacheEntry { ComPtr mResource; - bool mIsCubeMap; - size_t slot; + bool mIsCubeMap; + size_t slot; - TextureCacheEntry() noexcept : mIsCubeMap(false), slot(0) {} + TextureCacheEntry() noexcept + : mIsCubeMap(false), + slot(0) + {} }; - using TextureCache = std::map< std::wstring, TextureCacheEntry >; - - Impl( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - _In_ ID3D12DescriptorHeap* descriptorHeap) - : mPath{} - , mTextureDescriptorHeap(descriptorHeap) - , mDevice(device) - , mResourceUploadBatch(resourceUploadBatch) - , mSharing(true) - , mForceSRGB(false) - , mAutoGenMips(false) + using TextureCache = std::map; + + Impl(_In_ ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch, _In_ ID3D12DescriptorHeap* descriptorHeap) + : mPath{}, + mTextureDescriptorHeap(descriptorHeap), + mDevice(device), + mResourceUploadBatch(resourceUploadBatch), + mSharing(true), + mForceSRGB(false), + mAutoGenMips(false) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -56,26 +54,25 @@ class EffectTextureFactory::Impl *mPath = 0; } - Impl( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - _In_ size_t numDescriptors, + Impl(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + _In_ size_t numDescriptors, _In_ D3D12_DESCRIPTOR_HEAP_FLAGS descriptorHeapFlags) - : mPath{} - , mTextureDescriptorHeap(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, descriptorHeapFlags, numDescriptors) - , mDevice(device) - , mResourceUploadBatch(resourceUploadBatch) - , mSharing(true) - , mForceSRGB(false) - , mAutoGenMips(false) + : mPath{}, + mTextureDescriptorHeap(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, descriptorHeapFlags, numDescriptors), + mDevice(device), + mResourceUploadBatch(resourceUploadBatch), + mSharing(true), + mForceSRGB(false), + mAutoGenMips(false) { SetDebugObjectName(mTextureDescriptorHeap.Heap(), L"EffectTextureFactory"); } - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = delete; + Impl(Impl&&) = delete; Impl& operator=(Impl&&) = delete; size_t CreateTexture(_In_z_ const wchar_t* name, int descriptorSlot); @@ -91,21 +88,19 @@ class EffectTextureFactory::Impl std::vector mResources; // flat list of unique resources so we can index into it private: - ComPtr mDevice; - ResourceUploadBatch& mResourceUploadBatch; + ComPtr mDevice; + ResourceUploadBatch& mResourceUploadBatch; - TextureCache mTextureCache; + TextureCache mTextureCache; - bool mSharing; - bool mForceSRGB; - bool mAutoGenMips; + bool mSharing; + bool mForceSRGB; + bool mAutoGenMips; - std::mutex mutex; + std::mutex mutex; }; - -_Use_decl_annotations_ -size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int descriptorSlot) +_Use_decl_annotations_ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int descriptorSlot) { if (!name) throw std::invalid_argument("name required for CreateTexture"); @@ -148,8 +143,7 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int if (isdds) { - HRESULT hr = CreateDDSTextureFromFileEx( - mDevice.Get(), + HRESULT hr = CreateDDSTextureFromFileEx(mDevice.Get(), mResourceUploadBatch, fullName, 0u, @@ -160,22 +154,23 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int &textureEntry.mIsCubeMap); if (FAILED(hr)) { - DebugTrace("ERROR: CreateDDSTextureFromFile failed (%08X) for '%ls'\n", - static_cast(hr), fullName); + DebugTrace("ERROR: CreateDDSTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); throw std::runtime_error("EffectTextureFactory::CreateDDSTextureFromFile"); } } else { static_assert(static_cast(DDS_LOADER_DEFAULT) == static_cast(WIC_LOADER_DEFAULT), "DDS/WIC Load flags mismatch"); - static_assert(static_cast(DDS_LOADER_FORCE_SRGB) == static_cast(WIC_LOADER_FORCE_SRGB), "DDS/WIC Load flags mismatch"); - static_assert(static_cast(DDS_LOADER_MIP_AUTOGEN) == static_cast(WIC_LOADER_MIP_AUTOGEN), "DDS/WIC Load flags mismatch"); - static_assert(static_cast(DDS_LOADER_MIP_RESERVE) == static_cast(WIC_LOADER_MIP_RESERVE), "DDS/WIC Load flags mismatch"); + static_assert(static_cast(DDS_LOADER_FORCE_SRGB) == static_cast(WIC_LOADER_FORCE_SRGB), + "DDS/WIC Load flags mismatch"); + static_assert(static_cast(DDS_LOADER_MIP_AUTOGEN) == static_cast(WIC_LOADER_MIP_AUTOGEN), + "DDS/WIC Load flags mismatch"); + static_assert(static_cast(DDS_LOADER_MIP_RESERVE) == static_cast(WIC_LOADER_MIP_RESERVE), + "DDS/WIC Load flags mismatch"); textureEntry.mIsCubeMap = false; - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), mResourceUploadBatch, fullName, 0u, @@ -184,8 +179,7 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int textureEntry.mResource.ReleaseAndGetAddressOf()); if (FAILED(hr)) { - DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", - static_cast(hr), fullName); + DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); throw std::runtime_error("EffectTextureFactory::CreateWICTextureFromFile"); } } @@ -215,48 +209,37 @@ void EffectTextureFactory::Impl::ReleaseCache() mTextureCache.clear(); } - - //-------------------------------------------------------------------------------------- // EffectTextureFactory //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -EffectTextureFactory::EffectTextureFactory( - ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - ID3D12DescriptorHeap* descriptorHeap) noexcept(false) : - pImpl(std::make_unique(device, resourceUploadBatch, descriptorHeap)) +_Use_decl_annotations_ EffectTextureFactory::EffectTextureFactory(ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + ID3D12DescriptorHeap* descriptorHeap) noexcept(false) + : pImpl(std::make_unique(device, resourceUploadBatch, descriptorHeap)) {} -_Use_decl_annotations_ -EffectTextureFactory::EffectTextureFactory( - ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - size_t numDescriptors, - D3D12_DESCRIPTOR_HEAP_FLAGS descriptorHeapFlags) noexcept(false) : - pImpl(std::make_unique(device, resourceUploadBatch, numDescriptors, descriptorHeapFlags)) +_Use_decl_annotations_ EffectTextureFactory::EffectTextureFactory(ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + size_t numDescriptors, + D3D12_DESCRIPTOR_HEAP_FLAGS descriptorHeapFlags) noexcept(false) + : pImpl(std::make_unique(device, resourceUploadBatch, numDescriptors, descriptorHeapFlags)) {} +EffectTextureFactory::EffectTextureFactory(EffectTextureFactory&&) noexcept = default; +EffectTextureFactory& EffectTextureFactory::operator=(EffectTextureFactory&&) noexcept = default; +EffectTextureFactory::~EffectTextureFactory() = default; -EffectTextureFactory::EffectTextureFactory(EffectTextureFactory&&) noexcept = default; -EffectTextureFactory& EffectTextureFactory::operator= (EffectTextureFactory&&) noexcept = default; -EffectTextureFactory::~EffectTextureFactory() = default; - - -_Use_decl_annotations_ -size_t EffectTextureFactory::CreateTexture(_In_z_ const wchar_t* name, int descriptorIndex) +_Use_decl_annotations_ size_t EffectTextureFactory::CreateTexture(_In_z_ const wchar_t* name, int descriptorIndex) { return pImpl->CreateTexture(name, descriptorIndex); } - void EffectTextureFactory::ReleaseCache() { pImpl->ReleaseCache(); } - // Properties. void EffectTextureFactory::SetSharing(bool enabled) noexcept { @@ -284,7 +267,7 @@ void EffectTextureFactory::SetDirectory(_In_opt_z_ const wchar_t* path) noexcept // Ensure it has a trailing slash if (pImpl->mPath[len - 1] != L'\\') { - pImpl->mPath[len] = L'\\'; + pImpl->mPath[len] = L'\\'; pImpl->mPath[len + 1] = 0; } } @@ -314,8 +297,7 @@ size_t EffectTextureFactory::ResourceCount() const noexcept return pImpl->mResources.size(); } -_Use_decl_annotations_ -void EffectTextureFactory::GetResource(size_t slot, ID3D12Resource** resource, bool* isCubeMap) +_Use_decl_annotations_ void EffectTextureFactory::GetResource(size_t slot, ID3D12Resource** resource, bool* isCubeMap) { if (slot >= pImpl->mResources.size()) throw std::invalid_argument("Resource slot is invalid"); diff --git a/Src/EnvironmentMapEffect.cpp b/Src/EnvironmentMapEffect.cpp index d1900331..14a6f1ab 100644 --- a/Src/EnvironmentMapEffect.cpp +++ b/Src/EnvironmentMapEffect.cpp @@ -19,9 +19,9 @@ namespace struct EnvironmentMapEffectConstants { XMVECTOR environmentMapSpecular; - float environmentMapAmount; - float fresnelFactor; - float pad[2]; + float environmentMapAmount; + float fresnelFactor; + float pad[2]; XMVECTOR diffuseColor; XMVECTOR emissiveColor; @@ -41,32 +41,31 @@ namespace static_assert((sizeof(EnvironmentMapEffectConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct EnvironmentMapEffectTraits { using ConstantBufferType = EnvironmentMapEffectConstants; - static constexpr int VertexShaderCount = 6; - static constexpr int PixelShaderCount = 16; + static constexpr int VertexShaderCount = 6; + static constexpr int PixelShaderCount = 16; static constexpr int ShaderPermutationCount = 40; - static constexpr int RootSignatureCount = 1; + static constexpr int RootSignatureCount = 1; }; -} +} // namespace // Internal EnvironmentMapEffect implementation class. class EnvironmentMapEffect::Impl : public EffectBase { public: - Impl(_In_ ID3D12Device* device, - uint32_t effectFlags, + Impl(_In_ ID3D12Device* device, + uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - EnvironmentMapEffect::Mapping mapping); + EnvironmentMapEffect::Mapping mapping); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; enum RootParameterIndex @@ -91,7 +90,6 @@ class EnvironmentMapEffect::Impl : public EffectBase void Apply(_In_ ID3D12GraphicsCommandList* commandList); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -205,196 +203,192 @@ namespace #include "EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnel.inc" #include "EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnelNoFog.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { EnvironmentMapEffect_VSEnvMap, sizeof(EnvironmentMapEffect_VSEnvMap) }, - { EnvironmentMapEffect_VSEnvMapFresnel, sizeof(EnvironmentMapEffect_VSEnvMapFresnel) }, - { EnvironmentMapEffect_VSEnvMapPixelLighting, sizeof(EnvironmentMapEffect_VSEnvMapPixelLighting) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { EnvironmentMapEffect_VSEnvMap, sizeof(EnvironmentMapEffect_VSEnvMap) }, + { EnvironmentMapEffect_VSEnvMapFresnel, sizeof(EnvironmentMapEffect_VSEnvMapFresnel) }, + { EnvironmentMapEffect_VSEnvMapPixelLighting, sizeof(EnvironmentMapEffect_VSEnvMapPixelLighting) }, - { EnvironmentMapEffect_VSEnvMapBn, sizeof(EnvironmentMapEffect_VSEnvMapBn) }, - { EnvironmentMapEffect_VSEnvMapFresnelBn, sizeof(EnvironmentMapEffect_VSEnvMapFresnelBn) }, + { EnvironmentMapEffect_VSEnvMapBn, sizeof(EnvironmentMapEffect_VSEnvMapBn) }, + { EnvironmentMapEffect_VSEnvMapFresnelBn, sizeof(EnvironmentMapEffect_VSEnvMapFresnelBn) }, { EnvironmentMapEffect_VSEnvMapPixelLightingBn, sizeof(EnvironmentMapEffect_VSEnvMapPixelLightingBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // basic - 0, // basic, no fog - 1, // fresnel - 1, // fresnel, no fog - 0, // specular - 0, // specular, no fog - 1, // fresnel + specular - 1, // fresnel + specular, no fog - - 2, // pixel lighting - 2, // pixel lighting, no fog - 2, // pixel lighting, fresnel - 2, // pixel lighting, fresnel, no fog - - 3, // basic (biased vertex normals) - 3, // basic (biased vertex normals), no fog - 4, // fresnel (biased vertex normals) - 4, // fresnel (biased vertex normals), no fog - 3, // specular (biased vertex normals) - 3, // specular (biased vertex normals), no fog - 4, // fresnel + specular (biased vertex normals) - 4, // fresnel + specular (biased vertex normals), no fog - - 5, // pixel lighting (biased vertex normals) - 5, // pixel lighting (biased vertex normals), no fog - 5, // pixel lighting (biased vertex normals), fresnel - 5, // pixel lighting (biased vertex normals), fresnel, no fog - - 2, // spheremap pixel lighting - 2, // spheremap pixel lighting, no fog - 2, // spheremap pixel lighting, fresnel - 2, // spheremap pixel lighting, fresnel, no fog - - 5, // spheremap pixel lighting (biased vertex normals) - 5, // spheremap pixel lighting (biased vertex normals), no fog - 5, // spheremap pixel lighting (biased vertex normals), fresnel - 5, // spheremap pixel lighting (biased vertex normals), fresnel, no fog - - 2, // dual-parabola pixel lighting - 2, // dual-parabola pixel lighting, no fog - 2, // dual-parabola pixel lighting, fresnel - 2, // dual-parabola pixel lighting, fresnel, no fog - - 5, // dual-parabola pixel lighting (biased vertex normals) - 5, // dual-parabola pixel lighting (biased vertex normals), no fog - 5, // dual-parabola pixel lighting (biased vertex normals), fresnel - 5, // dual-parabola pixel lighting (biased vertex normals), fresnel, no fog +const int EffectBase::VertexShaderIndices[] = { + 0, // basic + 0, // basic, no fog + 1, // fresnel + 1, // fresnel, no fog + 0, // specular + 0, // specular, no fog + 1, // fresnel + specular + 1, // fresnel + specular, no fog + + 2, // pixel lighting + 2, // pixel lighting, no fog + 2, // pixel lighting, fresnel + 2, // pixel lighting, fresnel, no fog + + 3, // basic (biased vertex normals) + 3, // basic (biased vertex normals), no fog + 4, // fresnel (biased vertex normals) + 4, // fresnel (biased vertex normals), no fog + 3, // specular (biased vertex normals) + 3, // specular (biased vertex normals), no fog + 4, // fresnel + specular (biased vertex normals) + 4, // fresnel + specular (biased vertex normals), no fog + + 5, // pixel lighting (biased vertex normals) + 5, // pixel lighting (biased vertex normals), no fog + 5, // pixel lighting (biased vertex normals), fresnel + 5, // pixel lighting (biased vertex normals), fresnel, no fog + + 2, // spheremap pixel lighting + 2, // spheremap pixel lighting, no fog + 2, // spheremap pixel lighting, fresnel + 2, // spheremap pixel lighting, fresnel, no fog + + 5, // spheremap pixel lighting (biased vertex normals) + 5, // spheremap pixel lighting (biased vertex normals), no fog + 5, // spheremap pixel lighting (biased vertex normals), fresnel + 5, // spheremap pixel lighting (biased vertex normals), fresnel, no fog + + 2, // dual-parabola pixel lighting + 2, // dual-parabola pixel lighting, no fog + 2, // dual-parabola pixel lighting, fresnel + 2, // dual-parabola pixel lighting, fresnel, no fog + + 5, // dual-parabola pixel lighting (biased vertex normals) + 5, // dual-parabola pixel lighting (biased vertex normals), no fog + 5, // dual-parabola pixel lighting (biased vertex normals), fresnel + 5, // dual-parabola pixel lighting (biased vertex normals), fresnel, no fog }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { EnvironmentMapEffect_PSEnvMap, sizeof(EnvironmentMapEffect_PSEnvMap) }, - { EnvironmentMapEffect_PSEnvMapNoFog, sizeof(EnvironmentMapEffect_PSEnvMapNoFog) }, - { EnvironmentMapEffect_PSEnvMapSpecular, sizeof(EnvironmentMapEffect_PSEnvMapSpecular) }, - { EnvironmentMapEffect_PSEnvMapSpecularNoFog, sizeof(EnvironmentMapEffect_PSEnvMapSpecularNoFog) }, - { EnvironmentMapEffect_PSEnvMapPixelLighting, sizeof(EnvironmentMapEffect_PSEnvMapPixelLighting) }, - { EnvironmentMapEffect_PSEnvMapPixelLightingNoFog, sizeof(EnvironmentMapEffect_PSEnvMapPixelLightingNoFog) }, - { EnvironmentMapEffect_PSEnvMapPixelLightingFresnel, sizeof(EnvironmentMapEffect_PSEnvMapPixelLightingFresnel) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { EnvironmentMapEffect_PSEnvMap, sizeof(EnvironmentMapEffect_PSEnvMap) }, + { EnvironmentMapEffect_PSEnvMapNoFog, sizeof(EnvironmentMapEffect_PSEnvMapNoFog) }, + { EnvironmentMapEffect_PSEnvMapSpecular, sizeof(EnvironmentMapEffect_PSEnvMapSpecular) }, + { EnvironmentMapEffect_PSEnvMapSpecularNoFog, sizeof(EnvironmentMapEffect_PSEnvMapSpecularNoFog) }, + { EnvironmentMapEffect_PSEnvMapPixelLighting, sizeof(EnvironmentMapEffect_PSEnvMapPixelLighting) }, + { EnvironmentMapEffect_PSEnvMapPixelLightingNoFog, sizeof(EnvironmentMapEffect_PSEnvMapPixelLightingNoFog) }, + { EnvironmentMapEffect_PSEnvMapPixelLightingFresnel, sizeof(EnvironmentMapEffect_PSEnvMapPixelLightingFresnel) }, { EnvironmentMapEffect_PSEnvMapPixelLightingFresnelNoFog, sizeof(EnvironmentMapEffect_PSEnvMapPixelLightingFresnelNoFog) }, - { EnvironmentMapEffect_PSEnvMapSpherePixelLighting, sizeof(EnvironmentMapEffect_PSEnvMapSpherePixelLighting) }, - { EnvironmentMapEffect_PSEnvMapSpherePixelLightingNoFog, sizeof(EnvironmentMapEffect_PSEnvMapSpherePixelLightingNoFog) }, - { EnvironmentMapEffect_PSEnvMapSpherePixelLightingFresnel, sizeof(EnvironmentMapEffect_PSEnvMapSpherePixelLightingFresnel) }, + { EnvironmentMapEffect_PSEnvMapSpherePixelLighting, sizeof(EnvironmentMapEffect_PSEnvMapSpherePixelLighting) }, + { EnvironmentMapEffect_PSEnvMapSpherePixelLightingNoFog, sizeof(EnvironmentMapEffect_PSEnvMapSpherePixelLightingNoFog) }, + { EnvironmentMapEffect_PSEnvMapSpherePixelLightingFresnel, sizeof(EnvironmentMapEffect_PSEnvMapSpherePixelLightingFresnel) }, { EnvironmentMapEffect_PSEnvMapSpherePixelLightingFresnelNoFog, sizeof(EnvironmentMapEffect_PSEnvMapSpherePixelLightingFresnelNoFog) }, - { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLighting, sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLighting) }, - { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingNoFog, sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingNoFog) }, - { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnel, sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnel) }, - { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnelNoFog, sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnelNoFog) }, + { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLighting, sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLighting) }, + { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingNoFog, sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingNoFog) }, + { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnel, + sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnel) }, + { EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnelNoFog, + sizeof(EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnelNoFog) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // basic - 1, // basic, no fog - 0, // fresnel - 1, // fresnel, no fog - 2, // specular - 3, // specular, no fog - 2, // fresnel + specular - 3, // fresnel + specular, no fog - - 4, // per pixel lighting - 5, // per pixel lighting, no fog - 6, // per pixel lighting, fresnel - 7, // per pixel lighting, fresnel, no fog - - 0, // basic (biased vertex normals) - 1, // basic (biased vertex normals), no fog - 0, // fresnel (biased vertex normals) - 1, // fresnel (biased vertex normals), no fog - 2, // specular (biased vertex normals) - 3, // specular (biased vertex normals), no fog - 2, // fresnel + specular (biased vertex normals) - 3, // fresnel + specular (biased vertex normals), no fog - - 4, // per pixel lighting (biased vertex normals) - 5, // per pixel lighting (biased vertex normals), no fog - 6, // per pixel lighting (biased vertex normals), fresnel - 7, // per pixel lighting (biased vertex normals), fresnel, no fog - - 8, // spheremap pixel lighting - 9, // spheremap pixel lighting, no fog - 10, // spheremap pixel lighting, fresnel - 11, // spheremap pixel lighting, fresnel, no fog - - 8, // spheremap pixel lighting (biased vertex normals) - 9, // spheremap pixel lighting (biased vertex normals), no fog - 10, // spheremap pixel lighting (biased vertex normals), fresnel - 11, // spheremap pixel lighting (biased vertex normals), fresnel, no fog - - 12, // dual-parabola pixel lighting - 13, // dual-parabola pixel lighting, no fog - 14, // dual-parabola pixel lighting, fresnel - 15, // dual-parabola pixel lighting, fresnel, no fog - - 12, // dual-parabola pixel lighting (biased vertex normals) - 13, // dual-parabola pixel lighting (biased vertex normals), no fog - 14, // dual-parabola pixel lighting (biased vertex normals), fresnel - 15, // dual-parabola pixel lighting (biased vertex normals), fresnel, no fog +const int EffectBase::PixelShaderIndices[] = { + 0, // basic + 1, // basic, no fog + 0, // fresnel + 1, // fresnel, no fog + 2, // specular + 3, // specular, no fog + 2, // fresnel + specular + 3, // fresnel + specular, no fog + + 4, // per pixel lighting + 5, // per pixel lighting, no fog + 6, // per pixel lighting, fresnel + 7, // per pixel lighting, fresnel, no fog + + 0, // basic (biased vertex normals) + 1, // basic (biased vertex normals), no fog + 0, // fresnel (biased vertex normals) + 1, // fresnel (biased vertex normals), no fog + 2, // specular (biased vertex normals) + 3, // specular (biased vertex normals), no fog + 2, // fresnel + specular (biased vertex normals) + 3, // fresnel + specular (biased vertex normals), no fog + + 4, // per pixel lighting (biased vertex normals) + 5, // per pixel lighting (biased vertex normals), no fog + 6, // per pixel lighting (biased vertex normals), fresnel + 7, // per pixel lighting (biased vertex normals), fresnel, no fog + + 8, // spheremap pixel lighting + 9, // spheremap pixel lighting, no fog + 10, // spheremap pixel lighting, fresnel + 11, // spheremap pixel lighting, fresnel, no fog + + 8, // spheremap pixel lighting (biased vertex normals) + 9, // spheremap pixel lighting (biased vertex normals), no fog + 10, // spheremap pixel lighting (biased vertex normals), fresnel + 11, // spheremap pixel lighting (biased vertex normals), fresnel, no fog + + 12, // dual-parabola pixel lighting + 13, // dual-parabola pixel lighting, no fog + 14, // dual-parabola pixel lighting, fresnel + 15, // dual-parabola pixel lighting, fresnel, no fog + + 12, // dual-parabola pixel lighting (biased vertex normals) + 13, // dual-parabola pixel lighting (biased vertex normals), no fog + 14, // dual-parabola pixel lighting (biased vertex normals), fresnel + 15, // dual-parabola pixel lighting (biased vertex normals), fresnel, no fog }; #pragma endregion // Global pool of per-device EnvironmentMapEffect resources. template<> -SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - +SharedResourcePool::DeviceResources> + EffectBase::deviceResourcesPool = {}; // Constructor. -EnvironmentMapEffect::Impl::Impl( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - EnvironmentMapEffect::Mapping mapping) +EnvironmentMapEffect::Impl::Impl(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + EnvironmentMapEffect::Mapping mapping) : EffectBase(device), - texture{}, - textureSampler{}, - environmentMap{}, - environmentMapSampler{} -{ - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == EnvironmentMapEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == EnvironmentMapEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); - - switch(mapping) + texture{}, + textureSampler{}, + environmentMap{}, + environmentMapSampler{} +{ + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) + == EnvironmentMapEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) + == EnvironmentMapEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) + == EnvironmentMapEffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) + == EnvironmentMapEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + + switch (mapping) { case Mapping_Cube: case Mapping_Sphere: - case Mapping_DualParabola: - break; + case Mapping_DualParabola: break; - default: - throw std::invalid_argument("Unsupported mapping"); + default: throw std::invalid_argument("Unsupported mapping"); } // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; CD3DX12_ROOT_PARAMETER rootParameters[RootParameterIndex::RootParameterCount] = {}; @@ -404,13 +398,17 @@ EnvironmentMapEffect::Impl::Impl( const CD3DX12_DESCRIPTOR_RANGE textureDescriptor(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); const CD3DX12_DESCRIPTOR_RANGE textureSamplerDescriptor(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0); rootParameters[RootParameterIndex::TextureSRV].InitAsDescriptorTable(1, &textureDescriptor, D3D12_SHADER_VISIBILITY_PIXEL); - rootParameters[RootParameterIndex::TextureSampler].InitAsDescriptorTable(1, &textureSamplerDescriptor, D3D12_SHADER_VISIBILITY_PIXEL); + rootParameters[RootParameterIndex::TextureSampler].InitAsDescriptorTable(1, + &textureSamplerDescriptor, + D3D12_SHADER_VISIBILITY_PIXEL); // Texture 2 const CD3DX12_DESCRIPTOR_RANGE cubemapDescriptor(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1); const CD3DX12_DESCRIPTOR_RANGE cubemapSamplerDescriptor(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 1); rootParameters[RootParameterIndex::CubemapSRV].InitAsDescriptorTable(1, &cubemapDescriptor, D3D12_SHADER_VISIBILITY_PIXEL); - rootParameters[RootParameterIndex::CubemapSampler].InitAsDescriptorTable(1, &cubemapSamplerDescriptor, D3D12_SHADER_VISIBILITY_PIXEL); + rootParameters[RootParameterIndex::CubemapSampler].InitAsDescriptorTable(1, + &cubemapSamplerDescriptor, + D3D12_SHADER_VISIBILITY_PIXEL); // Create the root signature CD3DX12_ROOT_SIGNATURE_DESC rsigDesc = {}; @@ -435,7 +433,7 @@ EnvironmentMapEffect::Impl::Impl( } constants.environmentMapAmount = 1; - constants.fresnelFactor = 1; + constants.fresnelFactor = 1; XMVECTOR unwantedOutput[MaxDirectionalLights]; @@ -453,8 +451,7 @@ EnvironmentMapEffect::Impl::Impl( assert(pi >= 0 && pi < EnvironmentMapEffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < EnvironmentMapEffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -463,10 +460,7 @@ EnvironmentMapEffect::Impl::Impl( SetDebugObjectName(mPipelineState.Get(), L"EnvironmentMapEffect"); } - -int EnvironmentMapEffect::Impl::GetPipelineStatePermutation( - EnvironmentMapEffect::Mapping mapping, - uint32_t effectFlags) const noexcept +int EnvironmentMapEffect::Impl::GetPipelineStatePermutation(EnvironmentMapEffect::Mapping mapping, uint32_t effectFlags) const noexcept { const bool biasedVertexNormals = (effectFlags & EffectFlags::BiasedVertexNormals) != 0; @@ -526,7 +520,6 @@ int EnvironmentMapEffect::Impl::GetPipelineStatePermutation( return permutation; } - // Sets our state onto the D3D device. void EnvironmentMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { @@ -535,7 +528,14 @@ void EnvironmentMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandLi fog.SetConstants(dirtyFlags, matrices.worldView, constants.fogVector); - lights.SetConstants(dirtyFlags, matrices, constants.world, constants.worldInverseTranspose, constants.eyePosition, constants.diffuseColor, constants.emissiveColor, true); + lights.SetConstants(dirtyFlags, + matrices, + constants.world, + constants.worldInverseTranspose, + constants.eyePosition, + constants.diffuseColor, + constants.emissiveColor, + true); UpdateConstants(); @@ -545,16 +545,21 @@ void EnvironmentMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandLi // Set the textures if (!texture.ptr || !environmentMap.ptr) { - DebugTrace("ERROR: Missing texture(s) for EnvironmentMapEffect (texture %llu, environmentMap %llu)\n", texture.ptr, environmentMap.ptr); + DebugTrace("ERROR: Missing texture(s) for EnvironmentMapEffect (texture %llu, environmentMap %llu)\n", + texture.ptr, + environmentMap.ptr); throw std::runtime_error("EnvironmentMapEffect"); } if (!textureSampler.ptr || !environmentMapSampler.ptr) { - DebugTrace("ERROR: Missing sampler(s) for EnvironmentMapEffect (sampler %llu, environmentMap %llu)\n", textureSampler.ptr, environmentMapSampler.ptr); + DebugTrace("ERROR: Missing sampler(s) for EnvironmentMapEffect (sampler %llu, environmentMap %llu)\n", + textureSampler.ptr, + environmentMapSampler.ptr); throw std::runtime_error("EnvironmentMapEffect"); } - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heaps. commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSampler, textureSampler); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::CubemapSRV, environmentMap); @@ -567,30 +572,24 @@ void EnvironmentMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandLi commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - // Public constructor. -EnvironmentMapEffect::EnvironmentMapEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - EnvironmentMapEffect::Mapping mapping) +EnvironmentMapEffect::EnvironmentMapEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + EnvironmentMapEffect::Mapping mapping) : pImpl(std::make_unique(device, effectFlags, pipelineDescription, mapping)) {} - -EnvironmentMapEffect::EnvironmentMapEffect(EnvironmentMapEffect&&) noexcept = default; -EnvironmentMapEffect& EnvironmentMapEffect::operator= (EnvironmentMapEffect&&) noexcept = default; -EnvironmentMapEffect::~EnvironmentMapEffect() = default; - +EnvironmentMapEffect::EnvironmentMapEffect(EnvironmentMapEffect&&) noexcept = default; +EnvironmentMapEffect& EnvironmentMapEffect::operator=(EnvironmentMapEffect&&) noexcept = default; +EnvironmentMapEffect::~EnvironmentMapEffect() = default; // IEffect methods. -void EnvironmentMapEffect::Apply( - _In_ ID3D12GraphicsCommandList* cmdList) +void EnvironmentMapEffect::Apply(_In_ ID3D12GraphicsCommandList* cmdList) { pImpl->Apply(cmdList); } - // Camera settings. void XM_CALLCONV EnvironmentMapEffect::SetWorld(FXMMATRIX value) { @@ -599,7 +598,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::FogVector; } - void XM_CALLCONV EnvironmentMapEffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -607,7 +605,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; } - void XM_CALLCONV EnvironmentMapEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -615,17 +612,16 @@ void XM_CALLCONV EnvironmentMapEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV EnvironmentMapEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; - pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; + pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition + | EffectDirtyFlags::FogVector; } - // Material settings. void XM_CALLCONV EnvironmentMapEffect::SetDiffuseColor(FXMVECTOR value) { @@ -634,7 +630,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV EnvironmentMapEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -642,7 +637,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetEmissiveColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void EnvironmentMapEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -650,16 +644,14 @@ void EnvironmentMapEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV EnvironmentMapEffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->lights.diffuseColor = value; - pImpl->lights.alpha = XMVectorGetW(value); + pImpl->lights.alpha = XMVectorGetW(value); pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - // Light settings. void XM_CALLCONV EnvironmentMapEffect::SetAmbientLightColor(FXMVECTOR value) { @@ -668,7 +660,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetAmbientLightColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void EnvironmentMapEffect::SetLightEnabled(int whichLight, bool value) { XMVECTOR unwantedOutput[MaxDirectionalLights] = {}; @@ -676,7 +667,6 @@ void EnvironmentMapEffect::SetLightEnabled(int whichLight, bool value) pImpl->dirtyFlags |= pImpl->lights.SetLightEnabled(whichLight, value, pImpl->constants.lightDiffuseColor, unwantedOutput); } - void XM_CALLCONV EnvironmentMapEffect::SetLightDirection(int whichLight, FXMVECTOR value) { EffectLights::ValidateLightIndex(whichLight); @@ -686,25 +676,21 @@ void XM_CALLCONV EnvironmentMapEffect::SetLightDirection(int whichLight, FXMVECT pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV EnvironmentMapEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR value) { pImpl->dirtyFlags |= pImpl->lights.SetLightDiffuseColor(whichLight, value, pImpl->constants.lightDiffuseColor); } - void XM_CALLCONV EnvironmentMapEffect::SetLightSpecularColor(int, FXMVECTOR) { // Unsupported interface method. } - void EnvironmentMapEffect::EnableDefaultLighting() { EffectLights::EnableDefaultLighting(this); } - // Fog settings. void EnvironmentMapEffect::SetFogStart(float value) { @@ -713,7 +699,6 @@ void EnvironmentMapEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void EnvironmentMapEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -721,7 +706,6 @@ void EnvironmentMapEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV EnvironmentMapEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -729,22 +713,19 @@ void XM_CALLCONV EnvironmentMapEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void EnvironmentMapEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE texture, D3D12_GPU_DESCRIPTOR_HANDLE sampler) { - pImpl->texture = texture; + pImpl->texture = texture; pImpl->textureSampler = sampler; } - void EnvironmentMapEffect::SetEnvironmentMap(D3D12_GPU_DESCRIPTOR_HANDLE texture, D3D12_GPU_DESCRIPTOR_HANDLE sampler) { - pImpl->environmentMap = texture; + pImpl->environmentMap = texture; pImpl->environmentMapSampler = sampler; } - // Additional settings. void EnvironmentMapEffect::SetEnvironmentMapAmount(float value) { @@ -753,7 +734,6 @@ void EnvironmentMapEffect::SetEnvironmentMapAmount(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV EnvironmentMapEffect::SetEnvironmentMapSpecular(FXMVECTOR value) { pImpl->constants.environmentMapSpecular = value; @@ -761,7 +741,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetEnvironmentMapSpecular(FXMVECTOR value pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void EnvironmentMapEffect::SetFresnelFactor(float value) { pImpl->constants.fresnelFactor = value; diff --git a/Src/GamePad.cpp b/Src/GamePad.cpp index 5baac5ec..27373e6c 100644 --- a/Src/GamePad.cpp +++ b/Src/GamePad.cpp @@ -16,10 +16,9 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - namespace { - constexpr float c_XboxOneThumbDeadZone = .24f; // Recommended Xbox One controller deadzone + constexpr float c_XboxOneThumbDeadZone = .24f; // Recommended Xbox One controller deadzone float ApplyLinearDeadZone(float value, float maxValue, float deadZoneSize) noexcept { @@ -44,14 +43,13 @@ namespace return std::max(-1.f, std::min(scaledValue, 1.f)); } - void ApplyStickDeadZone( - float x, - float y, - GamePad::DeadZone deadZoneMode, - float maxValue, - float deadZoneSize, - _Out_ float& resultX, - _Out_ float& resultY) noexcept + void ApplyStickDeadZone(float x, + float y, + GamePad::DeadZone deadZoneMode, + float maxValue, + float deadZoneSize, + _Out_ float& resultX, + _Out_ float& resultY) noexcept { switch (deadZoneMode) { @@ -60,17 +58,16 @@ namespace resultY = ApplyLinearDeadZone(y, maxValue, deadZoneSize); break; - case GamePad::DEAD_ZONE_CIRCULAR: - { - const float dist = sqrtf(x*x + y * y); - const float wanted = ApplyLinearDeadZone(dist, maxValue, deadZoneSize); + case GamePad::DEAD_ZONE_CIRCULAR: { + const float dist = sqrtf(x * x + y * y); + const float wanted = ApplyLinearDeadZone(dist, maxValue, deadZoneSize); - const float scale = (wanted > 0.f) ? (wanted / dist) : 0.f; + const float scale = (wanted > 0.f) ? (wanted / dist) : 0.f; - resultX = std::max(-1.f, std::min(x * scale, 1.f)); - resultY = std::max(-1.f, std::min(y * scale, 1.f)); - } - break; + resultX = std::max(-1.f, std::min(x * scale, 1.f)); + resultY = std::max(-1.f, std::min(y * scale, 1.f)); + } + break; default: // GamePad::DEAD_ZONE_NONE resultX = ApplyLinearDeadZone(x, maxValue, 0); @@ -78,8 +75,7 @@ namespace break; } } -} - +} // namespace #pragma region Implementations #ifdef USING_GAMEINPUT @@ -96,7 +92,7 @@ using namespace GameInput::v2; using namespace GameInput::v3; #endif -using GameInputCreateFn = HRESULT(*)(IGameInput**); +using GameInputCreateFn = HRESULT (*)(IGameInput**); #ifdef __clang__ #pragma clang diagnostic ignored "-Wmicrosoft-cast" @@ -105,11 +101,11 @@ using GameInputCreateFn = HRESULT(*)(IGameInput**); class GamePad::Impl { public: - Impl(GamePad* owner) : - mOwner(owner), - mCtrlChanged(INVALID_HANDLE_VALUE), - mDeviceToken(0), - mMostRecentGamepad(0) + Impl(GamePad* owner) + : mOwner(owner), + mCtrlChanged(INVALID_HANDLE_VALUE), + mDeviceToken(0), + mMostRecentGamepad(0) { if (s_gamePad) { @@ -118,15 +114,16 @@ class GamePad::Impl s_gamePad = this; - #if defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION) +#if defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION) HRESULT hr = GameInputCreate(mGameInput.GetAddressOf()); - #else +#else if (!s_gameInputCreate) { s_gameInputModule = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (s_gameInputModule) { - s_gameInputCreate = reinterpret_cast(reinterpret_cast(GetProcAddress(s_gameInputModule, "GameInputCreate"))); + s_gameInputCreate + = reinterpret_cast(reinterpret_cast(GetProcAddress(s_gameInputModule, "GameInputCreate"))); } if (!s_gameInputCreate) @@ -137,11 +134,10 @@ class GamePad::Impl } HRESULT hr = s_gameInputCreate(mGameInput.GetAddressOf()); - #endif +#endif if (SUCCEEDED(hr)) { - ThrowIfFailed(mGameInput->RegisterDeviceCallback( - nullptr, + ThrowIfFailed(mGameInput->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceConnected, GameInputBlockingEnumeration, @@ -152,21 +148,21 @@ class GamePad::Impl else { DebugTrace("ERROR: GameInputCreate [gamepad] failed with %08X\n", static_cast(hr)); - #ifdef _GAMING_XBOX +#ifdef _GAMING_XBOX throw com_exception(hr); - #else +#else DebugTrace( "\t**** Install the latest GameInputRedist package on this system. ****\n" "\t**** NOTE: All calls to GetState will be reported as 'not connected'. ****\n"); - #endif +#endif } } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() { @@ -174,11 +170,11 @@ class GamePad::Impl { if (mGameInput) { - #if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) +#if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) if (!mGameInput->UnregisterCallback(mDeviceToken)) - #else +#else if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) - #endif +#endif { DebugTrace("ERROR: GameInput::UnregisterCallback [gamepad] failed"); } @@ -226,37 +222,45 @@ class GamePad::Impl if (reading->GetGamepadState(&pad)) { state.connected = true; - #if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) +#if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) state.packet = reading->GetTimestamp(); - #else +#else state.packet = reading->GetSequenceNumber(GameInputKindGamepad); - #endif - - state.buttons.a = (pad.buttons & GameInputGamepadA) != 0; - state.buttons.b = (pad.buttons & GameInputGamepadB) != 0; - state.buttons.x = (pad.buttons & GameInputGamepadX) != 0; - state.buttons.y = (pad.buttons & GameInputGamepadY) != 0; - state.buttons.leftStick = (pad.buttons & GameInputGamepadLeftThumbstick) != 0; - state.buttons.rightStick = (pad.buttons & GameInputGamepadRightThumbstick) != 0; - state.buttons.leftShoulder = (pad.buttons & GameInputGamepadLeftShoulder) != 0; +#endif + + state.buttons.a = (pad.buttons & GameInputGamepadA) != 0; + state.buttons.b = (pad.buttons & GameInputGamepadB) != 0; + state.buttons.x = (pad.buttons & GameInputGamepadX) != 0; + state.buttons.y = (pad.buttons & GameInputGamepadY) != 0; + state.buttons.leftStick = (pad.buttons & GameInputGamepadLeftThumbstick) != 0; + state.buttons.rightStick = (pad.buttons & GameInputGamepadRightThumbstick) != 0; + state.buttons.leftShoulder = (pad.buttons & GameInputGamepadLeftShoulder) != 0; state.buttons.rightShoulder = (pad.buttons & GameInputGamepadRightShoulder) != 0; - state.buttons.view = (pad.buttons & GameInputGamepadView) != 0; - state.buttons.menu = (pad.buttons & GameInputGamepadMenu) != 0; + state.buttons.view = (pad.buttons & GameInputGamepadView) != 0; + state.buttons.menu = (pad.buttons & GameInputGamepadMenu) != 0; - state.dpad.up = (pad.buttons & GameInputGamepadDPadUp) != 0; - state.dpad.down = (pad.buttons & GameInputGamepadDPadDown) != 0; + state.dpad.up = (pad.buttons & GameInputGamepadDPadUp) != 0; + state.dpad.down = (pad.buttons & GameInputGamepadDPadDown) != 0; state.dpad.right = (pad.buttons & GameInputGamepadDPadRight) != 0; - state.dpad.left = (pad.buttons & GameInputGamepadDPadLeft) != 0; - - ApplyStickDeadZone(pad.leftThumbstickX, pad.leftThumbstickY, - deadZoneMode, 1.f, c_XboxOneThumbDeadZone, - state.thumbSticks.leftX, state.thumbSticks.leftY); - - ApplyStickDeadZone(pad.rightThumbstickX, pad.rightThumbstickY, - deadZoneMode, 1.f, c_XboxOneThumbDeadZone, - state.thumbSticks.rightX, state.thumbSticks.rightY); - - state.triggers.left = pad.leftTrigger; + state.dpad.left = (pad.buttons & GameInputGamepadDPadLeft) != 0; + + ApplyStickDeadZone(pad.leftThumbstickX, + pad.leftThumbstickY, + deadZoneMode, + 1.f, + c_XboxOneThumbDeadZone, + state.thumbSticks.leftX, + state.thumbSticks.leftY); + + ApplyStickDeadZone(pad.rightThumbstickX, + pad.rightThumbstickY, + deadZoneMode, + 1.f, + c_XboxOneThumbDeadZone, + state.thumbSticks.rightX, + state.thumbSticks.rightY); + + state.triggers.left = pad.leftTrigger; state.triggers.right = pad.rightTrigger; } } @@ -274,17 +278,17 @@ class GamePad::Impl { if (device->GetDeviceStatus() & GameInputDeviceConnected) { - #if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) +#if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) const GameInputDeviceInfo* deviceInfo = nullptr; device->GetDeviceInfo(&deviceInfo); - #else +#else auto deviceInfo = device->GetDeviceInfo(); - #endif - caps.connected = true; +#endif + caps.connected = true; caps.gamepadType = Capabilities::GAMEPAD; - caps.id = deviceInfo->deviceId; - caps.vid = deviceInfo->vendorId; - caps.pid = deviceInfo->productId; + caps.id = deviceInfo->deviceId; + caps.vid = deviceInfo->vendorId; + caps.pid = deviceInfo->productId; return; } else @@ -307,13 +311,7 @@ class GamePad::Impl IGameInputDevice* device = mInputDevices[player].Get(); if (device) { - GameInputRumbleParams const params = - { - leftMotor, - rightMotor, - leftTrigger, - rightTrigger - }; + GameInputRumbleParams const params = { leftMotor, rightMotor, leftTrigger, rightTrigger }; device->SetRumbleState(¶ms); return true; @@ -350,8 +348,7 @@ class GamePad::Impl } } - _Success_(return) - bool GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept + _Success_(return) bool GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept { if (!device) return false; @@ -375,34 +372,33 @@ class GamePad::Impl return false; } - GamePad* mOwner; + GamePad* mOwner; static GamePad::Impl* s_gamePad; HANDLE mCtrlChanged; private: - ComPtr mGameInput; - ComPtr mInputDevices[MAX_PLAYER_COUNT]; + ComPtr mGameInput; + ComPtr mInputDevices[MAX_PLAYER_COUNT]; - GameInputCallbackToken mDeviceToken; + GameInputCallbackToken mDeviceToken; int mMostRecentGamepad; - static void CALLBACK OnGameInputDevice( - _In_ GameInputCallbackToken, - _In_ void * context, - _In_ IGameInputDevice * device, - _In_ uint64_t, - _In_ GameInputDeviceStatus currentStatus, - _In_ GameInputDeviceStatus) noexcept + static void CALLBACK OnGameInputDevice(_In_ GameInputCallbackToken, + _In_ void* context, + _In_ IGameInputDevice* device, + _In_ uint64_t, + _In_ GameInputDeviceStatus currentStatus, + _In_ GameInputDeviceStatus) noexcept { auto impl = reinterpret_cast(context); if (currentStatus & GameInputDeviceConnected) { size_t empty = MAX_PLAYER_COUNT; - size_t k = 0; + size_t k = 0; for (; k < MAX_PLAYER_COUNT; ++k) { if (impl->mInputDevices[k].Get() == device) @@ -423,7 +419,7 @@ class GamePad::Impl if (empty < MAX_PLAYER_COUNT) { impl->mInputDevices[empty] = device; - impl->mMostRecentGamepad = static_cast(empty); + impl->mMostRecentGamepad = static_cast(empty); } } } @@ -446,7 +442,7 @@ class GamePad::Impl } #if !defined(_GAMING_XBOX) && !defined(GAMEINPUT_API_VERSION) - static HMODULE s_gameInputModule; + static HMODULE s_gameInputModule; static GameInputCreateFn s_gameInputCreate; #endif }; @@ -454,7 +450,7 @@ class GamePad::Impl GamePad::Impl* GamePad::Impl::s_gamePad = nullptr; #if !defined(_GAMING_XBOX) && !defined(GAMEINPUT_API_VERSION) -HMODULE GamePad::Impl::s_gameInputModule = nullptr; +HMODULE GamePad::Impl::s_gameInputModule = nullptr; GameInputCreateFn GamePad::Impl::s_gameInputCreate = nullptr; #endif @@ -463,13 +459,11 @@ void GamePad::RegisterEvents(HANDLE ctrlChanged) noexcept pImpl->mCtrlChanged = (!ctrlChanged) ? INVALID_HANDLE_VALUE : ctrlChanged; } -_Success_(return) -bool GamePad::GetDevice(int player, _Outptr_ GameInputDevice_t * *device) noexcept +_Success_(return) bool GamePad::GetDevice(int player, _Outptr_ GameInputDevice_t** device) noexcept { return pImpl->GetDevice(player, device); } - #elif defined(USING_WINDOWS_GAMING_INPUT) //====================================================================================== @@ -488,17 +482,17 @@ bool GamePad::GetDevice(int player, _Outptr_ GameInputDevice_t * *device) noexce class GamePad::Impl { public: - Impl(GamePad* owner) : - mOwner(owner), - mCtrlChanged(INVALID_HANDLE_VALUE), - mUserChanged(INVALID_HANDLE_VALUE), - mMostRecentGamepad(0), - mStatics{}, - mGamePad{}, - mUserChangeToken{}, - mAddedToken{}, - mRemovedToken{}, - mChanged{} + Impl(GamePad* owner) + : mOwner(owner), + mCtrlChanged(INVALID_HANDLE_VALUE), + mUserChanged(INVALID_HANDLE_VALUE), + mMostRecentGamepad(0), + mStatics{}, + mGamePad{}, + mUserChangeToken{}, + mAddedToken{}, + mRemovedToken{}, + mChanged{} { using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; @@ -528,11 +522,11 @@ class GamePad::Impl ScanGamePads(); } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() { @@ -543,10 +537,10 @@ class GamePad::Impl if (mGamePad[j]) { ComPtr ctrl; - HRESULT hr = mGamePad[j].As(&ctrl); + HRESULT hr = mGamePad[j].As(&ctrl); if (SUCCEEDED(hr) && ctrl) { - std::ignore = ctrl->remove_UserChanged(mUserChangeToken[j]); + std::ignore = ctrl->remove_UserChanged(mUserChangeToken[j]); mUserChangeToken[j].value = 0; } @@ -556,10 +550,10 @@ class GamePad::Impl if (mStatics) { - std::ignore = mStatics->remove_GamepadAdded(mAddedToken); + std::ignore = mStatics->remove_GamepadAdded(mAddedToken); mAddedToken.value = 0; - std::ignore = mStatics->remove_GamepadRemoved(mRemovedToken); + std::ignore = mStatics->remove_GamepadRemoved(mRemovedToken); mRemovedToken.value = 0; mStatics.Reset(); @@ -586,40 +580,48 @@ class GamePad::Impl if (mGamePad[player]) { GamepadReading reading; - HRESULT hr = mGamePad[player]->GetCurrentReading(&reading); + HRESULT hr = mGamePad[player]->GetCurrentReading(&reading); if (SUCCEEDED(hr)) { state.connected = true; - state.packet = reading.Timestamp; + state.packet = reading.Timestamp; state.buttons.a = (reading.Buttons & GamepadButtons::GamepadButtons_A) != 0; state.buttons.b = (reading.Buttons & GamepadButtons::GamepadButtons_B) != 0; state.buttons.x = (reading.Buttons & GamepadButtons::GamepadButtons_X) != 0; state.buttons.y = (reading.Buttons & GamepadButtons::GamepadButtons_Y) != 0; - state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0; + state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0; state.buttons.rightStick = (reading.Buttons & GamepadButtons::GamepadButtons_RightThumbstick) != 0; - state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0; + state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0; state.buttons.rightShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_RightShoulder) != 0; - state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0; + state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0; state.buttons.start = (reading.Buttons & GamepadButtons::GamepadButtons_Menu) != 0; - state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0; - state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0; + state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0; + state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0; state.dpad.right = (reading.Buttons & GamepadButtons::GamepadButtons_DPadRight) != 0; - state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0; - - ApplyStickDeadZone(static_cast(reading.LeftThumbstickX), static_cast(reading.LeftThumbstickY), - deadZoneMode, 1.f, c_XboxOneThumbDeadZone, - state.thumbSticks.leftX, state.thumbSticks.leftY); - - ApplyStickDeadZone(static_cast(reading.RightThumbstickX), static_cast(reading.RightThumbstickY), - deadZoneMode, 1.f, c_XboxOneThumbDeadZone, - state.thumbSticks.rightX, state.thumbSticks.rightY); - - state.triggers.left = static_cast(reading.LeftTrigger); + state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0; + + ApplyStickDeadZone(static_cast(reading.LeftThumbstickX), + static_cast(reading.LeftThumbstickY), + deadZoneMode, + 1.f, + c_XboxOneThumbDeadZone, + state.thumbSticks.leftX, + state.thumbSticks.leftY); + + ApplyStickDeadZone(static_cast(reading.RightThumbstickX), + static_cast(reading.RightThumbstickY), + deadZoneMode, + 1.f, + c_XboxOneThumbDeadZone, + state.thumbSticks.rightX, + state.thumbSticks.rightY); + + state.triggers.left = static_cast(reading.LeftTrigger); state.triggers.right = static_cast(reading.RightTrigger); return; @@ -650,13 +652,13 @@ class GamePad::Impl { if (mGamePad[player]) { - caps.connected = true; + caps.connected = true; caps.gamepadType = Capabilities::GAMEPAD; caps.id.clear(); caps.vid = caps.pid = 0; ComPtr ctrl; - HRESULT hr = mGamePad[player].As(&ctrl); + HRESULT hr = mGamePad[player].As(&ctrl); if (SUCCEEDED(hr) && ctrl) { ComPtr user; @@ -671,10 +673,11 @@ class GamePad::Impl } } - // Requires the Windows 10 Creators Update SDK (15063) - #if defined(NTDDI_WIN10_RS2) && (NTDDI_VERSION >= NTDDI_WIN10_RS2) +// Requires the Windows 10 Creators Update SDK (15063) +#if defined(NTDDI_WIN10_RS2) && (NTDDI_VERSION >= NTDDI_WIN10_RS2) ComPtr rawStatics; - hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_RawGameController).Get(), rawStatics.GetAddressOf()); + hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_RawGameController).Get(), + rawStatics.GetAddressOf()); if (SUCCEEDED(hr)) { ComPtr raw; @@ -688,7 +691,7 @@ class GamePad::Impl caps.pid = 0; } } - #endif // NTDDI_WIN10_RS2 +#endif // NTDDI_WIN10_RS2 } return; } @@ -710,11 +713,11 @@ class GamePad::Impl if (mGamePad[player]) { GamepadVibration vib; - vib.LeftMotor = double(leftMotor); - vib.RightMotor = double(rightMotor); - vib.LeftTrigger = double(leftTrigger); + vib.LeftMotor = double(leftMotor); + vib.RightMotor = double(rightMotor); + vib.LeftTrigger = double(leftTrigger); vib.RightTrigger = double(rightTrigger); - HRESULT hr = mGamePad[player]->put_Vibration(vib); + HRESULT hr = mGamePad[player]->put_Vibration(vib); if (SUCCEEDED(hr)) return true; @@ -738,7 +741,7 @@ class GamePad::Impl SetEvent(mChanged.get()); } - GamePad* mOwner; + GamePad* mOwner; static GamePad::Impl* s_gamePad; @@ -769,7 +772,7 @@ class GamePad::Impl for (; k < count; ++k) { ComPtr pad; - HRESULT hr = pads->GetAt(k, pad.GetAddressOf()); + HRESULT hr = pads->GetAt(k, pad.GetAddressOf()); if (SUCCEEDED(hr) && (pad == mGamePad[j])) { break; @@ -779,10 +782,10 @@ class GamePad::Impl if (k >= count) { ComPtr ctrl; - HRESULT hr = mGamePad[j].As(&ctrl); + HRESULT hr = mGamePad[j].As(&ctrl); if (SUCCEEDED(hr) && ctrl) { - std::ignore = ctrl->remove_UserChanged(mUserChangeToken[j]); + std::ignore = ctrl->remove_UserChanged(mUserChangeToken[j]); mUserChangeToken[j].value = 0; } @@ -795,11 +798,11 @@ class GamePad::Impl for (unsigned int j = 0; j < count; ++j) { ComPtr pad; - HRESULT hr = pads->GetAt(j, pad.GetAddressOf()); + HRESULT hr = pads->GetAt(j, pad.GetAddressOf()); if (SUCCEEDED(hr)) { size_t empty = MAX_PLAYER_COUNT; - size_t k = 0; + size_t k = 0; for (; k < MAX_PLAYER_COUNT; ++k) { if (mGamePad[k] == pad) @@ -828,7 +831,8 @@ class GamePad::Impl hr = pad.As(&ctrl); if (SUCCEEDED(hr) && ctrl) { - typedef __FITypedEventHandler_2_Windows__CGaming__CInput__CIGameController_Windows__CSystem__CUserChangedEventArgs UserHandler; + typedef __FITypedEventHandler_2_Windows__CGaming__CInput__CIGameController_Windows__CSystem__CUserChangedEventArgs + UserHandler; ThrowIfFailed(ctrl->add_UserChanged(Callback(UserChanged).Get(), &mUserChangeToken[empty])); } } @@ -838,15 +842,15 @@ class GamePad::Impl } ComPtr mStatics; - ComPtr mGamePad[MAX_PLAYER_COUNT]; - EventRegistrationToken mUserChangeToken[MAX_PLAYER_COUNT]; + ComPtr mGamePad[MAX_PLAYER_COUNT]; + EventRegistrationToken mUserChangeToken[MAX_PLAYER_COUNT]; EventRegistrationToken mAddedToken; EventRegistrationToken mRemovedToken; ScopedHandle mChanged; - static HRESULT GamepadAdded(IInspectable *, ABI::Windows::Gaming::Input::IGamepad*) + static HRESULT GamepadAdded(IInspectable*, ABI::Windows::Gaming::Input::IGamepad*) { if (s_gamePad) { @@ -860,7 +864,7 @@ class GamePad::Impl return S_OK; } - static HRESULT GamepadRemoved(IInspectable *, ABI::Windows::Gaming::Input::IGamepad*) + static HRESULT GamepadRemoved(IInspectable*, ABI::Windows::Gaming::Input::IGamepad*) { if (s_gamePad) { @@ -895,7 +899,6 @@ void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept pImpl->mUserChanged = (!userChanged) ? INVALID_HANDLE_VALUE : userChanged; } - #elif defined(_XBOX_ONE) //====================================================================================== @@ -910,13 +913,15 @@ class GamePad::Impl { public: class GamepadAddedListener : public Microsoft::WRL::RuntimeClass, - ABI::Windows::Foundation::IEventHandler, - Microsoft::WRL::FtmBase> + ABI::Windows::Foundation::IEventHandler, + Microsoft::WRL::FtmBase> { public: - GamepadAddedListener(HANDLE event) : mEvent(event) {} + GamepadAddedListener(HANDLE event) + : mEvent(event) + {} - STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IGamepadAddedEventArgs *) override + STDMETHOD(Invoke)(_In_ IInspectable*, _In_ ABI::Windows::Xbox::Input::IGamepadAddedEventArgs*) override { SetEvent(mEvent); @@ -934,13 +939,15 @@ class GamePad::Impl }; class GamepadRemovedListener : public Microsoft::WRL::RuntimeClass, - ABI::Windows::Foundation::IEventHandler, - Microsoft::WRL::FtmBase> + ABI::Windows::Foundation::IEventHandler, + Microsoft::WRL::FtmBase> { public: - GamepadRemovedListener(HANDLE event) : mEvent(event) {} + GamepadRemovedListener(HANDLE event) + : mEvent(event) + {} - STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IGamepadRemovedEventArgs *) override + STDMETHOD(Invoke)(_In_ IInspectable*, _In_ ABI::Windows::Xbox::Input::IGamepadRemovedEventArgs*) override { SetEvent(mEvent); @@ -958,13 +965,13 @@ class GamePad::Impl }; class UserPairingListener : public Microsoft::WRL::RuntimeClass, - ABI::Windows::Foundation::IEventHandler, - Microsoft::WRL::FtmBase> + ABI::Windows::Foundation::IEventHandler, + Microsoft::WRL::FtmBase> { public: UserPairingListener() noexcept {} - STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IControllerPairingChangedEventArgs *) override + STDMETHOD(Invoke)(_In_ IInspectable*, _In_ ABI::Windows::Xbox::Input::IControllerPairingChangedEventArgs*) override { auto pad = GamePad::Impl::s_gamePad; @@ -976,18 +983,18 @@ class GamePad::Impl } }; - Impl(GamePad *owner) : - mOwner(owner), - mCtrlChanged(INVALID_HANDLE_VALUE), - mUserChanged(INVALID_HANDLE_VALUE), - mMostRecentGamepad(0), - mStatics{}, - mStaticsCtrl{}, - mGamePad{}, - mAddedToken{}, - mRemovedToken{}, - mUserParingToken{}, - mChanged{} + Impl(GamePad* owner) + : mOwner(owner), + mCtrlChanged(INVALID_HANDLE_VALUE), + mUserChanged(INVALID_HANDLE_VALUE), + mMostRecentGamepad(0), + mStatics{}, + mStaticsCtrl{}, + mGamePad{}, + mAddedToken{}, + mRemovedToken{}, + mUserParingToken{}, + mChanged{} { using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; @@ -1008,7 +1015,8 @@ class GamePad::Impl ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Gamepad).Get(), mStatics.GetAddressOf())); - ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Controller).Get(), mStaticsCtrl.GetAddressOf())); + ThrowIfFailed( + GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Controller).Get(), mStaticsCtrl.GetAddressOf())); ThrowIfFailed(mStatics->add_GamepadAdded(Make(mChanged.get()).Get(), &mAddedToken)); @@ -1023,10 +1031,10 @@ class GamePad::Impl { if (mStatics) { - std::ignore = mStatics->remove_GamepadAdded(mAddedToken); + std::ignore = mStatics->remove_GamepadAdded(mAddedToken); mAddedToken.value = 0; - std::ignore = mStatics->remove_GamepadRemoved(mRemovedToken); + std::ignore = mStatics->remove_GamepadRemoved(mRemovedToken); mRemovedToken.value = 0; mStatics.Reset(); @@ -1034,7 +1042,7 @@ class GamePad::Impl if (mStaticsCtrl) { - std::ignore = mStaticsCtrl->remove_ControllerPairingChanged(mUserParingToken); + std::ignore = mStaticsCtrl->remove_ControllerPairingChanged(mUserParingToken); mUserParingToken.value = 0; mStaticsCtrl.Reset(); @@ -1061,40 +1069,48 @@ class GamePad::Impl if (mGamePad[player]) { RawGamepadReading reading; - HRESULT hr = mGamePad[player]->GetRawCurrentReading(&reading); + HRESULT hr = mGamePad[player]->GetRawCurrentReading(&reading); if (SUCCEEDED(hr)) { state.connected = true; - state.packet = reading.Timestamp; + state.packet = reading.Timestamp; state.buttons.a = (reading.Buttons & GamepadButtons::GamepadButtons_A) != 0; state.buttons.b = (reading.Buttons & GamepadButtons::GamepadButtons_B) != 0; state.buttons.x = (reading.Buttons & GamepadButtons::GamepadButtons_X) != 0; state.buttons.y = (reading.Buttons & GamepadButtons::GamepadButtons_Y) != 0; - state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0; + state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0; state.buttons.rightStick = (reading.Buttons & GamepadButtons::GamepadButtons_RightThumbstick) != 0; - state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0; + state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0; state.buttons.rightShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_RightShoulder) != 0; - state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0; + state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0; state.buttons.start = (reading.Buttons & GamepadButtons::GamepadButtons_Menu) != 0; - state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0; - state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0; + state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0; + state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0; state.dpad.right = (reading.Buttons & GamepadButtons::GamepadButtons_DPadRight) != 0; - state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0; - - ApplyStickDeadZone(reading.LeftThumbstickX, reading.LeftThumbstickY, - deadZoneMode, 1.f, c_XboxOneThumbDeadZone, - state.thumbSticks.leftX, state.thumbSticks.leftY); - - ApplyStickDeadZone(reading.RightThumbstickX, reading.RightThumbstickY, - deadZoneMode, 1.f, c_XboxOneThumbDeadZone, - state.thumbSticks.rightX, state.thumbSticks.rightY); - - state.triggers.left = reading.LeftTrigger; + state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0; + + ApplyStickDeadZone(reading.LeftThumbstickX, + reading.LeftThumbstickY, + deadZoneMode, + 1.f, + c_XboxOneThumbDeadZone, + state.thumbSticks.leftX, + state.thumbSticks.leftY); + + ApplyStickDeadZone(reading.RightThumbstickX, + reading.RightThumbstickY, + deadZoneMode, + 1.f, + c_XboxOneThumbDeadZone, + state.thumbSticks.rightX, + state.thumbSticks.rightY); + + state.triggers.left = reading.LeftTrigger; state.triggers.right = reading.RightTrigger; return; @@ -1122,13 +1138,13 @@ class GamePad::Impl { if (mGamePad[player]) { - caps.connected = true; + caps.connected = true; caps.gamepadType = Capabilities::UNKNOWN; - caps.id = 0; + caps.id = 0; caps.vid = caps.pid = 0; ComPtr ctrl; - HRESULT hr = mGamePad[player].As(&ctrl); + HRESULT hr = mGamePad[player].As(&ctrl); if (SUCCEEDED(hr) && ctrl) { hr = ctrl->get_Id(&caps.id); @@ -1188,11 +1204,11 @@ class GamePad::Impl try { GamepadVibration vib; - vib.LeftMotorLevel = leftMotor; - vib.RightMotorLevel = rightMotor; - vib.LeftTriggerLevel = leftTrigger; + vib.LeftMotorLevel = leftMotor; + vib.RightMotorLevel = rightMotor; + vib.LeftTriggerLevel = leftTrigger; vib.RightTriggerLevel = rightTrigger; - hr = mGamePad[player]->SetVibration(vib); + hr = mGamePad[player]->SetVibration(vib); } catch (...) { @@ -1222,7 +1238,7 @@ class GamePad::Impl SetEvent(mChanged.get()); } - GamePad* mOwner; + GamePad* mOwner; static GamePad::Impl* s_gamePad; @@ -1252,7 +1268,7 @@ class GamePad::Impl for (; k < count; ++k) { ComPtr pad; - HRESULT hr = pads->GetAt(k, pad.GetAddressOf()); + HRESULT hr = pads->GetAt(k, pad.GetAddressOf()); if (SUCCEEDED(hr) && (pad == mGamePad[j])) { break; @@ -1270,11 +1286,11 @@ class GamePad::Impl for (unsigned int j = 0; j < count; ++j) { ComPtr pad; - HRESULT hr = pads->GetAt(j, pad.GetAddressOf()); + HRESULT hr = pads->GetAt(j, pad.GetAddressOf()); if (SUCCEEDED(hr)) { size_t empty = MAX_PLAYER_COUNT; - size_t k = 0; + size_t k = 0; for (; k < MAX_PLAYER_COUNT; ++k) { if (mGamePad[k] == pad) @@ -1305,9 +1321,9 @@ class GamePad::Impl } } - ComPtr mStatics; + ComPtr mStatics; ComPtr mStaticsCtrl; - ComPtr mGamePad[MAX_PLAYER_COUNT]; + ComPtr mGamePad[MAX_PLAYER_COUNT]; EventRegistrationToken mAddedToken; EventRegistrationToken mRemovedToken; @@ -1324,7 +1340,6 @@ void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept pImpl->mUserChanged = (!userChanged) ? INVALID_HANDLE_VALUE : userChanged; } - #elif defined(USING_XINPUT) //====================================================================================== @@ -1338,10 +1353,10 @@ static_assert(GamePad::MAX_PLAYER_COUNT == XUSER_MAX_COUNT, "xinput.h mismatch") class GamePad::Impl { public: - Impl(GamePad* owner) : - mOwner(owner), - mConnected{}, - mLastReadTime{} + Impl(GamePad* owner) + : mOwner(owner), + mConnected{}, + mLastReadTime{} { for (int j = 0; j < XUSER_MAX_COUNT; ++j) { @@ -1356,10 +1371,7 @@ class GamePad::Impl s_gamePad = this; } - ~Impl() - { - s_gamePad = nullptr; - } + ~Impl() { s_gamePad = nullptr; } void GetState(int player, _Out_ State& state, DeadZone deadZoneMode) { @@ -1371,7 +1383,7 @@ class GamePad::Impl if (!ThrottleRetry(player, time)) { XINPUT_STATE xstate; - const DWORD result = XInputGetState(DWORD(player), &xstate); + const DWORD result = XInputGetState(DWORD(player), &xstate); if (result == ERROR_DEVICE_NOT_CONNECTED) { ClearSlot(player, time); @@ -1384,43 +1396,53 @@ class GamePad::Impl mConnected[player] = true; state.connected = true; - state.packet = xstate.dwPacketNumber; - - const WORD xbuttons = xstate.Gamepad.wButtons; - state.buttons.a = (xbuttons & XINPUT_GAMEPAD_A) != 0; - state.buttons.b = (xbuttons & XINPUT_GAMEPAD_B) != 0; - state.buttons.x = (xbuttons & XINPUT_GAMEPAD_X) != 0; - state.buttons.y = (xbuttons & XINPUT_GAMEPAD_Y) != 0; - state.buttons.leftStick = (xbuttons & XINPUT_GAMEPAD_LEFT_THUMB) != 0; - state.buttons.rightStick = (xbuttons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0; - state.buttons.leftShoulder = (xbuttons & XINPUT_GAMEPAD_LEFT_SHOULDER) != 0; + state.packet = xstate.dwPacketNumber; + + const WORD xbuttons = xstate.Gamepad.wButtons; + state.buttons.a = (xbuttons & XINPUT_GAMEPAD_A) != 0; + state.buttons.b = (xbuttons & XINPUT_GAMEPAD_B) != 0; + state.buttons.x = (xbuttons & XINPUT_GAMEPAD_X) != 0; + state.buttons.y = (xbuttons & XINPUT_GAMEPAD_Y) != 0; + state.buttons.leftStick = (xbuttons & XINPUT_GAMEPAD_LEFT_THUMB) != 0; + state.buttons.rightStick = (xbuttons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0; + state.buttons.leftShoulder = (xbuttons & XINPUT_GAMEPAD_LEFT_SHOULDER) != 0; state.buttons.rightShoulder = (xbuttons & XINPUT_GAMEPAD_RIGHT_SHOULDER) != 0; - state.buttons.back = (xbuttons & XINPUT_GAMEPAD_BACK) != 0; - state.buttons.start = (xbuttons & XINPUT_GAMEPAD_START) != 0; + state.buttons.back = (xbuttons & XINPUT_GAMEPAD_BACK) != 0; + state.buttons.start = (xbuttons & XINPUT_GAMEPAD_START) != 0; - state.dpad.up = (xbuttons & XINPUT_GAMEPAD_DPAD_UP) != 0; - state.dpad.down = (xbuttons & XINPUT_GAMEPAD_DPAD_DOWN) != 0; + state.dpad.up = (xbuttons & XINPUT_GAMEPAD_DPAD_UP) != 0; + state.dpad.down = (xbuttons & XINPUT_GAMEPAD_DPAD_DOWN) != 0; state.dpad.right = (xbuttons & XINPUT_GAMEPAD_DPAD_RIGHT) != 0; - state.dpad.left = (xbuttons & XINPUT_GAMEPAD_DPAD_LEFT) != 0; + state.dpad.left = (xbuttons & XINPUT_GAMEPAD_DPAD_LEFT) != 0; if (deadZoneMode == DEAD_ZONE_NONE) { - state.triggers.left = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, 0.f); + state.triggers.left = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, 0.f); state.triggers.right = ApplyLinearDeadZone(float(xstate.Gamepad.bRightTrigger), 255.f, 0.f); } else { - state.triggers.left = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD)); - state.triggers.right = ApplyLinearDeadZone(float(xstate.Gamepad.bRightTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD)); + state.triggers.left + = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD)); + state.triggers.right + = ApplyLinearDeadZone(float(xstate.Gamepad.bRightTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD)); } - ApplyStickDeadZone(float(xstate.Gamepad.sThumbLX), float(xstate.Gamepad.sThumbLY), - deadZoneMode, 32767.f, float(XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE), - state.thumbSticks.leftX, state.thumbSticks.leftY); - - ApplyStickDeadZone(float(xstate.Gamepad.sThumbRX), float(xstate.Gamepad.sThumbRY), - deadZoneMode, 32767.f, float(XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE), - state.thumbSticks.rightX, state.thumbSticks.rightY); + ApplyStickDeadZone(float(xstate.Gamepad.sThumbLX), + float(xstate.Gamepad.sThumbLY), + deadZoneMode, + 32767.f, + float(XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE), + state.thumbSticks.leftX, + state.thumbSticks.leftY); + + ApplyStickDeadZone(float(xstate.Gamepad.sThumbRX), + float(xstate.Gamepad.sThumbRY), + deadZoneMode, + 32767.f, + float(XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE), + state.thumbSticks.rightX, + state.thumbSticks.rightY); return; } @@ -1439,7 +1461,7 @@ class GamePad::Impl if (!ThrottleRetry(player, time)) { XINPUT_CAPABILITIES xcaps; - const DWORD result = XInputGetCapabilities(DWORD(player), 0, &xcaps); + const DWORD result = XInputGetCapabilities(DWORD(player), 0, &xcaps); if (result == ERROR_DEVICE_NOT_CONNECTED) { ClearSlot(player, time); @@ -1452,15 +1474,15 @@ class GamePad::Impl mConnected[player] = true; caps.connected = true; - caps.id = uint64_t(player); + caps.id = uint64_t(player); if (xcaps.Type == XINPUT_DEVTYPE_GAMEPAD) { static_assert(Capabilities::GAMEPAD == XINPUT_DEVSUBTYPE_GAMEPAD, "xinput.h mismatch"); static_assert(XINPUT_DEVSUBTYPE_WHEEL == Capabilities::WHEEL, "xinput.h mismatch"); static_assert(XINPUT_DEVSUBTYPE_ARCADE_STICK == Capabilities::ARCADE_STICK, "xinput.h mismatch"); - #ifndef __MINGW32__ +#ifndef __MINGW32__ static_assert(XINPUT_DEVSUBTYPE_FLIGHT_STICK == Capabilities::FLIGHT_STICK, "xinput.h mismatch"); - #endif +#endif static_assert(XINPUT_DEVSUBTYPE_DANCE_PAD == Capabilities::DANCE_PAD, "xinput.h mismatch"); static_assert(XINPUT_DEVSUBTYPE_GUITAR == Capabilities::GUITAR, "xinput.h mismatch"); static_assert(XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE == Capabilities::GUITAR_ALTERNATE, "xinput.h mismatch"); @@ -1499,9 +1521,9 @@ class GamePad::Impl UNREFERENCED_PARAMETER(rightTrigger); XINPUT_VIBRATION xvibration; - xvibration.wLeftMotorSpeed = WORD(leftMotor * 0xFFFF); + xvibration.wLeftMotorSpeed = WORD(leftMotor * 0xFFFF); xvibration.wRightMotorSpeed = WORD(rightMotor * 0xFFFF); - const DWORD result = XInputSetState(DWORD(player), &xvibration); + const DWORD result = XInputSetState(DWORD(player), &xvibration); if (result == ERROR_DEVICE_NOT_CONNECTED) { ClearSlot(player, time); @@ -1519,29 +1541,29 @@ class GamePad::Impl void Suspend() noexcept { - #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) // XInput focus is handled automatically on Windows 10 - #else +#else XInputEnable(FALSE); - #endif +#endif } void Resume() noexcept { - #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) // XInput focus is handled automatically on Windows 10 - #else +#else XInputEnable(TRUE); - #endif +#endif } - GamePad* mOwner; + GamePad* mOwner; static GamePad::Impl* s_gamePad; private: - bool mConnected[XUSER_MAX_COUNT]; - ULONGLONG mLastReadTime[XUSER_MAX_COUNT]; + bool mConnected[XUSER_MAX_COUNT]; + ULONGLONG mLastReadTime[XUSER_MAX_COUNT]; bool ThrottleRetry(int player, ULONGLONG time) { @@ -1575,20 +1597,20 @@ class GamePad::Impl void ClearSlot(int player, ULONGLONG time) { - mConnected[player] = false; + mConnected[player] = false; mLastReadTime[player] = time; } int GetMostRecent() { - int player = -1; - ULONGLONG time = 0; + int player = -1; + ULONGLONG time = 0; for (size_t j = 0; j < XUSER_MAX_COUNT; ++j) { if (mConnected[j] && (mLastReadTime[j] > time)) { - time = mLastReadTime[j]; + time = mLastReadTime[j]; player = static_cast(j); } } @@ -1607,7 +1629,7 @@ GamePad::Impl* GamePad::Impl::s_gamePad = nullptr; #pragma endregion #ifdef _MSC_VER -#pragma warning( disable : 4355 ) +#pragma warning(disable : 4355) #endif // Public constructor. @@ -1615,7 +1637,6 @@ GamePad::GamePad() noexcept(false) : pImpl(std::make_unique(this)) {} - // Move constructor. GamePad::GamePad(GamePad&& moveFrom) noexcept : pImpl(std::move(moveFrom.pImpl)) @@ -1623,20 +1644,17 @@ GamePad::GamePad(GamePad&& moveFrom) noexcept pImpl->mOwner = this; } - // Move assignment. -GamePad& GamePad::operator= (GamePad&& moveFrom) noexcept +GamePad& GamePad::operator=(GamePad&& moveFrom) noexcept { - pImpl = std::move(moveFrom.pImpl); + pImpl = std::move(moveFrom.pImpl); pImpl->mOwner = this; return *this; } - // Public destructor. GamePad::~GamePad() = default; - GamePad::State GamePad::GetState(int player, DeadZone deadZoneMode) { State state; @@ -1644,7 +1662,6 @@ GamePad::State GamePad::GetState(int player, DeadZone deadZoneMode) return state; } - GamePad::Capabilities GamePad::GetCapabilities(int player) { Capabilities caps; @@ -1652,25 +1669,21 @@ GamePad::Capabilities GamePad::GetCapabilities(int player) return caps; } - bool GamePad::SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger) noexcept { return pImpl->SetVibration(player, leftMotor, rightMotor, leftTrigger, rightTrigger); } - void GamePad::Suspend() noexcept { pImpl->Suspend(); } - void GamePad::Resume() noexcept { pImpl->Resume(); } - GamePad& GamePad::Get() { if (!Impl::s_gamePad || !Impl::s_gamePad->mOwner) @@ -1679,13 +1692,12 @@ GamePad& GamePad::Get() return *Impl::s_gamePad->mOwner; } - - //====================================================================================== // ButtonStateTracker //====================================================================================== -#define UPDATE_BUTTON_STATE(field) field = static_cast( ( !!state.buttons.field ) | ( ( !!state.buttons.field ^ !!lastState.buttons.field ) << 1 ) ) +#define UPDATE_BUTTON_STATE(field) \ + field = static_cast((!!state.buttons.field) | ((!!state.buttons.field ^ !!lastState.buttons.field) << 1)) void GamePad::ButtonStateTracker::Update(const GamePad::State& state) noexcept { @@ -1709,9 +1721,9 @@ void GamePad::ButtonStateTracker::Update(const GamePad::State& state) noexcept UPDATE_BUTTON_STATE(back); UPDATE_BUTTON_STATE(start); - dpadUp = static_cast((!!state.dpad.up) | ((!!state.dpad.up ^ !!lastState.dpad.up) << 1)); - dpadDown = static_cast((!!state.dpad.down) | ((!!state.dpad.down ^ !!lastState.dpad.down) << 1)); - dpadLeft = static_cast((!!state.dpad.left) | ((!!state.dpad.left ^ !!lastState.dpad.left) << 1)); + dpadUp = static_cast((!!state.dpad.up) | ((!!state.dpad.up ^ !!lastState.dpad.up) << 1)); + dpadDown = static_cast((!!state.dpad.down) | ((!!state.dpad.down ^ !!lastState.dpad.down) << 1)); + dpadLeft = static_cast((!!state.dpad.left) | ((!!state.dpad.left ^ !!lastState.dpad.left) << 1)); dpadRight = static_cast((!!state.dpad.right) | ((!!state.dpad.right ^ !!lastState.dpad.right) << 1)); assert((!state.dpad.up && !lastState.dpad.up) == (dpadUp == UP)); @@ -1722,33 +1734,33 @@ void GamePad::ButtonStateTracker::Update(const GamePad::State& state) noexcept // Handle 'threshold' tests which emulate buttons bool threshold = state.IsLeftThumbStickUp(); - leftStickUp = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickUp()) << 1)); + leftStickUp = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickUp()) << 1)); - threshold = state.IsLeftThumbStickDown(); + threshold = state.IsLeftThumbStickDown(); leftStickDown = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickDown()) << 1)); - threshold = state.IsLeftThumbStickLeft(); + threshold = state.IsLeftThumbStickLeft(); leftStickLeft = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickLeft()) << 1)); - threshold = state.IsLeftThumbStickRight(); + threshold = state.IsLeftThumbStickRight(); leftStickRight = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickRight()) << 1)); - threshold = state.IsRightThumbStickUp(); + threshold = state.IsRightThumbStickUp(); rightStickUp = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickUp()) << 1)); - threshold = state.IsRightThumbStickDown(); + threshold = state.IsRightThumbStickDown(); rightStickDown = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickDown()) << 1)); - threshold = state.IsRightThumbStickLeft(); + threshold = state.IsRightThumbStickLeft(); rightStickLeft = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickLeft()) << 1)); - threshold = state.IsRightThumbStickRight(); + threshold = state.IsRightThumbStickRight(); rightStickRight = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickRight()) << 1)); - threshold = state.IsLeftTriggerPressed(); + threshold = state.IsLeftTriggerPressed(); leftTrigger = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsLeftTriggerPressed()) << 1)); - threshold = state.IsRightTriggerPressed(); + threshold = state.IsRightTriggerPressed(); rightTrigger = static_cast((!!threshold) | ((!!threshold ^ !!lastState.IsRightTriggerPressed()) << 1)); lastState = state; @@ -1756,7 +1768,6 @@ void GamePad::ButtonStateTracker::Update(const GamePad::State& state) noexcept #undef UPDATE_BUTTON_STATE - void GamePad::ButtonStateTracker::Reset() noexcept { memset(this, 0, sizeof(ButtonStateTracker)); diff --git a/Src/GeometricPrimitive.cpp b/Src/GeometricPrimitive.cpp index 5223184e..f52a96ba 100644 --- a/Src/GeometricPrimitive.cpp +++ b/Src/GeometricPrimitive.cpp @@ -25,44 +25,41 @@ using Microsoft::WRL::ComPtr; class GeometricPrimitive::Impl { public: - Impl() noexcept : mIndexCount(0), mVertexBufferView{}, mIndexBufferView{} {} + Impl() noexcept + : mIndexCount(0), + mVertexBufferView{}, + mIndexBufferView{} + {} - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; void Initialize(const VertexCollection& vertices, const IndexCollection& indices, _In_opt_ ID3D12Device* device); - void LoadStaticBuffers( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch); + void LoadStaticBuffers(_In_ ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch); - void Transition( - _In_ ID3D12GraphicsCommandList* commandList, - D3D12_RESOURCE_STATES stateBeforeVB, - D3D12_RESOURCE_STATES stateAfterVB, - D3D12_RESOURCE_STATES stateBeforeIB, - D3D12_RESOURCE_STATES stateAfterIB); + void Transition(_In_ ID3D12GraphicsCommandList* commandList, + D3D12_RESOURCE_STATES stateBeforeVB, + D3D12_RESOURCE_STATES stateAfterVB, + D3D12_RESOURCE_STATES stateBeforeIB, + D3D12_RESOURCE_STATES stateAfterIB); void DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation) const; - UINT mIndexCount; - SharedGraphicsResource mIndexBuffer; - SharedGraphicsResource mVertexBuffer; - ComPtr mStaticIndexBuffer; - ComPtr mStaticVertexBuffer; - D3D12_VERTEX_BUFFER_VIEW mVertexBufferView; - D3D12_INDEX_BUFFER_VIEW mIndexBufferView; + UINT mIndexCount; + SharedGraphicsResource mIndexBuffer; + SharedGraphicsResource mVertexBuffer; + ComPtr mStaticIndexBuffer; + ComPtr mStaticVertexBuffer; + D3D12_VERTEX_BUFFER_VIEW mVertexBufferView; + D3D12_INDEX_BUFFER_VIEW mIndexBufferView; }; - // Initializes a geometric primitive instance that will draw the specified vertex and index data. -void GeometricPrimitive::Impl::Initialize( - const VertexCollection& vertices, - const IndexCollection& indices, - _In_opt_ ID3D12Device* device) +void GeometricPrimitive::Impl::Initialize(const VertexCollection& vertices, const IndexCollection& indices, _In_opt_ ID3D12Device* device) { if (vertices.size() >= USHRT_MAX) throw std::invalid_argument("Too many vertices for 16-bit index buffer"); @@ -99,20 +96,16 @@ void GeometricPrimitive::Impl::Initialize( // Create views mVertexBufferView.BufferLocation = mVertexBuffer.GpuAddress(); - mVertexBufferView.StrideInBytes = static_cast(sizeof(VertexCollection::value_type)); - mVertexBufferView.SizeInBytes = static_cast(mVertexBuffer.Size()); + mVertexBufferView.StrideInBytes = static_cast(sizeof(VertexCollection::value_type)); + mVertexBufferView.SizeInBytes = static_cast(mVertexBuffer.Size()); mIndexBufferView.BufferLocation = mIndexBuffer.GpuAddress(); - mIndexBufferView.SizeInBytes = static_cast(mIndexBuffer.Size()); - mIndexBufferView.Format = DXGI_FORMAT_R16_UINT; + mIndexBufferView.SizeInBytes = static_cast(mIndexBuffer.Size()); + mIndexBufferView.Format = DXGI_FORMAT_R16_UINT; } - // Load VB/IB resources for static geometry. -_Use_decl_annotations_ -void GeometricPrimitive::Impl::LoadStaticBuffers( - ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch) +_Use_decl_annotations_ void GeometricPrimitive::Impl::LoadStaticBuffers(ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -126,21 +119,20 @@ void GeometricPrimitive::Impl::LoadStaticBuffers( const auto desc = CD3DX12_RESOURCE_DESC::Buffer(mVertexBuffer.Size()); - ThrowIfFailed(device->CreateCommittedResource( - &heapProperties, + ThrowIfFailed(device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, nullptr, - IID_GRAPHICS_PPV_ARGS(mStaticVertexBuffer.GetAddressOf()) - )); + IID_GRAPHICS_PPV_ARGS(mStaticVertexBuffer.GetAddressOf()))); SetDebugObjectName(mStaticVertexBuffer.Get(), L"GeometricPrimitive"); resourceUploadBatch.Upload(mStaticVertexBuffer.Get(), mVertexBuffer); resourceUploadBatch.Transition(mStaticVertexBuffer.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); // Update view mVertexBufferView.BufferLocation = mStaticVertexBuffer->GetGPUVirtualAddress(); @@ -155,21 +147,18 @@ void GeometricPrimitive::Impl::LoadStaticBuffers( const auto desc = CD3DX12_RESOURCE_DESC::Buffer(mIndexBuffer.Size()); - ThrowIfFailed(device->CreateCommittedResource( - &heapProperties, + ThrowIfFailed(device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, nullptr, - IID_GRAPHICS_PPV_ARGS(mStaticIndexBuffer.GetAddressOf()) - )); + IID_GRAPHICS_PPV_ARGS(mStaticIndexBuffer.GetAddressOf()))); SetDebugObjectName(mStaticIndexBuffer.Get(), L"GeometricPrimitive"); resourceUploadBatch.Upload(mStaticIndexBuffer.Get(), mIndexBuffer); - resourceUploadBatch.Transition(mStaticIndexBuffer.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER); + resourceUploadBatch.Transition(mStaticIndexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER); // Update view mIndexBufferView.BufferLocation = mStaticIndexBuffer->GetGPUVirtualAddress(); @@ -178,15 +167,12 @@ void GeometricPrimitive::Impl::LoadStaticBuffers( } } - // Transition VB/IB resources for static geometry. -_Use_decl_annotations_ -void GeometricPrimitive::Impl::Transition( - ID3D12GraphicsCommandList* commandList, - D3D12_RESOURCE_STATES stateBeforeVB, - D3D12_RESOURCE_STATES stateAfterVB, - D3D12_RESOURCE_STATES stateBeforeIB, - D3D12_RESOURCE_STATES stateAfterIB) +_Use_decl_annotations_ void GeometricPrimitive::Impl::Transition(ID3D12GraphicsCommandList* commandList, + D3D12_RESOURCE_STATES stateBeforeVB, + D3D12_RESOURCE_STATES stateAfterVB, + D3D12_RESOURCE_STATES stateBeforeIB, + D3D12_RESOURCE_STATES stateAfterIB) { UINT start = 0; UINT count = 0; @@ -194,13 +180,13 @@ void GeometricPrimitive::Impl::Transition( D3D12_RESOURCE_BARRIER barrier[2] = {}; barrier[0].Type = barrier[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier[0].Transition.Subresource = barrier[1].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier[0].Transition.pResource = mStaticIndexBuffer.Get(); - barrier[0].Transition.StateBefore = stateBeforeIB; - barrier[0].Transition.StateAfter = stateAfterIB; + barrier[0].Transition.pResource = mStaticIndexBuffer.Get(); + barrier[0].Transition.StateBefore = stateBeforeIB; + barrier[0].Transition.StateAfter = stateAfterIB; - barrier[1].Transition.pResource = mStaticVertexBuffer.Get(); + barrier[1].Transition.pResource = mStaticVertexBuffer.Get(); barrier[1].Transition.StateBefore = stateBeforeVB; - barrier[1].Transition.StateAfter = stateAfterVB; + barrier[1].Transition.StateAfter = stateAfterVB; if (stateBeforeIB == stateAfterIB || !mStaticIndexBuffer) { @@ -222,10 +208,10 @@ void GeometricPrimitive::Impl::Transition( } } - // Draws the primitive. -_Use_decl_annotations_ -void GeometricPrimitive::Impl::DrawInstanced(ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation) const +_Use_decl_annotations_ void GeometricPrimitive::Impl::DrawInstanced(ID3D12GraphicsCommandList* commandList, + uint32_t instanceCount, + uint32_t startInstanceLocation) const { commandList->IASetVertexBuffers(0, 1, &mVertexBufferView); commandList->IASetIndexBuffer(&mIndexBufferView); @@ -243,58 +229,44 @@ GeometricPrimitive::GeometricPrimitive() noexcept(false) : pImpl(std::make_unique()) {} - // Destructor. -GeometricPrimitive::~GeometricPrimitive() -{} - +GeometricPrimitive::~GeometricPrimitive() {} // Public entrypoints. -_Use_decl_annotations_ -void GeometricPrimitive::LoadStaticBuffers(ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch) +_Use_decl_annotations_ void GeometricPrimitive::LoadStaticBuffers(ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch) { pImpl->LoadStaticBuffers(device, resourceUploadBatch); } - -void GeometricPrimitive::Transition( - _In_ ID3D12GraphicsCommandList* commandList, - D3D12_RESOURCE_STATES stateBeforeVB, - D3D12_RESOURCE_STATES stateAfterVB, - D3D12_RESOURCE_STATES stateBeforeIB, - D3D12_RESOURCE_STATES stateAfterIB) +void GeometricPrimitive::Transition(_In_ ID3D12GraphicsCommandList* commandList, + D3D12_RESOURCE_STATES stateBeforeVB, + D3D12_RESOURCE_STATES stateAfterVB, + D3D12_RESOURCE_STATES stateBeforeIB, + D3D12_RESOURCE_STATES stateAfterIB) { pImpl->Transition(commandList, stateBeforeVB, stateAfterVB, stateBeforeIB, stateAfterIB); } - - -_Use_decl_annotations_ -void GeometricPrimitive::Draw(ID3D12GraphicsCommandList* commandList) const +_Use_decl_annotations_ void GeometricPrimitive::Draw(ID3D12GraphicsCommandList* commandList) const { pImpl->DrawInstanced(commandList, 1, 0); } - -_Use_decl_annotations_ -void GeometricPrimitive::DrawInstanced(ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation) const +_Use_decl_annotations_ void +GeometricPrimitive::DrawInstanced(ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation) const { pImpl->DrawInstanced(commandList, instanceCount, startInstanceLocation); } - //-------------------------------------------------------------------------------------- // Cube (aka a Hexahedron) or Box //-------------------------------------------------------------------------------------- // Creates a cube primitive. -std::unique_ptr GeometricPrimitive::CreateCube( - float size, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr GeometricPrimitive::CreateCube(float size, bool rhcoords, _In_opt_ ID3D12Device* device) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeBox(vertices, indices, XMFLOAT3(size, size, size), rhcoords, false); // Create the primitive object. @@ -305,25 +277,17 @@ std::unique_ptr GeometricPrimitive::CreateCube( return primitive; } -void GeometricPrimitive::CreateCube( - VertexCollection& vertices, - IndexCollection& indices, - float size, - bool rhcoords) +void GeometricPrimitive::CreateCube(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords) { ComputeBox(vertices, indices, XMFLOAT3(size, size, size), rhcoords, false); } - // Creates a box primitive. -std::unique_ptr GeometricPrimitive::CreateBox( - const XMFLOAT3& size, - bool rhcoords, - bool invertn, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateBox(const XMFLOAT3& size, bool rhcoords, bool invertn, _In_opt_ ID3D12Device* device) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeBox(vertices, indices, size, rhcoords, invertn); // Create the primitive object. @@ -334,34 +298,24 @@ std::unique_ptr GeometricPrimitive::CreateBox( return primitive; } -void GeometricPrimitive::CreateBox( - VertexCollection& vertices, - IndexCollection& indices, - const XMFLOAT3& size, - bool rhcoords, - bool invertn) +void GeometricPrimitive::CreateBox(VertexCollection& vertices, IndexCollection& indices, const XMFLOAT3& size, bool rhcoords, bool invertn) { ComputeBox(vertices, indices, size, rhcoords, invertn); } - //-------------------------------------------------------------------------------------- // Sphere //-------------------------------------------------------------------------------------- // Creates a sphere primitive. -std::unique_ptr GeometricPrimitive::CreateSphere( - float diameter, - size_t tessellation, - bool rhcoords, - bool invertn, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateSphere(float diameter, size_t tessellation, bool rhcoords, bool invertn, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeSphere(vertices, indices, diameter, tessellation, rhcoords, invertn); @@ -370,34 +324,29 @@ std::unique_ptr GeometricPrimitive::CreateSphere( return primitive; } -void GeometricPrimitive::CreateSphere( - VertexCollection& vertices, - IndexCollection& indices, - float diameter, - size_t tessellation, - bool rhcoords, - bool invertn) +void GeometricPrimitive::CreateSphere(VertexCollection& vertices, + IndexCollection& indices, + float diameter, + size_t tessellation, + bool rhcoords, + bool invertn) { ComputeSphere(vertices, indices, diameter, tessellation, rhcoords, invertn); } - //-------------------------------------------------------------------------------------- // Geodesic sphere //-------------------------------------------------------------------------------------- // Creates a geosphere primitive. -std::unique_ptr GeometricPrimitive::CreateGeoSphere( - float diameter, - size_t tessellation, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateGeoSphere(float diameter, size_t tessellation, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeGeoSphere(vertices, indices, diameter, tessellation, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -405,34 +354,28 @@ std::unique_ptr GeometricPrimitive::CreateGeoSphere( return primitive; } -void GeometricPrimitive::CreateGeoSphere( - VertexCollection& vertices, - IndexCollection& indices, - float diameter, - size_t tessellation, - bool rhcoords) +void GeometricPrimitive::CreateGeoSphere(VertexCollection& vertices, + IndexCollection& indices, + float diameter, + size_t tessellation, + bool rhcoords) { ComputeGeoSphere(vertices, indices, diameter, tessellation, rhcoords); } - //-------------------------------------------------------------------------------------- // Cylinder / Cone //-------------------------------------------------------------------------------------- // Creates a cylinder primitive. -std::unique_ptr GeometricPrimitive::CreateCylinder( - float height, - float diameter, - size_t tessellation, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateCylinder(float height, float diameter, size_t tessellation, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeCylinder(vertices, indices, height, diameter, tessellation, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -440,30 +383,25 @@ std::unique_ptr GeometricPrimitive::CreateCylinder( return primitive; } -void GeometricPrimitive::CreateCylinder( - VertexCollection& vertices, - IndexCollection& indices, - float height, float diameter, - size_t tessellation, - bool rhcoords) +void GeometricPrimitive::CreateCylinder(VertexCollection& vertices, + IndexCollection& indices, + float height, + float diameter, + size_t tessellation, + bool rhcoords) { ComputeCylinder(vertices, indices, height, diameter, tessellation, rhcoords); } - // Creates a cone primitive. -std::unique_ptr GeometricPrimitive::CreateCone( - float diameter, - float height, - size_t tessellation, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateCone(float diameter, float height, size_t tessellation, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeCone(vertices, indices, diameter, height, tessellation, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -471,35 +409,29 @@ std::unique_ptr GeometricPrimitive::CreateCone( return primitive; } -void GeometricPrimitive::CreateCone( - VertexCollection& vertices, - IndexCollection& indices, - float diameter, - float height, - size_t tessellation, - bool rhcoords) +void GeometricPrimitive::CreateCone(VertexCollection& vertices, + IndexCollection& indices, + float diameter, + float height, + size_t tessellation, + bool rhcoords) { ComputeCone(vertices, indices, diameter, height, tessellation, rhcoords); } - //-------------------------------------------------------------------------------------- // Torus //-------------------------------------------------------------------------------------- // Creates a torus primitive. -std::unique_ptr GeometricPrimitive::CreateTorus( - float diameter, - float thickness, - size_t tessellation, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateTorus(float diameter, float thickness, size_t tessellation, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeTorus(vertices, indices, diameter, thickness, tessellation, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -507,32 +439,27 @@ std::unique_ptr GeometricPrimitive::CreateTorus( return primitive; } -void GeometricPrimitive::CreateTorus( - VertexCollection& vertices, - IndexCollection& indices, - float diameter, - float thickness, - size_t tessellation, - bool rhcoords) +void GeometricPrimitive::CreateTorus(VertexCollection& vertices, + IndexCollection& indices, + float diameter, + float thickness, + size_t tessellation, + bool rhcoords) { ComputeTorus(vertices, indices, diameter, thickness, tessellation, rhcoords); } - //-------------------------------------------------------------------------------------- // Tetrahedron //-------------------------------------------------------------------------------------- -std::unique_ptr GeometricPrimitive::CreateTetrahedron( - float size, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr GeometricPrimitive::CreateTetrahedron(float size, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeTetrahedron(vertices, indices, size, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -540,30 +467,22 @@ std::unique_ptr GeometricPrimitive::CreateTetrahedron( return primitive; } -void GeometricPrimitive::CreateTetrahedron( - VertexCollection& vertices, - IndexCollection& indices, - float size, - bool rhcoords) +void GeometricPrimitive::CreateTetrahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords) { ComputeTetrahedron(vertices, indices, size, rhcoords); } - //-------------------------------------------------------------------------------------- // Octahedron //-------------------------------------------------------------------------------------- -std::unique_ptr GeometricPrimitive::CreateOctahedron( - float size, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr GeometricPrimitive::CreateOctahedron(float size, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeOctahedron(vertices, indices, size, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -571,30 +490,22 @@ std::unique_ptr GeometricPrimitive::CreateOctahedron( return primitive; } -void GeometricPrimitive::CreateOctahedron( - VertexCollection& vertices, - IndexCollection& indices, - float size, - bool rhcoords) +void GeometricPrimitive::CreateOctahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords) { ComputeOctahedron(vertices, indices, size, rhcoords); } - //-------------------------------------------------------------------------------------- // Dodecahedron //-------------------------------------------------------------------------------------- -std::unique_ptr GeometricPrimitive::CreateDodecahedron( - float size, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr GeometricPrimitive::CreateDodecahedron(float size, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeDodecahedron(vertices, indices, size, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -602,30 +513,22 @@ std::unique_ptr GeometricPrimitive::CreateDodecahedron( return primitive; } -void GeometricPrimitive::CreateDodecahedron( - VertexCollection& vertices, - IndexCollection& indices, - float size, - bool rhcoords) +void GeometricPrimitive::CreateDodecahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords) { ComputeDodecahedron(vertices, indices, size, rhcoords); } - //-------------------------------------------------------------------------------------- // Icosahedron //-------------------------------------------------------------------------------------- -std::unique_ptr GeometricPrimitive::CreateIcosahedron( - float size, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr GeometricPrimitive::CreateIcosahedron(float size, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeIcosahedron(vertices, indices, size, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -633,32 +536,24 @@ std::unique_ptr GeometricPrimitive::CreateIcosahedron( return primitive; } -void GeometricPrimitive::CreateIcosahedron( - VertexCollection& vertices, - IndexCollection& indices, - float size, - bool rhcoords) +void GeometricPrimitive::CreateIcosahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords) { ComputeIcosahedron(vertices, indices, size, rhcoords); } - //-------------------------------------------------------------------------------------- // Teapot //-------------------------------------------------------------------------------------- // Creates a teapot primitive. -std::unique_ptr GeometricPrimitive::CreateTeapot( - float size, - size_t tessellation, - bool rhcoords, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateTeapot(float size, size_t tessellation, bool rhcoords, _In_opt_ ID3D12Device* device) { // Create the primitive object. std::unique_ptr primitive(new GeometricPrimitive()); VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeTeapot(vertices, indices, size, tessellation, rhcoords); primitive->pImpl->Initialize(vertices, indices, device); @@ -666,24 +561,17 @@ std::unique_ptr GeometricPrimitive::CreateTeapot( return primitive; } -void GeometricPrimitive::CreateTeapot( - VertexCollection& vertices, - IndexCollection& indices, - float size, size_t tessellation, - bool rhcoords) +void GeometricPrimitive::CreateTeapot(VertexCollection& vertices, IndexCollection& indices, float size, size_t tessellation, bool rhcoords) { ComputeTeapot(vertices, indices, size, tessellation, rhcoords); } - //-------------------------------------------------------------------------------------- // Custom //-------------------------------------------------------------------------------------- -std::unique_ptr GeometricPrimitive::CreateCustom( - const VertexCollection& vertices, - const IndexCollection& indices, - _In_opt_ ID3D12Device* device) +std::unique_ptr +GeometricPrimitive::CreateCustom(const VertexCollection& vertices, const IndexCollection& indices, _In_opt_ ID3D12Device* device) { // Extra validation if (vertices.empty() || indices.empty()) diff --git a/Src/Geometry.cpp b/Src/Geometry.cpp index 26a70f98..6dcf7df1 100644 --- a/Src/Geometry.cpp +++ b/Src/Geometry.cpp @@ -27,7 +27,6 @@ namespace throw std::out_of_range("Index value out of range: cannot tesselate primitive so finely"); } - // Collection types used when generating the geometry. inline void index_push_back(IndexCollection& indices, size_t value) { @@ -35,7 +34,6 @@ namespace indices.push_back(static_cast(value)); } - // Helper for flipping winding of geometric primitives for LH vs. RH coords inline void ReverseWinding(IndexCollection& indices, VertexCollection& vertices) { @@ -51,7 +49,6 @@ namespace } } - // Helper for inverting normals of geometric primitives for 'inside' vs. 'outside' viewing inline void InvertNormals(VertexCollection& vertices) { @@ -62,8 +59,7 @@ namespace it.normal.z = -it.normal.z; } } -} - +} // namespace //-------------------------------------------------------------------------------------- // Cube (aka a Hexahedron) or Box @@ -76,18 +72,16 @@ void DirectX::ComputeBox(VertexCollection& vertices, IndexCollection& indices, c // A box has six faces, each one pointing in a different direction. constexpr int FaceCount = 6; - static const XMVECTORF32 faceNormals[FaceCount] = - { - { { { 0, 0, 1, 0 } } }, - { { { 0, 0, -1, 0 } } }, - { { { 1, 0, 0, 0 } } }, - { { { -1, 0, 0, 0 } } }, - { { { 0, 1, 0, 0 } } }, - { { { 0, -1, 0, 0 } } }, + static const XMVECTORF32 faceNormals[FaceCount] = { + { { { 0, 0, 1, 0 } } }, + { { { 0, 0, -1, 0 } } }, + { { { 1, 0, 0, 0 } } }, + { { { -1, 0, 0, 0 } } }, + { { { 0, 1, 0, 0 } } }, + { { { 0, -1, 0, 0 } } }, }; - static const XMVECTORF32 textureCoordinates[4] = - { + static const XMVECTORF32 textureCoordinates[4] = { { { { 1, 0, 0, 0 } } }, { { { 1, 1, 0, 0 } } }, { { { 0, 1, 0, 0 } } }, @@ -95,7 +89,7 @@ void DirectX::ComputeBox(VertexCollection& vertices, IndexCollection& indices, c }; XMVECTOR tsize = XMLoadFloat3(&size); - tsize = XMVectorDivide(tsize, g_XMTwo); + tsize = XMVectorDivide(tsize, g_XMTwo); // Create each face in turn. for (int i = 0; i < FaceCount; i++) @@ -120,16 +114,24 @@ void DirectX::ComputeBox(VertexCollection& vertices, IndexCollection& indices, c // Four vertices per face. // (normal - side1 - side2) * tsize // normal // t0 - vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorSubtract(XMVectorSubtract(normal, side1), side2), tsize), normal, textureCoordinates[0])); + vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorSubtract(XMVectorSubtract(normal, side1), side2), tsize), + normal, + textureCoordinates[0])); // (normal - side1 + side2) * tsize // normal // t1 - vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorAdd(XMVectorSubtract(normal, side1), side2), tsize), normal, textureCoordinates[1])); + vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorAdd(XMVectorSubtract(normal, side1), side2), tsize), + normal, + textureCoordinates[1])); // (normal + side1 + side2) * tsize // normal // t2 - vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorAdd(normal, XMVectorAdd(side1, side2)), tsize), normal, textureCoordinates[2])); + vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorAdd(normal, XMVectorAdd(side1, side2)), tsize), + normal, + textureCoordinates[2])); // (normal + side1 - side2) * tsize // normal // t3 - vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorSubtract(XMVectorAdd(normal, side1), side2), tsize), normal, textureCoordinates[3])); + vertices.push_back(VertexPositionNormalTexture(XMVectorMultiply(XMVectorSubtract(XMVectorAdd(normal, side1), side2), tsize), + normal, + textureCoordinates[3])); } // Build RH above @@ -140,11 +142,15 @@ void DirectX::ComputeBox(VertexCollection& vertices, IndexCollection& indices, c InvertNormals(vertices); } - //-------------------------------------------------------------------------------------- // Sphere //-------------------------------------------------------------------------------------- -void DirectX::ComputeSphere(VertexCollection& vertices, IndexCollection& indices, float diameter, size_t tessellation, bool rhcoords, bool invertn) +void DirectX::ComputeSphere(VertexCollection& vertices, + IndexCollection& indices, + float diameter, + size_t tessellation, + bool rhcoords, + bool invertn) { vertices.clear(); indices.clear(); @@ -152,7 +158,7 @@ void DirectX::ComputeSphere(VertexCollection& vertices, IndexCollection& indices if (tessellation < 3) throw std::invalid_argument("tesselation parameter must be at least 3"); - const size_t verticalSegments = tessellation; + const size_t verticalSegments = tessellation; const size_t horizontalSegments = tessellation * 2; const float radius = diameter / 2; @@ -163,7 +169,7 @@ void DirectX::ComputeSphere(VertexCollection& vertices, IndexCollection& indices const float v = 1 - float(i) / float(verticalSegments); const float latitude = (float(i) * XM_PI / float(verticalSegments)) - XM_PIDIV2; - float dy, dxz; + float dy, dxz; XMScalarSinCos(&dy, &dxz, latitude); @@ -173,14 +179,14 @@ void DirectX::ComputeSphere(VertexCollection& vertices, IndexCollection& indices const float u = float(j) / float(horizontalSegments); const float longitude = float(j) * XM_2PI / float(horizontalSegments); - float dx, dz; + float dx, dz; XMScalarSinCos(&dx, &dz, longitude); dx *= dxz; dz *= dxz; - const XMVECTOR normal = XMVectorSet(dx, dy, dz, 0); + const XMVECTOR normal = XMVectorSet(dx, dy, dz, 0); const XMVECTOR textureCoordinate = XMVectorSet(u, v, 0, 0); vertices.push_back(VertexPositionNormalTexture(XMVectorScale(normal, radius), normal, textureCoordinate)); @@ -215,7 +221,6 @@ void DirectX::ComputeSphere(VertexCollection& vertices, IndexCollection& indices InvertNormals(vertices); } - //-------------------------------------------------------------------------------------- // Geodesic sphere //-------------------------------------------------------------------------------------- @@ -231,28 +236,27 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // Makes an undirected edge. Rather than overloading comparison operators to give us the (a,b)==(b,a) property, // we'll just ensure that the larger of the two goes first. This'll simplify things greatly. auto makeUndirectedEdge = [](uint16_t a, uint16_t b) noexcept - { - return std::make_pair(std::max(a, b), std::min(a, b)); - }; + { + return std::make_pair(std::max(a, b), std::min(a, b)); + }; - // Key: an edge - // Value: the index of the vertex which lies midway between the two vertices pointed to by the key value - // This map is used to avoid duplicating vertices when subdividing triangles along edges. + // Key: an edge + // Value: the index of the vertex which lies midway between the two vertices pointed to by the key value + // This map is used to avoid duplicating vertices when subdividing triangles along edges. using EdgeSubdivisionMap = std::map; - - static const XMFLOAT3 OctahedronVertices[] = - { + static const XMFLOAT3 OctahedronVertices[] = { // when looking down the negative z-axis (into the screen) - XMFLOAT3(0, 1, 0), // 0 top - XMFLOAT3(0, 0, -1), // 1 front - XMFLOAT3(1, 0, 0), // 2 right - XMFLOAT3(0, 0, 1), // 3 back - XMFLOAT3(-1, 0, 0), // 4 left - XMFLOAT3(0, -1, 0), // 5 bottom + XMFLOAT3(0, 1, 0), // 0 top + XMFLOAT3(0, 0, -1), // 1 front + XMFLOAT3(1, 0, 0), // 2 right + XMFLOAT3(0, 0, 1), // 3 back + XMFLOAT3(-1, 0, 0), // 4 left + XMFLOAT3(0, -1, 0), // 5 bottom }; - static const uint16_t OctahedronIndices[] = - { + + static const uint16_t OctahedronIndices[] = { + // clang-format off 0, 1, 2, // top front-right face 0, 2, 3, // top back-right face 0, 3, 4, // top back-left face @@ -261,6 +265,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi 5, 4, 3, // bottom back-left face 5, 3, 2, // bottom back-right face 5, 2, 1, // bottom front-right face + // clang-format on }; const float radius = diameter / 2.0f; @@ -299,50 +304,45 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi const uint16_t iv2 = indices[iTriangle * 3 + 2]; // Get the new vertices - XMFLOAT3 v01; // vertex on the midpoint of v0 and v1 - XMFLOAT3 v12; // ditto v1 and v2 - XMFLOAT3 v20; // ditto v2 and v0 + XMFLOAT3 v01; // vertex on the midpoint of v0 and v1 + XMFLOAT3 v12; // ditto v1 and v2 + XMFLOAT3 v20; // ditto v2 and v0 uint16_t iv01; // index of v01 uint16_t iv12; // index of v12 uint16_t iv20; // index of v20 // Function that, when given the index of two vertices, creates a new vertex at the midpoint of those vertices. const auto divideEdge = [&](uint16_t i0, uint16_t i1, XMFLOAT3& outVertex, uint16_t& outIndex) + { + const UndirectedEdge edge = makeUndirectedEdge(i0, i1); + + // Check to see if we've already generated this vertex + auto it = subdividedEdges.find(edge); + if (it != subdividedEdges.end()) + { + // We've already generated this vertex before + outIndex = it->second; // the index of this vertex + outVertex = vertexPositions[outIndex]; // and the vertex itself + } + else { - const UndirectedEdge edge = makeUndirectedEdge(i0, i1); - - // Check to see if we've already generated this vertex - auto it = subdividedEdges.find(edge); - if (it != subdividedEdges.end()) - { - // We've already generated this vertex before - outIndex = it->second; // the index of this vertex - outVertex = vertexPositions[outIndex]; // and the vertex itself - } - else - { - // Haven't generated this vertex before: so add it now - - // outVertex = (vertices[i0] + vertices[i1]) / 2 - XMStoreFloat3( - &outVertex, - XMVectorScale( - XMVectorAdd(XMLoadFloat3(&vertexPositions[i0]), XMLoadFloat3(&vertexPositions[i1])), - 0.5f - ) - ); - - outIndex = static_cast(vertexPositions.size()); - CheckIndexOverflow(outIndex); - vertexPositions.push_back(outVertex); - - // Now add it to the map. - auto entry = std::make_pair(edge, outIndex); - subdividedEdges.insert(entry); - } - }; - - // Add/get new vertices and their indices + // Haven't generated this vertex before: so add it now + + // outVertex = (vertices[i0] + vertices[i1]) / 2 + XMStoreFloat3(&outVertex, + XMVectorScale(XMVectorAdd(XMLoadFloat3(&vertexPositions[i0]), XMLoadFloat3(&vertexPositions[i1])), 0.5f)); + + outIndex = static_cast(vertexPositions.size()); + CheckIndexOverflow(outIndex); + vertexPositions.push_back(outVertex); + + // Now add it to the map. + auto entry = std::make_pair(edge, outIndex); + subdividedEdges.insert(entry); + } + }; + + // Add/get new vertices and their indices divideEdge(iv0, iv1, v01, iv01); divideEdge(iv1, iv2, v12, iv12); divideEdge(iv0, iv2, v20, iv20); @@ -355,12 +355,14 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // /b\c/d\ // v2 o---o---o v1 // v12 - const uint16_t indicesToAdd[] = - { + + const uint16_t indicesToAdd[] = { + // clang-format off iv0, iv01, iv20, // a iv20, iv12, iv2, // b iv20, iv01, iv12, // c iv01, iv1, iv12, // d + // clang-format on }; newIndices.insert(newIndices.end(), std::begin(indicesToAdd), std::end(indicesToAdd)); } @@ -373,14 +375,14 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi for (const auto& it : vertexPositions) { const auto normal = XMVector3Normalize(XMLoadFloat3(&it)); - const auto pos = XMVectorScale(normal, radius); + const auto pos = XMVectorScale(normal, radius); XMFLOAT3 normalFloat3; XMStoreFloat3(&normalFloat3, normal); // calculate texture coordinates for this vertex const float longitude = atan2f(normalFloat3.x, -normalFloat3.z); - const float latitude = acosf(normalFloat3.y); + const float latitude = acosf(normalFloat3.y); const float u = longitude / XM_2PI + 0.5f; const float v = latitude / XM_PI; @@ -403,8 +405,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi for (size_t i = 0; i < preFixupVertexCount; ++i) { // This vertex is on the prime meridian if position.x and texcoord.u are both zero (allowing for small epsilon). - const bool isOnPrimeMeridian = XMVector2NearEqual( - XMVectorSet(vertices[i].position.x, vertices[i].textureCoordinate.x, 0.0f, 0.0f), + const bool isOnPrimeMeridian = XMVector2NearEqual(XMVectorSet(vertices[i].position.x, vertices[i].textureCoordinate.x, 0.0f, 0.0f), XMVectorZero(), XMVectorSplatEpsilon()); @@ -415,7 +416,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // copy this vertex, correct the texture coordinate, and add the vertex VertexPositionNormalTexture v = vertices[i]; - v.textureCoordinate.x = 1.0f; + v.textureCoordinate.x = 1.0f; vertices.push_back(v); // Now find all the triangles which contain this vertex and update them if necessary @@ -453,8 +454,8 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // check the other two vertices to see if we might need to fix this triangle - if (abs(v0.textureCoordinate.x - v1.textureCoordinate.x) > 0.5f || - abs(v0.textureCoordinate.x - v2.textureCoordinate.x) > 0.5f) + if (abs(v0.textureCoordinate.x - v1.textureCoordinate.x) > 0.5f + || abs(v0.textureCoordinate.x - v2.textureCoordinate.x) > 0.5f) { // yep; replace the specified index to point to the new, corrected vertex *triIndex0 = static_cast(newIndex); @@ -469,63 +470,63 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // spheres, we need to duplicate the pole vertex for every triangle that uses it. This will introduce seams near the // poles, but reduce stretching. const auto fixPole = [&](size_t poleIndex) - { - const auto& poleVertex = vertices[poleIndex]; - bool overwrittenPoleVertex = false; // overwriting the original pole vertex saves us one vertex + { + const auto& poleVertex = vertices[poleIndex]; + bool overwrittenPoleVertex = false; // overwriting the original pole vertex saves us one vertex - for (size_t i = 0; i < indices.size(); i += 3) + for (size_t i = 0; i < indices.size(); i += 3) + { + // These pointers point to the three indices which make up this triangle. pPoleIndex is the pointer to the + // entry in the index array which represents the pole index, and the other two pointers point to the other + // two indices making up this triangle. + uint16_t* pPoleIndex; + uint16_t* pOtherIndex0; + uint16_t* pOtherIndex1; + if (indices[i + 0] == poleIndex) { - // These pointers point to the three indices which make up this triangle. pPoleIndex is the pointer to the - // entry in the index array which represents the pole index, and the other two pointers point to the other - // two indices making up this triangle. - uint16_t* pPoleIndex; - uint16_t* pOtherIndex0; - uint16_t* pOtherIndex1; - if (indices[i + 0] == poleIndex) - { - pPoleIndex = &indices[i + 0]; - pOtherIndex0 = &indices[i + 1]; - pOtherIndex1 = &indices[i + 2]; - } - else if (indices[i + 1] == poleIndex) - { - pPoleIndex = &indices[i + 1]; - pOtherIndex0 = &indices[i + 2]; - pOtherIndex1 = &indices[i + 0]; - } - else if (indices[i + 2] == poleIndex) - { - pPoleIndex = &indices[i + 2]; - pOtherIndex0 = &indices[i + 0]; - pOtherIndex1 = &indices[i + 1]; - } - else - { - continue; - } + pPoleIndex = &indices[i + 0]; + pOtherIndex0 = &indices[i + 1]; + pOtherIndex1 = &indices[i + 2]; + } + else if (indices[i + 1] == poleIndex) + { + pPoleIndex = &indices[i + 1]; + pOtherIndex0 = &indices[i + 2]; + pOtherIndex1 = &indices[i + 0]; + } + else if (indices[i + 2] == poleIndex) + { + pPoleIndex = &indices[i + 2]; + pOtherIndex0 = &indices[i + 0]; + pOtherIndex1 = &indices[i + 1]; + } + else + { + continue; + } - const auto& otherVertex0 = vertices[*pOtherIndex0]; - const auto& otherVertex1 = vertices[*pOtherIndex1]; + const auto& otherVertex0 = vertices[*pOtherIndex0]; + const auto& otherVertex1 = vertices[*pOtherIndex1]; - // Calculate the texcoords for the new pole vertex, add it to the vertices and update the index - VertexPositionNormalTexture newPoleVertex = poleVertex; - newPoleVertex.textureCoordinate.x = (otherVertex0.textureCoordinate.x + otherVertex1.textureCoordinate.x) / 2; - newPoleVertex.textureCoordinate.y = poleVertex.textureCoordinate.y; + // Calculate the texcoords for the new pole vertex, add it to the vertices and update the index + VertexPositionNormalTexture newPoleVertex = poleVertex; + newPoleVertex.textureCoordinate.x = (otherVertex0.textureCoordinate.x + otherVertex1.textureCoordinate.x) / 2; + newPoleVertex.textureCoordinate.y = poleVertex.textureCoordinate.y; - if (!overwrittenPoleVertex) - { - vertices[poleIndex] = newPoleVertex; - overwrittenPoleVertex = true; - } - else - { - CheckIndexOverflow(vertices.size()); + if (!overwrittenPoleVertex) + { + vertices[poleIndex] = newPoleVertex; + overwrittenPoleVertex = true; + } + else + { + CheckIndexOverflow(vertices.size()); - *pPoleIndex = static_cast(vertices.size()); - vertices.push_back(newPoleVertex); - } + *pPoleIndex = static_cast(vertices.size()); + vertices.push_back(newPoleVertex); } - }; + } + }; fixPole(northPoleIndex); fixPole(southPoleIndex); @@ -535,7 +536,6 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi ReverseWinding(indices, vertices); } - //-------------------------------------------------------------------------------------- // Cylinder / Cone //-------------------------------------------------------------------------------------- @@ -545,7 +545,7 @@ namespace inline XMVECTOR GetCircleVector(size_t i, size_t tessellation) noexcept { const float angle = float(i) * XM_2PI / float(tessellation); - float dx, dz; + float dx, dz; XMScalarSinCos(&dx, &dz, angle); @@ -556,7 +556,7 @@ namespace inline XMVECTOR GetCircleTangent(size_t i, size_t tessellation) noexcept { const float angle = (float(i) * XM_2PI / float(tessellation)) + XM_PIDIV2; - float dx, dz; + float dx, dz; XMScalarSinCos(&dx, &dz, angle); @@ -564,9 +564,9 @@ namespace return v; } - // Helper creates a triangle fan to close the end of a cylinder / cone - void CreateCylinderCap(VertexCollection& vertices, IndexCollection& indices, size_t tessellation, float height, float radius, bool isTop) + void + CreateCylinderCap(VertexCollection& vertices, IndexCollection& indices, size_t tessellation, float height, float radius, bool isTop) { // Create cap indices. for (size_t i = 0; i < tessellation - 2; i++) @@ -586,12 +586,12 @@ namespace } // Which end of the cylinder is this? - XMVECTOR normal = g_XMIdentityR1; + XMVECTOR normal = g_XMIdentityR1; XMVECTOR textureScale = g_XMNegativeOneHalf; if (!isTop) { - normal = XMVectorNegate(normal); + normal = XMVectorNegate(normal); textureScale = XMVectorMultiply(textureScale, g_XMNegateX); } @@ -607,9 +607,14 @@ namespace vertices.push_back(VertexPositionNormalTexture(position, normal, textureCoordinate)); } } -} - -void DirectX::ComputeCylinder(VertexCollection& vertices, IndexCollection& indices, float height, float diameter, size_t tessellation, bool rhcoords) +} // namespace + +void DirectX::ComputeCylinder(VertexCollection& vertices, + IndexCollection& indices, + float height, + float diameter, + size_t tessellation, + bool rhcoords) { vertices.clear(); indices.clear(); @@ -621,7 +626,7 @@ void DirectX::ComputeCylinder(VertexCollection& vertices, IndexCollection& indic const XMVECTOR topOffset = XMVectorScale(g_XMIdentityR1, height); - const float radius = diameter / 2; + const float radius = diameter / 2; const size_t stride = tessellation + 1; // Create a ring of triangles around the outside of the cylinder. @@ -636,7 +641,8 @@ void DirectX::ComputeCylinder(VertexCollection& vertices, IndexCollection& indic const XMVECTOR textureCoordinate = XMLoadFloat(&u); vertices.push_back(VertexPositionNormalTexture(XMVectorAdd(sideOffset, topOffset), normal, textureCoordinate)); - vertices.push_back(VertexPositionNormalTexture(XMVectorSubtract(sideOffset, topOffset), normal, XMVectorAdd(textureCoordinate, g_XMIdentityR1))); + vertices.push_back( + VertexPositionNormalTexture(XMVectorSubtract(sideOffset, topOffset), normal, XMVectorAdd(textureCoordinate, g_XMIdentityR1))); index_push_back(indices, i * 2); index_push_back(indices, (i * 2 + 2) % (stride * 2)); @@ -656,9 +662,13 @@ void DirectX::ComputeCylinder(VertexCollection& vertices, IndexCollection& indic ReverseWinding(indices, vertices); } - // Creates a cone primitive. -void DirectX::ComputeCone(VertexCollection& vertices, IndexCollection& indices, float diameter, float height, size_t tessellation, bool rhcoords) +void DirectX::ComputeCone(VertexCollection& vertices, + IndexCollection& indices, + float diameter, + float height, + size_t tessellation, + bool rhcoords) { vertices.clear(); indices.clear(); @@ -670,7 +680,7 @@ void DirectX::ComputeCone(VertexCollection& vertices, IndexCollection& indices, const XMVECTOR topOffset = XMVectorScale(g_XMIdentityR1, height); - const float radius = diameter / 2; + const float radius = diameter / 2; const size_t stride = tessellation + 1; // Create a ring of triangles around the outside of the cone. @@ -686,10 +696,8 @@ void DirectX::ComputeCone(VertexCollection& vertices, IndexCollection& indices, const XMVECTOR pt = XMVectorSubtract(sideOffset, topOffset); - XMVECTOR normal = XMVector3Cross( - GetCircleTangent(i, tessellation), - XMVectorSubtract(topOffset, pt)); - normal = XMVector3Normalize(normal); + XMVECTOR normal = XMVector3Cross(GetCircleTangent(i, tessellation), XMVectorSubtract(topOffset, pt)); + normal = XMVector3Normalize(normal); // Duplicate the top vertex for distinct normals vertices.push_back(VertexPositionNormalTexture(topOffset, normal, g_XMZero)); @@ -708,11 +716,15 @@ void DirectX::ComputeCone(VertexCollection& vertices, IndexCollection& indices, ReverseWinding(indices, vertices); } - //-------------------------------------------------------------------------------------- // Torus //-------------------------------------------------------------------------------------- -void DirectX::ComputeTorus(VertexCollection& vertices, IndexCollection& indices, float diameter, float thickness, size_t tessellation, bool rhcoords) +void DirectX::ComputeTorus(VertexCollection& vertices, + IndexCollection& indices, + float diameter, + float thickness, + size_t tessellation, + bool rhcoords) { vertices.clear(); indices.clear(); @@ -739,17 +751,17 @@ void DirectX::ComputeTorus(VertexCollection& vertices, IndexCollection& indices, const float v = 1 - float(j) / float(tessellation); const float innerAngle = float(j) * XM_2PI / float(tessellation) + XM_PI; - float dx, dy; + float dx, dy; XMScalarSinCos(&dy, &dx, innerAngle); // Create a vertex. - XMVECTOR normal = XMVectorSet(dx, dy, 0, 0); - XMVECTOR position = XMVectorScale(normal, thickness / 2); + XMVECTOR normal = XMVectorSet(dx, dy, 0, 0); + XMVECTOR position = XMVectorScale(normal, thickness / 2); const XMVECTOR textureCoordinate = XMVectorSet(u, v, 0, 0); position = XMVector3Transform(position, transform); - normal = XMVector3TransformNormal(normal, transform); + normal = XMVector3TransformNormal(normal, transform); vertices.push_back(VertexPositionNormalTexture(position, normal, textureCoordinate)); @@ -772,7 +784,6 @@ void DirectX::ComputeTorus(VertexCollection& vertices, IndexCollection& indices, ReverseWinding(indices, vertices); } - //-------------------------------------------------------------------------------------- // Tetrahedron //-------------------------------------------------------------------------------------- @@ -781,20 +792,22 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in vertices.clear(); indices.clear(); - static const XMVECTORF32 verts[4] = - { + static const XMVECTORF32 verts[4] = { + // clang-format off { { { 0.f, 0.f, 1.f, 0 } } }, { { { 2.f*SQRT2 / 3.f, 0.f, -1.f / 3.f, 0 } } }, { { { -SQRT2 / 3.f, SQRT6 / 3.f, -1.f / 3.f, 0 } } }, { { { -SQRT2 / 3.f, -SQRT6 / 3.f, -1.f / 3.f, 0 } } } + // clang-format on }; - static const uint32_t faces[4 * 3] = - { + static const uint32_t faces[4 * 3] = { + // clang-format off 0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2, + // clang-format on }; for (size_t j = 0; j < std::size(faces); j += 3) @@ -803,10 +816,8 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in const uint32_t v1 = faces[j + 1]; const uint32_t v2 = faces[j + 2]; - XMVECTOR normal = XMVector3Cross( - XMVectorSubtract(verts[v1].v, verts[v0].v), - XMVectorSubtract(verts[v2].v, verts[v0].v)); - normal = XMVector3Normalize(normal); + XMVECTOR normal = XMVector3Cross(XMVectorSubtract(verts[v1].v, verts[v0].v), XMVectorSubtract(verts[v2].v, verts[v0].v)); + normal = XMVector3Normalize(normal); const size_t base = vertices.size(); index_push_back(indices, base); @@ -832,7 +843,6 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in assert(indices.size() == 4 * 3); } - //-------------------------------------------------------------------------------------- // Octahedron //-------------------------------------------------------------------------------------- @@ -841,18 +851,15 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind vertices.clear(); indices.clear(); - static const XMVECTORF32 verts[6] = - { - { { { 1, 0, 0, 0 } } }, - { { { -1, 0, 0, 0 } } }, - { { { 0, 1, 0, 0 } } }, - { { { 0, -1, 0, 0 } } }, - { { { 0, 0, 1, 0 } } }, - { { { 0, 0, -1, 0 } } } - }; + static const XMVECTORF32 verts[6] = { { { { 1, 0, 0, 0 } } }, + { { { -1, 0, 0, 0 } } }, + { { { 0, 1, 0, 0 } } }, + { { { 0, -1, 0, 0 } } }, + { { { 0, 0, 1, 0 } } }, + { { { 0, 0, -1, 0 } } } }; - static const uint32_t faces[8 * 3] = - { + static const uint32_t faces[8 * 3] = { + // clang-format off 4, 0, 2, 4, 2, 1, 4, 1, 3, @@ -861,6 +868,7 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind 5, 1, 2, 5, 3, 1, 5, 0, 3 + // clang-format on }; for (size_t j = 0; j < std::size(faces); j += 3) @@ -869,10 +877,8 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind const uint32_t v1 = faces[j + 1]; const uint32_t v2 = faces[j + 2]; - XMVECTOR normal = XMVector3Cross( - XMVectorSubtract(verts[v1].v, verts[v0].v), - XMVectorSubtract(verts[v2].v, verts[v0].v)); - normal = XMVector3Normalize(normal); + XMVECTOR normal = XMVector3Cross(XMVectorSubtract(verts[v1].v, verts[v0].v), XMVectorSubtract(verts[v2].v, verts[v0].v)); + normal = XMVector3Normalize(normal); const size_t base = vertices.size(); index_push_back(indices, base); @@ -898,7 +904,6 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind assert(indices.size() == 8 * 3); } - //-------------------------------------------------------------------------------------- // Dodecahedron //-------------------------------------------------------------------------------------- @@ -911,8 +916,8 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i constexpr float b = 0.356822089773089931942f; // sqrt( ( 3 - sqrt(5) ) / 6 ) constexpr float c = 0.934172358962715696451f; // sqrt( ( 3 + sqrt(5) ) / 6 ); - static const XMVECTORF32 verts[20] = - { + static const XMVECTORF32 verts[20] = { + // clang-format off { { { a, a, a, 0 } } }, { { { a, a, -a, 0 } } }, { { { a, -a, a, 0 } } }, @@ -933,10 +938,11 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i { { { 0, -b, c, 0 } } }, { { { 0, b, -c, 0 } } }, { { { 0, -b, -c, 0 } } } + // clang-format on }; - static const uint32_t faces[12 * 5] = - { + static const uint32_t faces[12 * 5] = { + // clang-format off 0, 8, 9, 4, 16, 0, 16, 17, 2, 12, 12, 2, 10, 3, 13, @@ -949,19 +955,21 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i 6, 11, 10, 2, 17, 7, 15, 5, 18, 19, 7, 19, 3, 10, 11, + // clang-format on }; - static const XMVECTORF32 textureCoordinates[5] = - { + static const XMVECTORF32 textureCoordinates[5] = { + // clang-format off { { { 0.654508f, 0.0244717f, 0, 0 } } }, { { { 0.0954915f, 0.206107f, 0, 0 } } }, { { { 0.0954915f, 0.793893f, 0, 0 } } }, { { { 0.654508f, 0.975528f, 0, 0 } } }, { { { 1.f, 0.5f, 0, 0 } } } + // clang-format on }; - static const uint32_t textureIndex[12][5] = - { + static const uint32_t textureIndex[12][5] = { + // clang-format off { 0, 1, 2, 3, 4 }, { 2, 3, 4, 0, 1 }, { 4, 0, 1, 2, 3 }, @@ -974,6 +982,7 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i { 1, 2, 3, 4, 0 }, { 0, 1, 2, 3, 4 }, { 2, 3, 4, 0, 1 }, + // clang-format on }; size_t t = 0; @@ -985,10 +994,8 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i const uint32_t v3 = faces[j + 3]; const uint32_t v4 = faces[j + 4]; - XMVECTOR normal = XMVector3Cross( - XMVectorSubtract(verts[v1].v, verts[v0].v), - XMVectorSubtract(verts[v2].v, verts[v0].v)); - normal = XMVector3Normalize(normal); + XMVECTOR normal = XMVector3Cross(XMVectorSubtract(verts[v1].v, verts[v0].v), XMVectorSubtract(verts[v2].v, verts[v0].v)); + normal = XMVector3Normalize(normal); const size_t base = vertices.size(); @@ -1029,7 +1036,6 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i assert(indices.size() == 12 * 3 * 3); } - //-------------------------------------------------------------------------------------- // Icosahedron //-------------------------------------------------------------------------------------- @@ -1038,11 +1044,11 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in vertices.clear(); indices.clear(); - constexpr float t = 1.618033988749894848205f; // (1 + sqrt(5)) / 2 + constexpr float t = 1.618033988749894848205f; // (1 + sqrt(5)) / 2 constexpr float t2 = 1.519544995837552493271f; // sqrt( 1 + sqr( (1 + sqrt(5)) / 2 ) ) - static const XMVECTORF32 verts[12] = - { + static const XMVECTORF32 verts[12] = { + // clang-format off { { { t / t2, 1.f / t2, 0, 0 } } }, { { { -t / t2, 1.f / t2, 0, 0 } } }, { { { t / t2, -1.f / t2, 0, 0 } } }, @@ -1055,10 +1061,11 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in { { { 0, -t / t2, 1.f / t2, 0 } } }, { { { 0, t / t2, -1.f / t2, 0 } } }, { { { 0, -t / t2, -1.f / t2, 0 } } } + // clang-format on }; - static const uint32_t faces[20 * 3] = - { + static const uint32_t faces[20 * 3] = { + // clang-format off 0, 8, 4, 0, 5, 10, 2, 4, 9, @@ -1079,6 +1086,7 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in 9, 4, 6, 10, 5, 7, 11, 7, 5 + // clang-format on }; for (size_t j = 0; j < std::size(faces); j += 3) @@ -1087,10 +1095,8 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in const uint32_t v1 = faces[j + 1]; const uint32_t v2 = faces[j + 2]; - XMVECTOR normal = XMVector3Cross( - XMVectorSubtract(verts[v1].v, verts[v0].v), - XMVectorSubtract(verts[v2].v, verts[v0].v)); - normal = XMVector3Normalize(normal); + XMVECTOR normal = XMVector3Cross(XMVectorSubtract(verts[v1].v, verts[v0].v), XMVectorSubtract(verts[v2].v, verts[v0].v)); + normal = XMVector3Normalize(normal); const size_t base = vertices.size(); index_push_back(indices, base); @@ -1116,7 +1122,6 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in assert(indices.size() == 20 * 3); } - //-------------------------------------------------------------------------------------- // Teapot //-------------------------------------------------------------------------------------- @@ -1127,7 +1132,12 @@ namespace #include "TeapotData.inc" // Tessellates the specified bezier patch. - void XM_CALLCONV TessellatePatch(VertexCollection& vertices, IndexCollection& indices, TeapotPatch const& patch, size_t tessellation, FXMVECTOR scale, bool isMirrored) + void XM_CALLCONV TessellatePatch(VertexCollection& vertices, + IndexCollection& indices, + TeapotPatch const& patch, + size_t tessellation, + FXMVECTOR scale, + bool isMirrored) { // Look up the 16 control points for this patch. XMVECTOR controlPoints[16] = {}; @@ -1139,19 +1149,23 @@ namespace // Create the index data. size_t vbase = vertices.size(); - Bezier::CreatePatchIndices(tessellation, isMirrored, [&](size_t index) + Bezier::CreatePatchIndices(tessellation, + isMirrored, + [&](size_t index) { index_push_back(indices, vbase + index); }); // Create the vertex data. - Bezier::CreatePatchVertices(controlPoints, tessellation, isMirrored, [&](FXMVECTOR position, FXMVECTOR normal, FXMVECTOR textureCoordinate) + Bezier::CreatePatchVertices(controlPoints, + tessellation, + isMirrored, + [&](FXMVECTOR position, FXMVECTOR normal, FXMVECTOR textureCoordinate) { vertices.push_back(VertexPositionNormalTexture(position, normal, textureCoordinate)); }); } -} - +} // namespace // Creates a teapot primitive. void DirectX::ComputeTeapot(VertexCollection& vertices, IndexCollection& indices, float size, size_t tessellation, bool rhcoords) @@ -1164,8 +1178,8 @@ void DirectX::ComputeTeapot(VertexCollection& vertices, IndexCollection& indices const XMVECTOR scaleVector = XMVectorReplicate(size); - const XMVECTOR scaleNegateX = XMVectorMultiply(scaleVector, g_XMNegateX); - const XMVECTOR scaleNegateZ = XMVectorMultiply(scaleVector, g_XMNegateZ); + const XMVECTOR scaleNegateX = XMVectorMultiply(scaleVector, g_XMNegateX); + const XMVECTOR scaleNegateZ = XMVectorMultiply(scaleVector, g_XMNegateZ); const XMVECTOR scaleNegateXZ = XMVectorMultiply(scaleVector, XMVectorMultiply(g_XMNegateX, g_XMNegateZ)); for (size_t i = 0; i < std::size(TeapotPatches); i++) diff --git a/Src/Geometry.h b/Src/Geometry.h index 08bd8565..4ae4546b 100644 --- a/Src/Geometry.h +++ b/Src/Geometry.h @@ -13,17 +13,21 @@ namespace DirectX { using VertexCollection = std::vector; - using IndexCollection = std::vector; + using IndexCollection = std::vector; void ComputeBox(VertexCollection& vertices, IndexCollection& indices, const XMFLOAT3& size, bool rhcoords, bool invertn); - void ComputeSphere(VertexCollection& vertices, IndexCollection& indices, float diameter, size_t tessellation, bool rhcoords, bool invertn); + void + ComputeSphere(VertexCollection& vertices, IndexCollection& indices, float diameter, size_t tessellation, bool rhcoords, bool invertn); void ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indices, float diameter, size_t tessellation, bool rhcoords); - void ComputeCylinder(VertexCollection& vertices, IndexCollection& indices, float height, float diameter, size_t tessellation, bool rhcoords); - void ComputeCone(VertexCollection& vertices, IndexCollection& indices, float diameter, float height, size_t tessellation, bool rhcoords); - void ComputeTorus(VertexCollection& vertices, IndexCollection& indices, float diameter, float thickness, size_t tessellation, bool rhcoords); + void + ComputeCylinder(VertexCollection& vertices, IndexCollection& indices, float height, float diameter, size_t tessellation, bool rhcoords); + void + ComputeCone(VertexCollection& vertices, IndexCollection& indices, float diameter, float height, size_t tessellation, bool rhcoords); + void + ComputeTorus(VertexCollection& vertices, IndexCollection& indices, float diameter, float thickness, size_t tessellation, bool rhcoords); void ComputeTetrahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords); void ComputeOctahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords); void ComputeDodecahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords); void ComputeIcosahedron(VertexCollection& vertices, IndexCollection& indices, float size, bool rhcoords); void ComputeTeapot(VertexCollection& vertices, IndexCollection& indices, float size, size_t tessellation, bool rhcoords); -} +} // namespace DirectX diff --git a/Src/GraphicsMemory.cpp b/Src/GraphicsMemory.cpp index b58c934a..0209ceff 100644 --- a/Src/GraphicsMemory.cpp +++ b/Src/GraphicsMemory.cpp @@ -23,11 +23,11 @@ using ScopedLock = std::lock_guard; namespace { - constexpr size_t MinPageSize = 64 * 1024; - constexpr size_t MinAllocSize = 4 * 1024; + constexpr size_t MinPageSize = 64 * 1024; + constexpr size_t MinAllocSize = 4 * 1024; constexpr size_t AllocatorIndexShift = 12; // start block sizes at 4KB - constexpr size_t AllocatorPoolCount = 21; // allocation sizes up to 2GB supported - constexpr size_t PoolIndexScale = 1; // multiply the allocation size this amount to push large values into the next bucket + constexpr size_t AllocatorPoolCount = 21; // allocation sizes up to 2GB supported + constexpr size_t PoolIndexScale = 1; // multiply the allocation size this amount to push large values into the next bucket static_assert((1 << AllocatorIndexShift) == MinAllocSize, "1 << AllocatorIndexShift must == MinPageSize (in KiB)"); static_assert((MinPageSize & (MinPageSize - 1)) == 0, "MinPageSize size must be a power of 2"); @@ -42,9 +42,9 @@ namespace x |= x >> 4; x |= x >> 8; x |= x >> 16; - #ifdef _WIN64 +#ifdef _WIN64 x |= x >> 32; - #endif +#endif return ++x; } @@ -59,26 +59,26 @@ namespace // etc... // Need to convert to an index. - #ifdef _MSC_VER +#ifdef _MSC_VER unsigned long bitIndex = 0; - #ifdef _WIN64 +#ifdef _WIN64 return _BitScanForward64(&bitIndex, allocatorPageSize) ? bitIndex + 1 : 0; - #else +#else return _BitScanForward(&bitIndex, static_cast(allocatorPageSize)) ? bitIndex + 1 : 0; - #endif +#endif - #elif defined(__GNUC__) +#elif defined(__GNUC__) - #ifdef __LP64__ +#ifdef __LP64__ return static_cast(__builtin_ffsll(static_cast(allocatorPageSize))); - #else +#else return static_cast(__builtin_ffs(static_cast(allocatorPageSize))); - #endif +#endif - #else - #error Unknown forward bit-scan syntax - #endif +#else +#error Unknown forward bit-scan syntax +#endif } inline size_t GetPageSizeFromPoolIndex(size_t x) noexcept @@ -102,17 +102,15 @@ namespace for (size_t i = 0; i < mPools.size(); ++i) { size_t pageSize = GetPageSizeFromPoolIndex(i); - mPools[i] = std::make_unique( - mDevice.Get(), - pageSize); + mPools[i] = std::make_unique(mDevice.Get(), pageSize); } } - DeviceAllocator(DeviceAllocator&&) = delete; - DeviceAllocator& operator= (DeviceAllocator&&) = delete; + DeviceAllocator(DeviceAllocator&&) = delete; + DeviceAllocator& operator=(DeviceAllocator&&) = delete; - DeviceAllocator(DeviceAllocator const&) = delete; - DeviceAllocator& operator= (DeviceAllocator const&) = delete; + DeviceAllocator(DeviceAllocator const&) = delete; + DeviceAllocator& operator=(DeviceAllocator const&) = delete; // Explicitly destroy LinearAllocators inside a critical section ~DeviceAllocator() @@ -130,7 +128,7 @@ namespace ScopedLock lock(mMutex); // Which memory pool does it live in? - const size_t poolSize = NextPow2((alignment + size) * PoolIndexScale); + const size_t poolSize = NextPow2((alignment + size) * PoolIndexScale); const size_t poolIndex = GetPoolIndexFromSize(poolSize); assert(poolIndex < mPools.size()); @@ -149,8 +147,7 @@ namespace size_t offset = page->Suballocate(size, alignment); // Return the information to the user - return GraphicsResource( - page, + return GraphicsResource(page, page->GpuAddress() + offset, page->UploadResource(), static_cast(page->BaseMemory()) + offset, @@ -188,9 +185,9 @@ namespace void GetStatistics(GraphicsMemoryStatistics& stats) const { - size_t totalPageCount = 0; + size_t totalPageCount = 0; size_t committedMemoryUsage = 0; - size_t totalMemoryUsage = 0; + size_t totalMemoryUsage = 0; ScopedLock lock(mMutex); @@ -204,18 +201,18 @@ namespace } } - stats = {}; + stats = {}; stats.committedMemory = committedMemoryUsage; - stats.totalMemory = totalMemoryUsage; - stats.totalPages = totalPageCount; + stats.totalMemory = totalMemoryUsage; + stats.totalPages = totalPageCount; } ID3D12Device* GetDevice() const noexcept { return mDevice.Get(); } private: - ComPtr mDevice; + ComPtr mDevice; std::array, AllocatorPoolCount> mPools; - mutable std::mutex mMutex; + mutable std::mutex mMutex; }; #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS @@ -223,7 +220,6 @@ namespace #endif } // anonymous namespace - //-------------------------------------------------------------------------------------- // GraphicsMemory::Impl //-------------------------------------------------------------------------------------- @@ -232,12 +228,12 @@ class GraphicsMemory::Impl { public: Impl(GraphicsMemory* owner) noexcept(false) - : mOwner(owner) - , m_peakCommited(0) - , m_peakBytes(0) - , m_peakPages(0) + : mOwner(owner), + m_peakCommited(0), + m_peakBytes(0), + m_peakPages(0) { - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) if (s_graphicsMemory) { throw std::logic_error("GraphicsMemory is a singleton"); @@ -245,28 +241,28 @@ class GraphicsMemory::Impl s_graphicsMemory = this; - #endif - #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS +#endif +#ifdef USING_PIX_CUSTOM_MEMORY_EVENTS DebugTrace("INFO: GraphicsMemory PIX custom memory tracking events enabled (Allocator ID %u)\n", c_PIXAllocatorID); - #endif +#endif } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() { - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) s_graphicsMemory = nullptr; - #else +#else if (mDeviceAllocator && mDeviceAllocator->GetDevice()) { s_graphicsMemory.erase(mDeviceAllocator->GetDevice()); } - #endif +#endif mDeviceAllocator.reset(); } @@ -274,29 +270,20 @@ class GraphicsMemory::Impl { mDeviceAllocator = std::make_unique(device); - #if !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) +#if !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) if (s_graphicsMemory.find(device) != s_graphicsMemory.cend()) { throw std::logic_error("GraphicsMemory is a per-device singleton"); } s_graphicsMemory[device] = this; - #endif +#endif } - GraphicsResource Allocate(size_t size, size_t alignment) - { - return mDeviceAllocator->Alloc(size, alignment); - } + GraphicsResource Allocate(size_t size, size_t alignment) { return mDeviceAllocator->Alloc(size, alignment); } - void Commit(_In_ ID3D12CommandQueue* commandQueue) - { - mDeviceAllocator->KickFences(commandQueue); - } + void Commit(_In_ ID3D12CommandQueue* commandQueue) { mDeviceAllocator->KickFences(commandQueue); } - void GarbageCollect() - { - mDeviceAllocator->GarbageCollect(); - } + void GarbageCollect() { mDeviceAllocator->GarbageCollect(); } void GetStatistics(GraphicsMemoryStatistics& stats) { @@ -324,8 +311,8 @@ class GraphicsMemory::Impl void ResetStatistics() { m_peakCommited = 0; - m_peakBytes = 0; - m_peakPages = 0; + m_peakBytes = 0; + m_peakPages = 0; } ID3D12Device* GetDevice() const noexcept { return mDeviceAllocator ? mDeviceAllocator->GetDevice() : nullptr; } @@ -340,9 +327,9 @@ class GraphicsMemory::Impl private: std::unique_ptr mDeviceAllocator; - size_t m_peakCommited; - size_t m_peakBytes; - size_t m_peakPages; + size_t m_peakCommited; + size_t m_peakBytes; + size_t m_peakPages; }; #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) @@ -351,7 +338,6 @@ GraphicsMemory::Impl* GraphicsMemory::Impl::s_graphicsMemory = nullptr; std::map GraphicsMemory::Impl::s_graphicsMemory; #endif - //-------------------------------------------------------------------------------------- // GraphicsMemory //-------------------------------------------------------------------------------------- @@ -363,7 +349,6 @@ GraphicsMemory::GraphicsMemory(_In_ ID3D12Device* device) pImpl->Initialize(device); } - // Move constructor. GraphicsMemory::GraphicsMemory(GraphicsMemory&& moveFrom) noexcept : pImpl(std::move(moveFrom.pImpl)) @@ -371,33 +356,28 @@ GraphicsMemory::GraphicsMemory(GraphicsMemory&& moveFrom) noexcept pImpl->mOwner = this; } - // Move assignment. -GraphicsMemory& GraphicsMemory::operator= (GraphicsMemory&& moveFrom) noexcept +GraphicsMemory& GraphicsMemory::operator=(GraphicsMemory&& moveFrom) noexcept { - pImpl = std::move(moveFrom.pImpl); + pImpl = std::move(moveFrom.pImpl); pImpl->mOwner = this; return *this; } - // Public destructor. GraphicsMemory::~GraphicsMemory() = default; - GraphicsResource GraphicsMemory::AllocateImpl(size_t size, size_t alignment) { assert(alignment >= 4); // Should use at least DWORD alignment return pImpl->Allocate(size, alignment); } - void GraphicsMemory::Commit(_In_ ID3D12CommandQueue* commandQueue) { pImpl->Commit(commandQueue); } - void GraphicsMemory::GarbageCollect() { pImpl->GarbageCollect(); @@ -458,53 +438,50 @@ GraphicsMemory& GraphicsMemory::Get(_In_opt_ ID3D12Device* device) #endif #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS -__declspec(allocator) -void* GraphicsMemory::ReportCustomMemoryAlloc(void* pMem, size_t size, UINT64 metadata) +__declspec(allocator) void* GraphicsMemory::ReportCustomMemoryAlloc(void* pMem, size_t size, UINT64 metadata) { PIXRecordMemoryAllocationEvent(c_PIXAllocatorID, pMem, size, metadata); return pMem; } #endif - //-------------------------------------------------------------------------------------- // GraphicsResource smart-pointer interface //-------------------------------------------------------------------------------------- GraphicsResource::GraphicsResource() noexcept - : mPage(nullptr) - , mGpuAddress{} - , mResource(nullptr) - , mMemory(nullptr) - , mBufferOffset(0) - , mSize(0) + : mPage(nullptr), + mGpuAddress{}, + mResource(nullptr), + mMemory(nullptr), + mBufferOffset(0), + mSize(0) {} -GraphicsResource::GraphicsResource( - _In_ LinearAllocatorPage* page, - _In_ D3D12_GPU_VIRTUAL_ADDRESS gpuAddress, - _In_ ID3D12Resource* resource, - _In_ void* memory, - _In_ size_t offset, - _In_ size_t size) noexcept - : mPage(page) - , mGpuAddress(gpuAddress) - , mResource(resource) - , mMemory(memory) - , mBufferOffset(offset) - , mSize(size) +GraphicsResource::GraphicsResource(_In_ LinearAllocatorPage* page, + _In_ D3D12_GPU_VIRTUAL_ADDRESS gpuAddress, + _In_ ID3D12Resource* resource, + _In_ void* memory, + _In_ size_t offset, + _In_ size_t size) noexcept + : mPage(page), + mGpuAddress(gpuAddress), + mResource(resource), + mMemory(memory), + mBufferOffset(offset), + mSize(size) { assert(mPage != nullptr); mPage->AddRef(); } GraphicsResource::GraphicsResource(GraphicsResource&& other) noexcept - : mPage(nullptr) - , mGpuAddress{} - , mResource(nullptr) - , mMemory(nullptr) - , mBufferOffset(0) - , mSize(0) + : mPage(nullptr), + mGpuAddress{}, + mResource(nullptr), + mMemory(nullptr), + mBufferOffset(0), + mSize(0) { Reset(std::move(other)); } @@ -513,16 +490,16 @@ GraphicsResource::~GraphicsResource() { if (mPage) { - #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS +#ifdef USING_PIX_CUSTOM_MEMORY_EVENTS PIXRecordMemoryFreeEvent(c_PIXAllocatorID, reinterpret_cast(mGpuAddress), mSize, 0); - #endif +#endif mPage->Release(); mPage = nullptr; } } -GraphicsResource&& GraphicsResource::operator= (GraphicsResource&& other) noexcept +GraphicsResource&& GraphicsResource::operator=(GraphicsResource&& other) noexcept { Reset(std::move(other)); return std::move(*this); @@ -532,49 +509,48 @@ void GraphicsResource::Reset() noexcept { if (mPage) { - #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS +#ifdef USING_PIX_CUSTOM_MEMORY_EVENTS PIXRecordMemoryFreeEvent(c_PIXAllocatorID, reinterpret_cast(mGpuAddress), mSize, 0); - #endif +#endif mPage->Release(); mPage = nullptr; } - mGpuAddress = {}; - mResource = nullptr; - mMemory = nullptr; + mGpuAddress = {}; + mResource = nullptr; + mMemory = nullptr; mBufferOffset = 0; - mSize = 0; + mSize = 0; } void GraphicsResource::Reset(GraphicsResource&& alloc) noexcept { if (mPage) { - #ifdef USING_PIX_CUSTOM_MEMORY_EVENTS +#ifdef USING_PIX_CUSTOM_MEMORY_EVENTS PIXRecordMemoryFreeEvent(c_PIXAllocatorID, reinterpret_cast(mGpuAddress), mSize, 0); - #endif +#endif mPage->Release(); mPage = nullptr; } - mGpuAddress = alloc.GpuAddress(); - mResource = alloc.Resource(); - mMemory = alloc.Memory(); + mGpuAddress = alloc.GpuAddress(); + mResource = alloc.Resource(); + mMemory = alloc.Memory(); mBufferOffset = alloc.ResourceOffset(); - mSize = alloc.Size(); - mPage = alloc.mPage; + mSize = alloc.Size(); + mPage = alloc.mPage; - alloc.mGpuAddress = {}; - alloc.mResource = nullptr; - alloc.mMemory = nullptr; + alloc.mGpuAddress = {}; + alloc.mResource = nullptr; + alloc.mMemory = nullptr; alloc.mBufferOffset = 0; - alloc.mSize = 0; - alloc.mPage = nullptr; + alloc.mSize = 0; + alloc.mPage = nullptr; } - //-------------------------------------------------------------------------------------- // SharedGraphicsResource //-------------------------------------------------------------------------------------- @@ -595,22 +571,21 @@ SharedGraphicsResource::SharedGraphicsResource(const SharedGraphicsResource& res : mSharedResource(resource.mSharedResource) {} -SharedGraphicsResource::~SharedGraphicsResource() -{} +SharedGraphicsResource::~SharedGraphicsResource() {} -SharedGraphicsResource&& SharedGraphicsResource::operator= (SharedGraphicsResource&& resource) noexcept +SharedGraphicsResource&& SharedGraphicsResource::operator=(SharedGraphicsResource&& resource) noexcept { mSharedResource = std::move(resource.mSharedResource); return std::move(*this); } -SharedGraphicsResource&& SharedGraphicsResource::operator= (GraphicsResource&& resource) +SharedGraphicsResource&& SharedGraphicsResource::operator=(GraphicsResource&& resource) { mSharedResource = std::make_shared(std::move(resource)); return std::move(*this); } -SharedGraphicsResource& SharedGraphicsResource::operator= (const SharedGraphicsResource& resource) noexcept +SharedGraphicsResource& SharedGraphicsResource::operator=(const SharedGraphicsResource& resource) noexcept { mSharedResource = resource.mSharedResource; return *this; diff --git a/Src/Keyboard.cpp b/Src/Keyboard.cpp index deeead9c..98f3143e 100644 --- a/Src/Keyboard.cpp +++ b/Src/Keyboard.cpp @@ -45,8 +45,7 @@ namespace const unsigned int bf = 1u << (key & 0x1f); ptr[(key >> 5)] &= ~bf; } -} - +} // namespace #pragma region Implementations #ifdef USING_GAMEINPUT @@ -63,7 +62,7 @@ using namespace GameInput::v2; using namespace GameInput::v3; #endif -using GameInputCreateFn = HRESULT(*)(IGameInput**); +using GameInputCreateFn = HRESULT (*)(IGameInput**); #ifdef __clang__ #pragma clang diagnostic ignored "-Wmicrosoft-cast" @@ -72,11 +71,11 @@ using GameInputCreateFn = HRESULT(*)(IGameInput**); class Keyboard::Impl { public: - Impl(Keyboard* owner) : - mOwner(owner), - mConnected(0), - mDeviceToken(0), - mKeyState{} + Impl(Keyboard* owner) + : mOwner(owner), + mConnected(0), + mDeviceToken(0), + mKeyState{} { if (s_keyboard) { @@ -85,15 +84,16 @@ class Keyboard::Impl s_keyboard = this; - #if defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION) +#if defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION) HRESULT hr = GameInputCreate(mGameInput.GetAddressOf()); - #else +#else if (!s_gameInputCreate) { s_gameInputModule = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (s_gameInputModule) { - s_gameInputCreate = reinterpret_cast(reinterpret_cast(GetProcAddress(s_gameInputModule, "GameInputCreate"))); + s_gameInputCreate + = reinterpret_cast(reinterpret_cast(GetProcAddress(s_gameInputModule, "GameInputCreate"))); } if (!s_gameInputCreate) @@ -104,11 +104,10 @@ class Keyboard::Impl } HRESULT hr = s_gameInputCreate(mGameInput.GetAddressOf()); - #endif +#endif if (SUCCEEDED(hr)) { - ThrowIfFailed(mGameInput->RegisterDeviceCallback( - nullptr, + ThrowIfFailed(mGameInput->RegisterDeviceCallback(nullptr, GameInputKindKeyboard, GameInputDeviceConnected, GameInputBlockingEnumeration, @@ -119,21 +118,21 @@ class Keyboard::Impl else { DebugTrace("ERROR: GameInputCreate [keyboard] failed with %08X\n", static_cast(hr)); - #ifdef _GAMING_XBOX +#ifdef _GAMING_XBOX throw com_exception(hr); - #else +#else DebugTrace( "\t**** Install the latest GameInputRedist package on this system. ****\n" "\t**** NOTE: All calls to GetState will be reported as 'not connected'. ****\n"); - #endif +#endif } } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() { @@ -141,11 +140,11 @@ class Keyboard::Impl { if (mGameInput) { - #if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) +#if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) if (!mGameInput->UnregisterCallback(mDeviceToken)) - #else +#else if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) - #endif +#endif { DebugTrace("ERROR: GameInput::UnregisterCallback [keyboard] failed"); } @@ -179,7 +178,7 @@ class Keyboard::Impl { case 0xe036: vk = VK_RSHIFT; break; case 0xe045: vk = VK_NUMLOCK; break; - default: break; + default: break; } } @@ -188,39 +187,34 @@ class Keyboard::Impl } } - void Reset() noexcept - {} + void Reset() noexcept {} - bool IsConnected() const - { - return mConnected > 0; - } + bool IsConnected() const { return mConnected > 0; } - Keyboard* mOwner; - uint32_t mConnected; + Keyboard* mOwner; + uint32_t mConnected; static Keyboard::Impl* s_keyboard; private: - static constexpr size_t c_MaxSimultaneousKeys = 16; + static constexpr size_t c_MaxSimultaneousKeys = 16; - ComPtr mGameInput; - GameInputCallbackToken mDeviceToken; + ComPtr mGameInput; + GameInputCallbackToken mDeviceToken; - mutable GameInputKeyState mKeyState[c_MaxSimultaneousKeys]; + mutable GameInputKeyState mKeyState[c_MaxSimultaneousKeys]; - static void CALLBACK OnGameInputDevice( - _In_ GameInputCallbackToken, - _In_ void * context, - _In_ IGameInputDevice *, - _In_ uint64_t, + static void CALLBACK OnGameInputDevice(_In_ GameInputCallbackToken, + _In_ void* context, + _In_ IGameInputDevice*, + _In_ uint64_t, _In_ GameInputDeviceStatus currentStatus, _In_ GameInputDeviceStatus previousStatus) noexcept { auto impl = reinterpret_cast(context); const bool wasConnected = (previousStatus & GameInputDeviceConnected) != 0; - const bool isConnected = (currentStatus & GameInputDeviceConnected) != 0; + const bool isConnected = (currentStatus & GameInputDeviceConnected) != 0; if (isConnected && !wasConnected) { @@ -233,7 +227,7 @@ class Keyboard::Impl } #if !defined(_GAMING_XBOX) && !defined(GAMEINPUT_API_VERSION) - static HMODULE s_gameInputModule; + static HMODULE s_gameInputModule; static GameInputCreateFn s_gameInputCreate; #endif }; @@ -241,7 +235,7 @@ class Keyboard::Impl Keyboard::Impl* Keyboard::Impl::s_keyboard = nullptr; #if !defined(_GAMING_XBOX) && !defined(GAMEINPUT_API_VERSION) -HMODULE Keyboard::Impl::s_gameInputModule = nullptr; +HMODULE Keyboard::Impl::s_gameInputModule = nullptr; GameInputCreateFn Keyboard::Impl::s_gameInputCreate = nullptr; #endif @@ -250,7 +244,6 @@ void Keyboard::ProcessMessage(UINT, WPARAM, LPARAM) noexcept // GameInput for Keyboard doesn't require Win32 messages, but this simplifies integration. } - #elif defined(USING_COREWINDOW) //====================================================================================== @@ -271,11 +264,11 @@ void Keyboard::ProcessMessage(UINT, WPARAM, LPARAM) noexcept class Keyboard::Impl { public: - Impl(Keyboard* owner) : - mState{}, - mOwner(owner), - mAcceleratorKeyToken{}, - mActivatedToken{} + Impl(Keyboard* owner) + : mState{}, + mOwner(owner), + mAcceleratorKeyToken{}, + mActivatedToken{} { if (s_keyboard) { @@ -292,15 +285,9 @@ class Keyboard::Impl RemoveHandlers(); } - void GetState(State& state) const - { - memcpy(&state, &mState, sizeof(State)); - } + void GetState(State& state) const { memcpy(&state, &mState, sizeof(State)); } - void Reset() noexcept - { - memset(&mState, 0, sizeof(State)); - } + void Reset() noexcept { memset(&mState, 0, sizeof(State)); } bool IsConnected() const { @@ -350,13 +337,14 @@ class Keyboard::Impl hr = dispatcher.As(&keys); ThrowIfFailed(hr); - typedef __FITypedEventHandler_2_Windows__CUI__CCore__CCoreDispatcher_Windows__CUI__CCore__CAcceleratorKeyEventArgs AcceleratorKeyHandler; + typedef __FITypedEventHandler_2_Windows__CUI__CCore__CCoreDispatcher_Windows__CUI__CCore__CAcceleratorKeyEventArgs + AcceleratorKeyHandler; hr = keys->add_AcceleratorKeyActivated(Callback(AcceleratorKeyEvent).Get(), &mAcceleratorKeyToken); ThrowIfFailed(hr); } - State mState; - Keyboard* mOwner; + State mState; + Keyboard* mOwner; static Keyboard::Impl* s_keyboard; @@ -373,17 +361,17 @@ class Keyboard::Impl using namespace ABI::Windows::UI::Core; ComPtr dispatcher; - HRESULT hr = mWindow->get_Dispatcher(dispatcher.GetAddressOf()); + HRESULT hr = mWindow->get_Dispatcher(dispatcher.GetAddressOf()); ThrowIfFailed(hr); - std::ignore = mWindow->remove_Activated(mActivatedToken); + std::ignore = mWindow->remove_Activated(mActivatedToken); mActivatedToken.value = 0; ComPtr keys; hr = dispatcher.As(&keys); ThrowIfFailed(hr); - std::ignore = keys->remove_AcceleratorKeyActivated(mAcceleratorKeyToken); + std::ignore = keys->remove_AcceleratorKeyActivated(mAcceleratorKeyToken); mAcceleratorKeyToken.value = 0; } } @@ -411,7 +399,7 @@ class Keyboard::Impl return S_OK; CoreAcceleratorKeyEventType evtType; - HRESULT hr = args->get_EventType(&evtType); + HRESULT hr = args->get_EventType(&evtType); ThrowIfFailed(hr); bool down = false; @@ -419,16 +407,12 @@ class Keyboard::Impl switch (evtType) { case CoreAcceleratorKeyEventType_KeyDown: - case CoreAcceleratorKeyEventType_SystemKeyDown: - down = true; - break; + case CoreAcceleratorKeyEventType_SystemKeyDown: down = true; break; case CoreAcceleratorKeyEventType_KeyUp: - case CoreAcceleratorKeyEventType_SystemKeyUp: - break; + case CoreAcceleratorKeyEventType_SystemKeyUp: break; - default: - return S_OK; + default: return S_OK; } CorePhysicalKeyStatus status; @@ -453,13 +437,9 @@ class Keyboard::Impl } break; - case VK_CONTROL: - vk = (status.IsExtendedKey) ? VK_RCONTROL : VK_LCONTROL; - break; + case VK_CONTROL: vk = (status.IsExtendedKey) ? VK_RCONTROL : VK_LCONTROL; break; - case VK_MENU: - vk = (status.IsExtendedKey) ? VK_RMENU : VK_LMENU; - break; + case VK_MENU: vk = (status.IsExtendedKey) ? VK_RMENU : VK_LMENU; break; } if (down) @@ -475,16 +455,13 @@ class Keyboard::Impl } }; - Keyboard::Impl* Keyboard::Impl::s_keyboard = nullptr; - void Keyboard::SetWindow(ABI::Windows::UI::Core::ICoreWindow* window) { pImpl->SetWindow(window); } - #else //====================================================================================== @@ -518,9 +495,9 @@ void Keyboard::SetWindow(ABI::Windows::UI::Core::ICoreWindow* window) class Keyboard::Impl { public: - Impl(Keyboard* owner) : - mState{}, - mOwner(owner) + Impl(Keyboard* owner) + : mState{}, + mOwner(owner) { if (s_keyboard) { @@ -530,42 +507,28 @@ class Keyboard::Impl s_keyboard = this; } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; - ~Impl() - { - s_keyboard = nullptr; - } + ~Impl() { s_keyboard = nullptr; } - void GetState(State& state) const - { - memcpy(&state, &mState, sizeof(State)); - } + void GetState(State& state) const { memcpy(&state, &mState, sizeof(State)); } - void Reset() noexcept - { - memset(&mState, 0, sizeof(State)); - } + void Reset() noexcept { memset(&mState, 0, sizeof(State)); } - bool IsConnected() const - { - return true; - } + bool IsConnected() const { return true; } - State mState; - Keyboard* mOwner; + State mState; + Keyboard* mOwner; static Keyboard::Impl* s_keyboard; }; - Keyboard::Impl* Keyboard::Impl::s_keyboard = nullptr; - void Keyboard::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) noexcept { auto pImpl = Impl::s_keyboard; @@ -578,21 +541,15 @@ void Keyboard::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) noexce switch (message) { case WM_ACTIVATE: - case WM_ACTIVATEAPP: - pImpl->Reset(); - return; + case WM_ACTIVATEAPP: pImpl->Reset(); return; case WM_KEYDOWN: - case WM_SYSKEYDOWN: - down = true; - break; + case WM_SYSKEYDOWN: down = true; break; case WM_KEYUP: - case WM_SYSKEYUP: - break; + case WM_SYSKEYUP: break; - default: - return; + default: return; } int vk = LOWORD(wParam); @@ -601,23 +558,21 @@ void Keyboard::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) noexce { case VK_SHIFT: case VK_CONTROL: - case VK_MENU: + case VK_MENU: { + if (vk == VK_SHIFT && !down) { - if (vk == VK_SHIFT && !down) - { - // Workaround to ensure left vs. right shift get cleared when both were pressed at same time - KeyUp(VK_LSHIFT, pImpl->mState); - KeyUp(VK_RSHIFT, pImpl->mState); - } - - bool isExtendedKey = (HIWORD(lParam) & KF_EXTENDED) == KF_EXTENDED; - int scanCode = LOBYTE(HIWORD(lParam)) | (isExtendedKey ? 0xe000 : 0); - vk = LOWORD(MapVirtualKeyW(static_cast(scanCode), MAPVK_VSC_TO_VK_EX)); + // Workaround to ensure left vs. right shift get cleared when both were pressed at same time + KeyUp(VK_LSHIFT, pImpl->mState); + KeyUp(VK_RSHIFT, pImpl->mState); } - break; - default: - break; + bool isExtendedKey = (HIWORD(lParam) & KF_EXTENDED) == KF_EXTENDED; + int scanCode = LOBYTE(HIWORD(lParam)) | (isExtendedKey ? 0xe000 : 0); + vk = LOWORD(MapVirtualKeyW(static_cast(scanCode), MAPVK_VSC_TO_VK_EX)); + } + break; + + default: break; } if (down) @@ -634,7 +589,7 @@ void Keyboard::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) noexce #pragma endregion #ifdef _MSC_VER -#pragma warning( disable : 4355 ) +#pragma warning(disable : 4355) #endif // Public constructor. @@ -642,7 +597,6 @@ Keyboard::Keyboard() noexcept(false) : pImpl(std::make_unique(this)) {} - // Move constructor. Keyboard::Keyboard(Keyboard&& moveFrom) noexcept : pImpl(std::move(moveFrom.pImpl)) @@ -650,20 +604,17 @@ Keyboard::Keyboard(Keyboard&& moveFrom) noexcept pImpl->mOwner = this; } - // Move assignment. -Keyboard& Keyboard::operator= (Keyboard&& moveFrom) noexcept +Keyboard& Keyboard::operator=(Keyboard&& moveFrom) noexcept { - pImpl = std::move(moveFrom.pImpl); + pImpl = std::move(moveFrom.pImpl); pImpl->mOwner = this; return *this; } - // Public destructor. Keyboard::~Keyboard() = default; - Keyboard::State Keyboard::GetState() const { State state; @@ -671,13 +622,11 @@ Keyboard::State Keyboard::GetState() const return state; } - void Keyboard::Reset() noexcept { pImpl->Reset(); } - bool Keyboard::IsConnected() const { return pImpl->IsConnected(); @@ -691,21 +640,19 @@ Keyboard& Keyboard::Get() return *Impl::s_keyboard->mOwner; } - - //====================================================================================== // KeyboardStateTracker //====================================================================================== void Keyboard::KeyboardStateTracker::Update(const State& state) noexcept { - auto currPtr = reinterpret_cast(&state); - auto prevPtr = reinterpret_cast(&lastState); + auto currPtr = reinterpret_cast(&state); + auto prevPtr = reinterpret_cast(&lastState); auto releasedPtr = reinterpret_cast(&released); - auto pressedPtr = reinterpret_cast(&pressed); + auto pressedPtr = reinterpret_cast(&pressed); for (size_t j = 0; j < (256 / 32); ++j) { - *pressedPtr = *currPtr & ~(*prevPtr); + *pressedPtr = *currPtr & ~(*prevPtr); *releasedPtr = ~(*currPtr) & *prevPtr; ++currPtr; diff --git a/Src/LinearAllocator.cpp b/Src/LinearAllocator.cpp index 5989916a..db24ac14 100644 --- a/Src/LinearAllocator.cpp +++ b/Src/LinearAllocator.cpp @@ -16,21 +16,21 @@ #define VALIDATE_LISTS 0 #if VALIDATE_LISTS -# include +#include #endif using namespace DirectX; using Microsoft::WRL::ComPtr; LinearAllocatorPage::LinearAllocatorPage() noexcept - : pPrevPage(nullptr) - , pNextPage(nullptr) - , mMemory(nullptr) - , mPendingFence(0) - , mGpuAddress{} - , mOffset(0) - , mSize(0) - , mRefCount(1) + : pPrevPage(nullptr), + pNextPage(nullptr), + mMemory(nullptr), + mPendingFence(0), + mGpuAddress{}, + mOffset(0), + mSize(0), + mRefCount(1) {} size_t LinearAllocatorPage::Suballocate(_In_ size_t size, _In_ size_t alignment) @@ -57,20 +57,16 @@ void LinearAllocatorPage::Release() noexcept } } - //-------------------------------------------------------------------------------------- -LinearAllocator::LinearAllocator( - _In_ ID3D12Device* pDevice, - _In_ size_t pageSize, - _In_ size_t preallocateBytes) noexcept(false) - : m_pendingPages(nullptr) - , m_usedPages(nullptr) - , m_unusedPages(nullptr) - , m_increment(pageSize) - , m_numPending(0) - , m_totalPages(0) - , m_fenceCount(0) - , m_device(pDevice) +LinearAllocator::LinearAllocator(_In_ ID3D12Device* pDevice, _In_ size_t pageSize, _In_ size_t preallocateBytes) noexcept(false) + : m_pendingPages(nullptr), + m_usedPages(nullptr), + m_unusedPages(nullptr), + m_increment(pageSize), + m_numPending(0), + m_totalPages(0), + m_fenceCount(0), + m_device(pDevice) { assert(pDevice != nullptr); #if defined(_DEBUG) || defined(PROFILE) @@ -83,15 +79,13 @@ LinearAllocator::LinearAllocator( if (GetNewPage() == nullptr) { DebugTrace("LinearAllocator failed to preallocate pages (%zu required bytes, %zu pages)\n", - preallocatePageCount * m_increment, preallocatePageCount); + preallocatePageCount * m_increment, + preallocatePageCount); throw std::bad_alloc(); } } - ThrowIfFailed(pDevice->CreateFence( - 0, - D3D12_FENCE_FLAG_NONE, - IID_GRAPHICS_PPV_ARGS(m_fence.ReleaseAndGetAddressOf()))); + ThrowIfFailed(pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_GRAPHICS_PPV_ARGS(m_fence.ReleaseAndGetAddressOf()))); } LinearAllocator::~LinearAllocator() @@ -109,9 +103,9 @@ LinearAllocator::~LinearAllocator() FreePages(m_usedPages); m_pendingPages = nullptr; - m_usedPages = nullptr; - m_unusedPages = nullptr; - m_increment = 0; + m_usedPages = nullptr; + m_unusedPages = nullptr; + m_increment = 0; } LinearAllocatorPage* LinearAllocator::FindPageForAlloc(_In_ size_t size, _In_ size_t alignment) @@ -142,10 +136,10 @@ void LinearAllocator::FenceCommittedPages(_In_ ID3D12CommandQueue* commandQueue) return; // For all the used pages, fence them - UINT numReady = 0; - LinearAllocatorPage* readyPages = nullptr; + UINT numReady = 0; + LinearAllocatorPage* readyPages = nullptr; LinearAllocatorPage* unreadyPages = nullptr; - LinearAllocatorPage* nextPage = nullptr; + LinearAllocatorPage* nextPage = nullptr; for (auto page = m_usedPages; page != nullptr; page = nextPage) { nextPage = page->pNextPage; @@ -163,14 +157,16 @@ void LinearAllocator::FenceCommittedPages(_In_ ID3D12CommandQueue* commandQueue) // Link to the ready pages list page->pNextPage = readyPages; - if (readyPages) readyPages->pPrevPage = page; + if (readyPages) + readyPages->pPrevPage = page; readyPages = page; } else { // Link to the unready list page->pNextPage = unreadyPages; - if (unreadyPages) unreadyPages->pPrevPage = page; + if (unreadyPages) + unreadyPages->pPrevPage = page; unreadyPages = page; } } @@ -248,9 +244,7 @@ LinearAllocatorPage* LinearAllocator::GetCleanPageForAlloc() return page; } -LinearAllocatorPage* LinearAllocator::GetPageForAlloc( - size_t sizeBytes, - size_t alignment) +LinearAllocatorPage* LinearAllocator::GetPageForAlloc(size_t sizeBytes, size_t alignment) { // Fast path if (sizeBytes == m_increment && (alignment == 0 || alignment == m_increment)) @@ -268,10 +262,7 @@ LinearAllocatorPage* LinearAllocator::GetPageForAlloc( return page; } -LinearAllocatorPage* LinearAllocator::FindPageForAlloc( - LinearAllocatorPage* list, - size_t sizeBytes, - size_t alignment) noexcept +LinearAllocatorPage* LinearAllocator::FindPageForAlloc(LinearAllocatorPage* list, size_t sizeBytes, size_t alignment) noexcept { for (auto page = list; page != nullptr; page = page->pNextPage) { @@ -285,12 +276,11 @@ LinearAllocatorPage* LinearAllocator::FindPageForAlloc( LinearAllocatorPage* LinearAllocator::GetNewPage() { const CD3DX12_HEAP_PROPERTIES uploadHeapProperties(D3D12_HEAP_TYPE_UPLOAD); - const CD3DX12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(m_increment); + const CD3DX12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(m_increment); // Allocate the upload heap ComPtr spResource; - HRESULT hr = m_device->CreateCommittedResource( - &uploadHeapProperties, + HRESULT hr = m_device->CreateCommittedResource(&uploadHeapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, @@ -300,7 +290,8 @@ LinearAllocatorPage* LinearAllocator::GetNewPage() { if (hr != E_OUTOFMEMORY) { - DebugTrace("LinearAllocator::GetNewPage resource allocation failed due to unexpected error %08X\n", static_cast(hr)); + DebugTrace("LinearAllocator::GetNewPage resource allocation failed due to unexpected error %08X\n", + static_cast(hr)); } return nullptr; } @@ -315,15 +306,16 @@ LinearAllocatorPage* LinearAllocator::GetNewPage() memset(pMemory, 0, m_increment); // Add the page to the page list - auto page = new LinearAllocatorPage; - page->mMemory = pMemory; + auto page = new LinearAllocatorPage; + page->mMemory = pMemory; page->mGpuAddress = spResource->GetGPUVirtualAddress(); - page->mSize = m_increment; + page->mSize = m_increment; page->mUploadResource.Swap(spResource); // Set as head of the list page->pNextPage = m_unusedPages; - if (m_unusedPages) m_unusedPages->pPrevPage = page; + if (m_unusedPages) + m_unusedPages->pPrevPage = page; m_unusedPages = page; m_totalPages++; @@ -372,7 +364,8 @@ void LinearAllocator::LinkPageChain(LinearAllocatorPage* page, LinearAllocatorPa // Follow chain to the end and append LinearAllocatorPage* lastPage = nullptr; - for (lastPage = page; lastPage->pNextPage != nullptr; lastPage = lastPage->pNextPage) {} + for (lastPage = page; lastPage->pNextPage != nullptr; lastPage = lastPage->pNextPage) + {} lastPage->pNextPage = list; if (list) @@ -446,9 +439,7 @@ void LinearAllocator::FreePages(LinearAllocatorPage* page) noexcept #if VALIDATE_LISTS void LinearAllocator::ValidateList(LinearAllocatorPage* list) { - for (auto page = list, *lastPage = nullptr; - page != nullptr; - lastPage = page, page = page->pNextPage) + for (auto page = list, *lastPage = nullptr; page != nullptr; lastPage = page, page = page->pNextPage) { if (page->pPrevPage != lastPage) { @@ -468,8 +459,8 @@ void LinearAllocator::ValidatePageLists() #if defined(_DEBUG) || defined(PROFILE) void LinearAllocator::SetDebugName(const char* name) { - wchar_t wname[MAX_PATH] = {}; - const int result = MultiByteToWideChar(CP_UTF8, 0, name, static_cast(strlen(name)), wname, MAX_PATH); + wchar_t wname[MAX_PATH] = {}; + const int result = MultiByteToWideChar(CP_UTF8, 0, name, static_cast(strlen(name)), wname, MAX_PATH); if (result > 0) { SetDebugName(wname); diff --git a/Src/LinearAllocator.h b/Src/LinearAllocator.h index 2fc15577..d980bc66 100644 --- a/Src/LinearAllocator.h +++ b/Src/LinearAllocator.h @@ -44,7 +44,6 @@ #include - namespace DirectX { class LinearAllocatorPage @@ -52,39 +51,39 @@ namespace DirectX public: LinearAllocatorPage() noexcept; - LinearAllocatorPage(LinearAllocatorPage&&) = delete; - LinearAllocatorPage& operator= (LinearAllocatorPage&&) = delete; + LinearAllocatorPage(LinearAllocatorPage&&) = delete; + LinearAllocatorPage& operator=(LinearAllocatorPage&&) = delete; - LinearAllocatorPage(LinearAllocatorPage const&) = delete; + LinearAllocatorPage(LinearAllocatorPage const&) = delete; LinearAllocatorPage& operator=(LinearAllocatorPage const&) = delete; size_t Suballocate(_In_ size_t size, _In_ size_t alignment); - void* BaseMemory() const noexcept { return mMemory; } - ID3D12Resource* UploadResource() const noexcept { return mUploadResource.Get(); } + void* BaseMemory() const noexcept { return mMemory; } + ID3D12Resource* UploadResource() const noexcept { return mUploadResource.Get(); } D3D12_GPU_VIRTUAL_ADDRESS GpuAddress() const noexcept { return mGpuAddress; } - size_t BytesUsed() const noexcept { return mOffset; } - size_t Size() const noexcept { return mSize; } + size_t BytesUsed() const noexcept { return mOffset; } + size_t Size() const noexcept { return mSize; } - void AddRef() noexcept { mRefCount.fetch_add(1); } + void AddRef() noexcept { mRefCount.fetch_add(1); } int32_t RefCount() const noexcept { return mRefCount.load(); } - void Release() noexcept; + void Release() noexcept; protected: friend class LinearAllocator; - LinearAllocatorPage* pPrevPage; - LinearAllocatorPage* pNextPage; + LinearAllocatorPage* pPrevPage; + LinearAllocatorPage* pNextPage; - void* mMemory; - uint64_t mPendingFence; - D3D12_GPU_VIRTUAL_ADDRESS mGpuAddress; - size_t mOffset; - size_t mSize; - Microsoft::WRL::ComPtr mUploadResource; + void* mMemory; + uint64_t mPendingFence; + D3D12_GPU_VIRTUAL_ADDRESS mGpuAddress; + size_t mOffset; + size_t mSize; + Microsoft::WRL::ComPtr mUploadResource; private: - std::atomic mRefCount; + std::atomic mRefCount; }; class LinearAllocator @@ -93,15 +92,12 @@ namespace DirectX // These values will be rounded up to the nearest 64k. // You can specify zero for incrementalSizeBytes to increment // by 1 page (64k). - LinearAllocator( - _In_ ID3D12Device* pDevice, - _In_ size_t pageSize, - _In_ size_t preallocateBytes = 0) noexcept(false); + LinearAllocator(_In_ ID3D12Device* pDevice, _In_ size_t pageSize, _In_ size_t preallocateBytes = 0) noexcept(false); - LinearAllocator(LinearAllocator&&) = default; - LinearAllocator& operator= (LinearAllocator&&) = default; + LinearAllocator(LinearAllocator&&) = default; + LinearAllocator& operator=(LinearAllocator&&) = default; - LinearAllocator(LinearAllocator const&) = delete; + LinearAllocator(LinearAllocator const&) = delete; LinearAllocator& operator=(LinearAllocator const&) = delete; ~LinearAllocator(); @@ -125,23 +121,23 @@ namespace DirectX size_t TotalMemoryUsage() const noexcept { return m_totalPages * m_increment; } size_t PageSize() const noexcept { return m_increment; } - #if defined(_DEBUG) || defined(PROFILE) - // Debug info +#if defined(_DEBUG) || defined(PROFILE) + // Debug info const wchar_t* GetDebugName() const noexcept { return m_debugName.c_str(); } - void SetDebugName(const wchar_t* name); - void SetDebugName(const char* name); - #endif + void SetDebugName(const wchar_t* name); + void SetDebugName(const char* name); +#endif private: - LinearAllocatorPage* m_pendingPages; // Pages in use by the GPU - LinearAllocatorPage* m_usedPages; // Pages to be submitted to the GPU - LinearAllocatorPage* m_unusedPages; // Pages not being used right now - size_t m_increment; - size_t m_numPending; - size_t m_totalPages; - uint64_t m_fenceCount; - Microsoft::WRL::ComPtr m_device; - Microsoft::WRL::ComPtr m_fence; + LinearAllocatorPage* m_pendingPages; // Pages in use by the GPU + LinearAllocatorPage* m_usedPages; // Pages to be submitted to the GPU + LinearAllocatorPage* m_unusedPages; // Pages not being used right now + size_t m_increment; + size_t m_numPending; + size_t m_totalPages; + uint64_t m_fenceCount; + Microsoft::WRL::ComPtr m_device; + Microsoft::WRL::ComPtr m_fence; LinearAllocatorPage* GetPageForAlloc(size_t sizeBytes, size_t alignment); LinearAllocatorPage* GetCleanPageForAlloc(); @@ -156,13 +152,13 @@ namespace DirectX void ReleasePage(LinearAllocatorPage* page) noexcept; void FreePages(LinearAllocatorPage* list) noexcept; - #if defined(_DEBUG) || defined(PROFILE) +#if defined(_DEBUG) || defined(PROFILE) std::wstring m_debugName; static void ValidateList(LinearAllocatorPage* list); - void ValidatePageLists(); + void ValidatePageLists(); void SetPageDebugName(LinearAllocatorPage* list) noexcept; - #endif +#endif }; -} +} // namespace DirectX diff --git a/Src/LoaderHelpers.h b/Src/LoaderHelpers.h index 7b1f1d48..2d3a07ab 100644 --- a/Src/LoaderHelpers.h +++ b/Src/LoaderHelpers.h @@ -37,14 +37,12 @@ namespace DirectX case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_UINT: - case DXGI_FORMAT_R32G32B32A32_SINT: - return 128; + case DXGI_FORMAT_R32G32B32A32_SINT: return 128; case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R32G32B32_UINT: - case DXGI_FORMAT_R32G32B32_SINT: - return 96; + case DXGI_FORMAT_R32G32B32_SINT: return 96; case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: @@ -62,8 +60,7 @@ namespace DirectX case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: case DXGI_FORMAT_Y416: case DXGI_FORMAT_Y210: - case DXGI_FORMAT_Y216: - return 64; + case DXGI_FORMAT_Y216: return 64; case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: @@ -103,23 +100,23 @@ namespace DirectX case DXGI_FORMAT_AYUV: case DXGI_FORMAT_Y410: case DXGI_FORMAT_YUY2: - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) case DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT: case DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT: case DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM: - #endif +#endif return 32; case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: - #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) case DXGI_FORMAT_V408: - #endif - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#endif +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) case DXGI_FORMAT_D16_UNORM_S8_UINT: case DXGI_FORMAT_R16_UNORM_X8_TYPELESS: case DXGI_FORMAT_X16_TYPELESS_G8_UINT: - #endif +#endif return 24; case DXGI_FORMAT_R8G8_TYPELESS: @@ -138,16 +135,15 @@ namespace DirectX case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_A8P8: case DXGI_FORMAT_B4G4R4A4_UNORM: - #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) case DXGI_FORMAT_P208: case DXGI_FORMAT_V208: - #endif +#endif return 16; case DXGI_FORMAT_NV12: case DXGI_FORMAT_420_OPAQUE: - case DXGI_FORMAT_NV11: - return 12; + case DXGI_FORMAT_NV11: return 12; case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_R8_UNORM: @@ -173,26 +169,23 @@ namespace DirectX case DXGI_FORMAT_AI44: case DXGI_FORMAT_IA44: case DXGI_FORMAT_P8: - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) case DXGI_FORMAT_R4G4_UNORM: - #endif +#endif return 8; - case DXGI_FORMAT_R1_UNORM: - return 1; + case DXGI_FORMAT_R1_UNORM: return 1; case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: - case DXGI_FORMAT_BC4_SNORM: - return 4; + case DXGI_FORMAT_BC4_SNORM: return 4; case DXGI_FORMAT_UNKNOWN: case DXGI_FORMAT_FORCE_UINT: - default: - return 0; + default: return 0; } } @@ -201,29 +194,21 @@ namespace DirectX { switch (format) { - case DXGI_FORMAT_R8G8B8A8_UNORM: - return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + case DXGI_FORMAT_R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - case DXGI_FORMAT_BC1_UNORM: - return DXGI_FORMAT_BC1_UNORM_SRGB; + case DXGI_FORMAT_BC1_UNORM: return DXGI_FORMAT_BC1_UNORM_SRGB; - case DXGI_FORMAT_BC2_UNORM: - return DXGI_FORMAT_BC2_UNORM_SRGB; + case DXGI_FORMAT_BC2_UNORM: return DXGI_FORMAT_BC2_UNORM_SRGB; - case DXGI_FORMAT_BC3_UNORM: - return DXGI_FORMAT_BC3_UNORM_SRGB; + case DXGI_FORMAT_BC3_UNORM: return DXGI_FORMAT_BC3_UNORM_SRGB; - case DXGI_FORMAT_B8G8R8A8_UNORM: - return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; + case DXGI_FORMAT_B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; - case DXGI_FORMAT_B8G8R8X8_UNORM: - return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + case DXGI_FORMAT_B8G8R8X8_UNORM: return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; - case DXGI_FORMAT_BC7_UNORM: - return DXGI_FORMAT_BC7_UNORM_SRGB; + case DXGI_FORMAT_BC7_UNORM: return DXGI_FORMAT_BC7_UNORM_SRGB; - default: - return format; + default: return format; } } @@ -232,29 +217,21 @@ namespace DirectX { switch (format) { - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM; - case DXGI_FORMAT_BC1_UNORM_SRGB: - return DXGI_FORMAT_BC1_UNORM; + case DXGI_FORMAT_BC1_UNORM_SRGB: return DXGI_FORMAT_BC1_UNORM; - case DXGI_FORMAT_BC2_UNORM_SRGB: - return DXGI_FORMAT_BC2_UNORM; + case DXGI_FORMAT_BC2_UNORM_SRGB: return DXGI_FORMAT_BC2_UNORM; - case DXGI_FORMAT_BC3_UNORM_SRGB: - return DXGI_FORMAT_BC3_UNORM; + case DXGI_FORMAT_BC3_UNORM_SRGB: return DXGI_FORMAT_BC3_UNORM; - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM; - case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: - return DXGI_FORMAT_B8G8R8X8_UNORM; + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8X8_UNORM; - case DXGI_FORMAT_BC7_UNORM_SRGB: - return DXGI_FORMAT_BC7_UNORM; + case DXGI_FORMAT_BC7_UNORM_SRGB: return DXGI_FORMAT_BC7_UNORM; - default: - return format; + default: return format; } } @@ -283,11 +260,9 @@ namespace DirectX case DXGI_FORMAT_BC6H_SF16: case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: - case DXGI_FORMAT_BC7_UNORM_SRGB: - return true; + case DXGI_FORMAT_BC7_UNORM_SRGB: return true; - default: - return false; + default: return false; } } @@ -321,12 +296,11 @@ namespace DirectX } //-------------------------------------------------------------------------------------- - inline HRESULT LoadTextureDataFromMemory( - _In_reads_(ddsDataSize) const uint8_t* ddsData, - size_t ddsDataSize, - const DDS_HEADER** header, - const uint8_t** bitData, - size_t* bitSize) noexcept + inline HRESULT LoadTextureDataFromMemory(_In_reads_(ddsDataSize) const uint8_t* ddsData, + size_t ddsDataSize, + const DDS_HEADER** header, + const uint8_t** bitData, + size_t* bitSize) noexcept { if (!header || !bitData || !bitSize) { @@ -355,16 +329,14 @@ namespace DirectX auto hdr = reinterpret_cast(ddsData + sizeof(uint32_t)); // Verify header to validate DDS file - if (hdr->size != sizeof(DDS_HEADER) || - hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) + if (hdr->size != sizeof(DDS_HEADER) || hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) { return E_FAIL; } // Check for DX10 extension bool bDXT10Header = false; - if ((hdr->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) + if ((hdr->ddspf.flags & DDS_FOURCC) && (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) { // Must be long enough for both headers and magic value if (ddsDataSize < DDS_DX10_HEADER_SIZE) @@ -376,22 +348,20 @@ namespace DirectX } // setup the pointers in the process request - *header = hdr; - auto offset = DDS_MIN_HEADER_SIZE - + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0u); - *bitData = ddsData + offset; - *bitSize = ddsDataSize - offset; + *header = hdr; + auto offset = DDS_MIN_HEADER_SIZE + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0u); + *bitData = ddsData + offset; + *bitSize = ddsDataSize - offset; return S_OK; } //-------------------------------------------------------------------------------------- - inline HRESULT LoadTextureDataFromFile( - _In_z_ const wchar_t* fileName, - std::unique_ptr& ddsData, - const DDS_HEADER** header, - const uint8_t** bitData, - size_t* bitSize) noexcept + inline HRESULT LoadTextureDataFromFile(_In_z_ const wchar_t* fileName, + std::unique_ptr& ddsData, + const DDS_HEADER** header, + const uint8_t** bitData, + size_t* bitSize) noexcept { if (!header || !bitData || !bitSize) { @@ -401,10 +371,7 @@ namespace DirectX *bitSize = 0; // open the file - ScopedHandle hFile(safe_handle(CreateFile2( - fileName, - GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, - nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); if (!hFile) { return HRESULT_FROM_WIN32(GetLastError()); @@ -438,12 +405,7 @@ namespace DirectX // read the data in DWORD bytesRead = 0; - if (!ReadFile(hFile.get(), - ddsData.get(), - fileInfo.EndOfFile.LowPart, - &bytesRead, - nullptr - )) + if (!ReadFile(hFile.get(), ddsData.get(), fileInfo.EndOfFile.LowPart, &bytesRead, nullptr)) { ddsData.reset(); return HRESULT_FROM_WIN32(GetLastError()); @@ -466,8 +428,7 @@ namespace DirectX auto hdr = reinterpret_cast(ddsData.get() + sizeof(uint32_t)); // Verify header to validate DDS file - if (hdr->size != sizeof(DDS_HEADER) || - hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) + if (hdr->size != sizeof(DDS_HEADER) || hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) { ddsData.reset(); return E_FAIL; @@ -475,8 +436,7 @@ namespace DirectX // Check for DX10 extension bool bDXT10Header = false; - if ((hdr->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) + if ((hdr->ddspf.flags & DDS_FOURCC) && (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) { // Must be long enough for both headers and magic value if (fileInfo.EndOfFile.LowPart < DDS_DX10_HEADER_SIZE) @@ -489,11 +449,10 @@ namespace DirectX } // setup the pointers in the process request - *header = hdr; - auto offset = DDS_MIN_HEADER_SIZE - + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0u); - *bitData = ddsData.get() + offset; - *bitSize = fileInfo.EndOfFile.LowPart - offset; + *header = hdr; + auto offset = DDS_MIN_HEADER_SIZE + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0u); + *bitData = ddsData.get() + offset; + *bitSize = fileInfo.EndOfFile.LowPart - offset; return S_OK; } @@ -501,26 +460,24 @@ namespace DirectX //-------------------------------------------------------------------------------------- // Get surface information for a particular format //-------------------------------------------------------------------------------------- - inline HRESULT GetSurfaceInfo( - _In_ size_t width, - _In_ size_t height, - _In_ DXGI_FORMAT fmt, - _Out_opt_ size_t* outNumBytes, - _Out_opt_ size_t* outRowBytes, - _Out_opt_ size_t* outNumRows) noexcept + inline HRESULT GetSurfaceInfo(_In_ size_t width, + _In_ size_t height, + _In_ DXGI_FORMAT fmt, + _Out_opt_ size_t* outNumBytes, + _Out_opt_ size_t* outRowBytes, + _Out_opt_ size_t* outNumRows) noexcept { uint64_t numBytes = 0; uint64_t rowBytes = 0; - uint64_t numRows = 0; + uint64_t numRows = 0; - bool bc = false; - bool packed = false; - bool planar = false; - size_t bpe = 0; + bool bc = false; + bool packed = false; + bool planar = false; + size_t bpe = 0; switch (fmt) { - case DXGI_FORMAT_UNKNOWN: - return E_INVALIDARG; + case DXGI_FORMAT_UNKNOWN: return E_INVALIDARG; case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: @@ -528,7 +485,7 @@ namespace DirectX case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: - bc = true; + bc = true; bpe = 8; break; @@ -547,7 +504,7 @@ namespace DirectX case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: - bc = true; + bc = true; bpe = 16; break; @@ -555,13 +512,13 @@ namespace DirectX case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_YUY2: packed = true; - bpe = 4; + bpe = 4; break; case DXGI_FORMAT_Y210: case DXGI_FORMAT_Y216: packed = true; - bpe = 8; + bpe = 8; break; case DXGI_FORMAT_NV12: @@ -572,17 +529,17 @@ namespace DirectX return E_INVALIDARG; } planar = true; - bpe = 2; + bpe = 2; break; - #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) case DXGI_FORMAT_P208: planar = true; - bpe = 2; + bpe = 2; break; - #endif +#endif case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: @@ -592,22 +549,21 @@ namespace DirectX return E_INVALIDARG; } planar = true; - bpe = 4; + bpe = 4; break; - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) case DXGI_FORMAT_D16_UNORM_S8_UINT: case DXGI_FORMAT_R16_UNORM_X8_TYPELESS: case DXGI_FORMAT_X16_TYPELESS_G8_UINT: planar = true; - bpe = 4; + bpe = 4; break; - #endif +#endif - default: - break; + default: break; } if (bc) @@ -623,26 +579,26 @@ namespace DirectX numBlocksHigh = std::max(1u, (uint64_t(height) + 3u) / 4u); } rowBytes = numBlocksWide * bpe; - numRows = numBlocksHigh; + numRows = numBlocksHigh; numBytes = rowBytes * numBlocksHigh; } else if (packed) { rowBytes = ((uint64_t(width) + 1u) >> 1) * bpe; - numRows = uint64_t(height); + numRows = uint64_t(height); numBytes = rowBytes * height; } else if (fmt == DXGI_FORMAT_NV11) { rowBytes = ((uint64_t(width) + 3u) >> 2) * 4u; - numRows = uint64_t(height) * 2u; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data + numRows = uint64_t(height) * 2u; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data numBytes = rowBytes * numRows; } else if (planar) { rowBytes = ((uint64_t(width) + 1u) >> 1) * bpe; numBytes = (rowBytes * uint64_t(height)) + ((rowBytes * uint64_t(height) + 1u) >> 1); - numRows = height + ((uint64_t(height) + 1u) >> 1); + numRows = height + ((uint64_t(height) + 1u) >> 1); } else { @@ -651,17 +607,17 @@ namespace DirectX return E_INVALIDARG; rowBytes = (uint64_t(width) * bpp + 7u) / 8u; // round up to nearest byte - numRows = uint64_t(height); + numRows = uint64_t(height); numBytes = rowBytes * height; } - #if defined(_M_IX86) || defined(_M_ARM) || defined(_M_HYBRID_X86_ARM64) +#if defined(_M_IX86) || defined(_M_ARM) || defined(_M_HYBRID_X86_ARM64) static_assert(sizeof(size_t) == 4, "Not a 32-bit platform!"); if (numBytes > UINT32_MAX || rowBytes > UINT32_MAX || numRows > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); - #else +#else static_assert(sizeof(size_t) == 8, "Not a 64-bit platform!"); - #endif +#endif if (outNumBytes) { @@ -680,7 +636,7 @@ namespace DirectX } //-------------------------------------------------------------------------------------- - #define ISBITMASK( r,g,b,a ) ( ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a ) +#define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a) inline DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf) noexcept { @@ -780,8 +736,7 @@ namespace DirectX // No 3:3:2 or paletted DXGI formats aka D3DFMT_R3G3B2, D3DFMT_P8 break; - default: - return DXGI_FORMAT_UNKNOWN; + default: return DXGI_FORMAT_UNKNOWN; } } else if (ddpf.flags & DDS_LUMINANCE) @@ -813,8 +768,7 @@ namespace DirectX } break; - default: - return DXGI_FORMAT_UNKNOWN; + default: return DXGI_FORMAT_UNKNOWN; } } else if (ddpf.flags & DDS_ALPHA) @@ -848,8 +802,7 @@ namespace DirectX } break; - default: - return DXGI_FORMAT_UNKNOWN; + default: return DXGI_FORMAT_UNKNOWN; } // No DXGI format maps to DDPF_BUMPLUMINANCE aka D3DFMT_L6V5U5, D3DFMT_X8L8V8U8 @@ -925,7 +878,7 @@ namespace DirectX // Check for D3DFORMAT enums being set here switch (ddpf.fourCC) { - case 36: // D3DFMT_A16B16G16R16 + case 36: // D3DFMT_A16B16G16R16 return DXGI_FORMAT_R16G16B16A16_UNORM; case 110: // D3DFMT_Q16W16V16U16 @@ -949,17 +902,16 @@ namespace DirectX case 116: // D3DFMT_A32B32G32R32F return DXGI_FORMAT_R32G32B32A32_FLOAT; - // No DXGI format maps to D3DFMT_CxV8U8 + // No DXGI format maps to D3DFMT_CxV8U8 - default: - return DXGI_FORMAT_UNKNOWN; + default: return DXGI_FORMAT_UNKNOWN; } } return DXGI_FORMAT_UNKNOWN; } - #undef ISBITMASK +#undef ISBITMASK //-------------------------------------------------------------------------------------- inline DirectX::DDS_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header) noexcept @@ -968,23 +920,22 @@ namespace DirectX { if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC) { - auto d3d10ext = reinterpret_cast(reinterpret_cast(header) + sizeof(DDS_HEADER)); + auto d3d10ext + = reinterpret_cast(reinterpret_cast(header) + sizeof(DDS_HEADER)); const auto mode = static_cast(d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK); switch (mode) { case DDS_ALPHA_MODE_STRAIGHT: case DDS_ALPHA_MODE_PREMULTIPLIED: case DDS_ALPHA_MODE_OPAQUE: - case DDS_ALPHA_MODE_CUSTOM: - return mode; + case DDS_ALPHA_MODE_CUSTOM: return mode; case DDS_ALPHA_MODE_UNKNOWN: - default: - break; + default: break; } } else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC) - || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC)) + || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC)) { return DDS_ALPHA_MODE_PREMULTIPLIED; } @@ -997,12 +948,14 @@ namespace DirectX class auto_delete_file { public: - auto_delete_file(HANDLE hFile) noexcept : m_handle(hFile) {} + auto_delete_file(HANDLE hFile) noexcept + : m_handle(hFile) + {} - auto_delete_file(const auto_delete_file&) = delete; + auto_delete_file(const auto_delete_file&) = delete; auto_delete_file& operator=(const auto_delete_file&) = delete; - auto_delete_file(const auto_delete_file&&) = delete; + auto_delete_file(const auto_delete_file&&) = delete; auto_delete_file& operator=(const auto_delete_file&&) = delete; ~auto_delete_file() @@ -1010,8 +963,8 @@ namespace DirectX if (m_handle) { FILE_DISPOSITION_INFO info = {}; - info.DeleteFile = TRUE; - std::ignore = SetFileInformationByHandle(m_handle, FileDispositionInfo, &info, sizeof(info)); + info.DeleteFile = TRUE; + std::ignore = SetFileInformationByHandle(m_handle, FileDispositionInfo, &info, sizeof(info)); } } @@ -1024,12 +977,15 @@ namespace DirectX class auto_delete_file_wic { public: - auto_delete_file_wic(Microsoft::WRL::ComPtr& hFile, LPCWSTR szFile) noexcept : m_filename(szFile), m_handle(hFile) {} + auto_delete_file_wic(Microsoft::WRL::ComPtr& hFile, LPCWSTR szFile) noexcept + : m_filename(szFile), + m_handle(hFile) + {} - auto_delete_file_wic(const auto_delete_file_wic&) = delete; + auto_delete_file_wic(const auto_delete_file_wic&) = delete; auto_delete_file_wic& operator=(const auto_delete_file_wic&) = delete; - auto_delete_file_wic(const auto_delete_file_wic&&) = delete; + auto_delete_file_wic(const auto_delete_file_wic&&) = delete; auto_delete_file_wic& operator=(const auto_delete_file_wic&&) = delete; ~auto_delete_file_wic() @@ -1044,7 +1000,7 @@ namespace DirectX void clear() noexcept { m_filename = nullptr; } private: - LPCWSTR m_filename; + LPCWSTR m_filename; Microsoft::WRL::ComPtr& m_handle; }; @@ -1070,7 +1026,11 @@ namespace DirectX if (origx > origy) { size_t x; - for (x = maxsize; x > 1; x >>= 1) { if (x <= targetx) break; } + for (x = maxsize; x > 1; x >>= 1) + { + if (x <= targetx) + break; + } targetx = UINT(x); float bestScore = FLT_MAX; @@ -1080,14 +1040,18 @@ namespace DirectX if (score < bestScore) { bestScore = score; - targety = UINT(y); + targety = UINT(y); } } } else { size_t y; - for (y = maxsize; y > 1; y >>= 1) { if (y <= targety) break; } + for (y = maxsize; y > 1; y >>= 1) + { + if (y <= targety) + break; + } targety = UINT(y); float bestScore = FLT_MAX; @@ -1097,10 +1061,10 @@ namespace DirectX if (score < bestScore) { bestScore = score; - targetx = UINT(x); + targetx = UINT(x); } } } } - } -} + } // namespace LoaderHelpers +} // namespace DirectX diff --git a/Src/Model.cpp b/Src/Model.cpp index a783a302..5ebcb525 100644 --- a/Src/Model.cpp +++ b/Src/Model.cpp @@ -23,36 +23,33 @@ using namespace DirectX; #error Model requires RTTI #endif - //-------------------------------------------------------------------------------------- // ModelMeshPart //-------------------------------------------------------------------------------------- -ModelMeshPart::ModelMeshPart(uint32_t ipartIndex) noexcept : - partIndex(ipartIndex), - materialIndex(0), - indexCount(0), - startIndex(0), - vertexOffset(0), - vertexStride(0), - vertexCount(0), - indexBufferSize(0), - vertexBufferSize(0), - primitiveType(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST), - indexFormat(DXGI_FORMAT_R16_UINT) -{} - - -ModelMeshPart::~ModelMeshPart() +ModelMeshPart::ModelMeshPart(uint32_t ipartIndex) noexcept + : partIndex(ipartIndex), + materialIndex(0), + indexCount(0), + startIndex(0), + vertexOffset(0), + vertexStride(0), + vertexCount(0), + indexBufferSize(0), + vertexBufferSize(0), + primitiveType(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST), + indexFormat(DXGI_FORMAT_R16_UINT) {} +ModelMeshPart::~ModelMeshPart() {} -_Use_decl_annotations_ -void ModelMeshPart::Draw(_In_ ID3D12GraphicsCommandList* commandList) const +_Use_decl_annotations_ void ModelMeshPart::Draw(_In_ ID3D12GraphicsCommandList* commandList) const { if (!indexBufferSize || !vertexBufferSize) { - DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", indexBufferSize, vertexBufferSize); + DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", + indexBufferSize, + vertexBufferSize); throw std::runtime_error("ModelMeshPart"); } @@ -70,14 +67,14 @@ void ModelMeshPart::Draw(_In_ ID3D12GraphicsCommandList* commandList) const D3D12_VERTEX_BUFFER_VIEW vbv; vbv.BufferLocation = staticVertexBuffer ? staticVertexBuffer->GetGPUVirtualAddress() : vertexBuffer.GpuAddress(); - vbv.StrideInBytes = vertexStride; - vbv.SizeInBytes = vertexBufferSize; + vbv.StrideInBytes = vertexStride; + vbv.SizeInBytes = vertexBufferSize; commandList->IASetVertexBuffers(0, 1, &vbv); D3D12_INDEX_BUFFER_VIEW ibv; ibv.BufferLocation = staticIndexBuffer ? staticIndexBuffer->GetGPUVirtualAddress() : indexBuffer.GpuAddress(); - ibv.SizeInBytes = indexBufferSize; - ibv.Format = indexFormat; + ibv.SizeInBytes = indexBufferSize; + ibv.Format = indexFormat; commandList->IASetIndexBuffer(&ibv); commandList->IASetPrimitiveTopology(primitiveType); @@ -85,16 +82,14 @@ void ModelMeshPart::Draw(_In_ ID3D12GraphicsCommandList* commandList) const commandList->DrawIndexedInstanced(indexCount, 1, startIndex, vertexOffset, 0); } - -_Use_decl_annotations_ -void ModelMeshPart::DrawInstanced( - ID3D12GraphicsCommandList* commandList, - uint32_t instanceCount, - uint32_t startInstance) const +_Use_decl_annotations_ void +ModelMeshPart::DrawInstanced(ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstance) const { if (!indexBufferSize || !vertexBufferSize) { - DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", indexBufferSize, vertexBufferSize); + DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", + indexBufferSize, + vertexBufferSize); throw std::runtime_error("ModelMeshPart"); } @@ -112,14 +107,14 @@ void ModelMeshPart::DrawInstanced( D3D12_VERTEX_BUFFER_VIEW vbv; vbv.BufferLocation = staticVertexBuffer ? staticVertexBuffer->GetGPUVirtualAddress() : vertexBuffer.GpuAddress(); - vbv.StrideInBytes = vertexStride; - vbv.SizeInBytes = vertexBufferSize; + vbv.StrideInBytes = vertexStride; + vbv.SizeInBytes = vertexBufferSize; commandList->IASetVertexBuffers(0, 1, &vbv); D3D12_INDEX_BUFFER_VIEW ibv; ibv.BufferLocation = staticIndexBuffer ? staticIndexBuffer->GetGPUVirtualAddress() : indexBuffer.GpuAddress(); - ibv.SizeInBytes = indexBufferSize; - ibv.Format = indexFormat; + ibv.SizeInBytes = indexBufferSize; + ibv.Format = indexFormat; commandList->IASetIndexBuffer(&ibv); commandList->IASetPrimitiveTopology(primitiveType); @@ -127,11 +122,7 @@ void ModelMeshPart::DrawInstanced( commandList->DrawIndexedInstanced(indexCount, instanceCount, startIndex, vertexOffset, startInstance); } - -_Use_decl_annotations_ -void ModelMeshPart::DrawMeshParts( - ID3D12GraphicsCommandList* commandList, - const ModelMeshPart::Collection& meshParts) +_Use_decl_annotations_ void ModelMeshPart::DrawMeshParts(ID3D12GraphicsCommandList* commandList, const ModelMeshPart::Collection& meshParts) { for (const auto& it : meshParts) { @@ -142,12 +133,9 @@ void ModelMeshPart::DrawMeshParts( } } - -_Use_decl_annotations_ -void ModelMeshPart::DrawMeshParts( - ID3D12GraphicsCommandList* commandList, - const ModelMeshPart::Collection& meshParts, - ModelMeshPart::DrawCallback callback) +_Use_decl_annotations_ void ModelMeshPart::DrawMeshParts(ID3D12GraphicsCommandList* commandList, + const ModelMeshPart::Collection& meshParts, + ModelMeshPart::DrawCallback callback) { for (const auto& it : meshParts) { @@ -159,29 +147,22 @@ void ModelMeshPart::DrawMeshParts( } } - -_Use_decl_annotations_ -void ModelMeshPart::DrawMeshParts( - ID3D12GraphicsCommandList* commandList, - const ModelMeshPart::Collection& meshParts, - IEffect* effect) +_Use_decl_annotations_ void +ModelMeshPart::DrawMeshParts(ID3D12GraphicsCommandList* commandList, const ModelMeshPart::Collection& meshParts, IEffect* effect) { effect->Apply(commandList); DrawMeshParts(commandList, meshParts); } - //-------------------------------------------------------------------------------------- // ModelMesh //-------------------------------------------------------------------------------------- -ModelMesh::ModelMesh() noexcept : - boneIndex(ModelBone::c_Invalid) +ModelMesh::ModelMesh() noexcept + : boneIndex(ModelBone::c_Invalid) {} - -ModelMesh::~ModelMesh() -{} +ModelMesh::~ModelMesh() {} // Draw the mesh void ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList) const @@ -194,7 +175,6 @@ void ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList) const ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts); } - // Draw the mesh with an effect void ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEffect* effect) const { @@ -206,7 +186,6 @@ void ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEff ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts, effect); } - // Draw the mesh with a callback for each mesh part void ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const { @@ -218,23 +197,20 @@ void ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, ModelMesh ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts, callback); } - //-------------------------------------------------------------------------------------- // Model //-------------------------------------------------------------------------------------- -Model::Model() noexcept -{} +Model::Model() noexcept {} -Model::~Model() -{} +Model::~Model() {} -Model::Model(Model const& other) : - meshes(other.meshes), - materials(other.materials), - textureNames(other.textureNames), - bones(other.bones), - name(other.name) +Model::Model(Model const& other) + : meshes(other.meshes), + materials(other.materials), + textureNames(other.textureNames), + bones(other.bones), + name(other.name) { const size_t nbones = other.bones.size(); if (nbones > 0) @@ -252,7 +228,7 @@ Model::Model(Model const& other) : } } -Model& Model::operator= (Model const& rhs) +Model& Model::operator=(Model const& rhs) { if (this != &rhs) { @@ -268,7 +244,6 @@ Model& Model::operator= (Model const& rhs) return *this; } - // Load texture resources. int Model::LoadTextures(IEffectTextureFactory& texFactory, int destinationDescriptorOffset) const { @@ -280,23 +255,17 @@ int Model::LoadTextures(IEffectTextureFactory& texFactory, int destinationDescri return static_cast(textureNames.size()); } - // Load texture resources (helper function). -_Use_decl_annotations_ -std::unique_ptr Model::LoadTextures( - ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - const wchar_t* texturesPath, - D3D12_DESCRIPTOR_HEAP_FLAGS flags) const +_Use_decl_annotations_ std::unique_ptr Model::LoadTextures(ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + const wchar_t* texturesPath, + D3D12_DESCRIPTOR_HEAP_FLAGS flags) const { if (textureNames.empty()) return nullptr; - std::unique_ptr texFactory = std::make_unique( - device, - resourceUploadBatch, - textureNames.size(), - flags); + std::unique_ptr texFactory + = std::make_unique(device, resourceUploadBatch, textureNames.size(), flags); if (texturesPath != nullptr && *texturesPath != 0) { texFactory->SetDirectory(texturesPath); @@ -307,13 +276,8 @@ std::unique_ptr Model::LoadTextures( return texFactory; } - // Load VB/IB resources for static geometry. -_Use_decl_annotations_ -void Model::LoadStaticBuffers( - ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - bool keepMemory) +_Use_decl_annotations_ void Model::LoadStaticBuffers(ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch, bool keepMemory) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -351,21 +315,20 @@ void Model::LoadStaticBuffers( const auto desc = CD3DX12_RESOURCE_DESC::Buffer(part->vertexBuffer.Size()); - ThrowIfFailed(device->CreateCommittedResource( - &heapProperties, + ThrowIfFailed(device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, nullptr, - IID_GRAPHICS_PPV_ARGS(part->staticVertexBuffer.GetAddressOf()) - )); + IID_GRAPHICS_PPV_ARGS(part->staticVertexBuffer.GetAddressOf()))); SetDebugObjectName(part->staticVertexBuffer.Get(), L"ModelMeshPart"); resourceUploadBatch.Upload(part->staticVertexBuffer.Get(), part->vertexBuffer); resourceUploadBatch.Transition(part->staticVertexBuffer.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); // Scan for any other part with the same vertex buffer for sharing for (auto sit = std::next(it); sit != uniqueParts.cend(); ++sit) @@ -378,7 +341,7 @@ void Model::LoadStaticBuffers( if (sharePart->vertexBuffer == part->vertexBuffer) { - sharePart->vertexBufferSize = part->vertexBufferSize; + sharePart->vertexBufferSize = part->vertexBufferSize; sharePart->staticVertexBuffer = part->staticVertexBuffer; if (!keepMemory) @@ -407,21 +370,20 @@ void Model::LoadStaticBuffers( const auto desc = CD3DX12_RESOURCE_DESC::Buffer(part->indexBuffer.Size()); - ThrowIfFailed(device->CreateCommittedResource( - &heapProperties, + ThrowIfFailed(device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, nullptr, - IID_GRAPHICS_PPV_ARGS(part->staticIndexBuffer.GetAddressOf()) - )); + IID_GRAPHICS_PPV_ARGS(part->staticIndexBuffer.GetAddressOf()))); SetDebugObjectName(part->staticIndexBuffer.Get(), L"ModelMeshPart"); resourceUploadBatch.Upload(part->staticIndexBuffer.Get(), part->indexBuffer); resourceUploadBatch.Transition(part->staticIndexBuffer.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER); + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_INDEX_BUFFER); // Scan for any other part with the same index buffer for sharing for (auto sit = std::next(it); sit != uniqueParts.cend(); ++sit) @@ -434,7 +396,7 @@ void Model::LoadStaticBuffers( if (sharePart->indexBuffer == part->indexBuffer) { - sharePart->indexBufferSize = part->indexBufferSize; + sharePart->indexBufferSize = part->indexBufferSize; sharePart->staticIndexBuffer = part->staticIndexBuffer; if (!keepMemory) @@ -452,14 +414,12 @@ void Model::LoadStaticBuffers( } } - // Create effects for each mesh piece. -Model::EffectCollection Model::CreateEffects( - IEffectFactory& fxFactory, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - int textureDescriptorOffset, - int samplerDescriptorOffset) const +Model::EffectCollection Model::CreateEffects(IEffectFactory& fxFactory, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + int textureDescriptorOffset, + int samplerDescriptorOffset) const { if (materials.empty()) { @@ -501,7 +461,12 @@ Model::EffectCollection Model::CreateEffects( // If this fires, you have multiple parts with the same unique ID assert(effects[part->partIndex] == nullptr); - effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset, part.get()); + effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, + opaquePipelineState, + alphaPipelineState, + textureDescriptorOffset, + samplerDescriptorOffset, + part.get()); } for (const auto& part : mesh->alphaMeshParts) @@ -514,23 +479,25 @@ Model::EffectCollection Model::CreateEffects( // If this fires, you have multiple parts with the same unique ID assert(effects[part->partIndex] == nullptr); - effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset, part.get()); + effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, + opaquePipelineState, + alphaPipelineState, + textureDescriptorOffset, + samplerDescriptorOffset, + part.get()); } } return effects; } - // Private helper for creating an effect for a mesh part. -_Use_decl_annotations_ -std::shared_ptr Model::CreateEffectForMeshPart( - IEffectFactory& fxFactory, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - int textureDescriptorOffset, - int samplerDescriptorOffset, - const ModelMeshPart* part) const +_Use_decl_annotations_ std::shared_ptr Model::CreateEffectForMeshPart(IEffectFactory& fxFactory, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + int textureDescriptorOffset, + int samplerDescriptorOffset, + const ModelMeshPart* part) const { assert(part->materialIndex < materials.size()); const auto& m = materials[part->materialIndex]; @@ -542,33 +509,26 @@ std::shared_ptr Model::CreateEffectForMeshPart( throw std::runtime_error("Model mesh part input layout size is too large for DirectX 12"); D3D12_INPUT_LAYOUT_DESC il = {}; - il.NumElements = static_cast(part->vbDecl->size()); - il.pInputElementDescs = part->vbDecl->data(); + il.NumElements = static_cast(part->vbDecl->size()); + il.pInputElementDescs = part->vbDecl->data(); return fxFactory.CreateEffect(m, opaquePipelineState, alphaPipelineState, il, textureDescriptorOffset, samplerDescriptorOffset); } - // Create effects for each mesh piece with the default factory. -_Use_decl_annotations_ -Model::EffectCollection Model::CreateEffects( - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - ID3D12DescriptorHeap* textureDescriptorHeap, - ID3D12DescriptorHeap* samplerDescriptorHeap, - int textureDescriptorOffset, - int samplerDescriptorOffset) const +_Use_decl_annotations_ Model::EffectCollection Model::CreateEffects(const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + ID3D12DescriptorHeap* textureDescriptorHeap, + ID3D12DescriptorHeap* samplerDescriptorHeap, + int textureDescriptorOffset, + int samplerDescriptorOffset) const { EffectFactory fxFactory(textureDescriptorHeap, samplerDescriptorHeap); return CreateEffects(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset); } - // Compute using bone hierarchy from model bone matrices to an array. -_Use_decl_annotations_ -void Model::CopyAbsoluteBoneTransformsTo( - size_t nbones, - XMMATRIX* boneTransforms) const +_Use_decl_annotations_ void Model::CopyAbsoluteBoneTransformsTo(size_t nbones, XMMATRIX* boneTransforms) const { if (!nbones || !boneTransforms) { @@ -587,18 +547,14 @@ void Model::CopyAbsoluteBoneTransformsTo( memset(boneTransforms, 0, sizeof(XMMATRIX) * nbones); - const XMMATRIX id = XMMatrixIdentity(); - size_t visited = 0; + const XMMATRIX id = XMMatrixIdentity(); + size_t visited = 0; ComputeAbsolute(0, id, bones.size(), boneMatrices.get(), boneTransforms, visited); } - // Compute using bone hierarchy from one array to another array. -_Use_decl_annotations_ -void Model::CopyAbsoluteBoneTransforms( - size_t nbones, - const XMMATRIX* inBoneTransforms, - XMMATRIX* outBoneTransforms) const +_Use_decl_annotations_ void +Model::CopyAbsoluteBoneTransforms(size_t nbones, const XMMATRIX* inBoneTransforms, XMMATRIX* outBoneTransforms) const { if (!nbones || !inBoneTransforms || !outBoneTransforms) { @@ -617,21 +573,18 @@ void Model::CopyAbsoluteBoneTransforms( memset(outBoneTransforms, 0, sizeof(XMMATRIX) * nbones); - const XMMATRIX id = XMMatrixIdentity(); - size_t visited = 0; + const XMMATRIX id = XMMatrixIdentity(); + size_t visited = 0; ComputeAbsolute(0, id, bones.size(), inBoneTransforms, outBoneTransforms, visited); } - // Private helper for computing hierarchical transforms using bones via recursion. -_Use_decl_annotations_ -void Model::ComputeAbsolute( - uint32_t index, - CXMMATRIX parent, - size_t nbones, - const XMMATRIX* inBoneTransforms, - XMMATRIX* outBoneTransforms, - size_t& visited) const +_Use_decl_annotations_ void Model::ComputeAbsolute(uint32_t index, + CXMMATRIX parent, + size_t nbones, + const XMMATRIX* inBoneTransforms, + XMMATRIX* outBoneTransforms, + size_t& visited) const { if (index == ModelBone::c_Invalid || index >= nbones) return; @@ -645,27 +598,23 @@ void Model::ComputeAbsolute( throw std::runtime_error("Model bones form an invalid graph"); } - XMMATRIX local = inBoneTransforms[index]; - local = XMMatrixMultiply(local, parent); + XMMATRIX local = inBoneTransforms[index]; + local = XMMatrixMultiply(local, parent); outBoneTransforms[index] = local; if (bones[index].siblingIndex != ModelBone::c_Invalid) { - ComputeAbsolute(bones[index].siblingIndex, parent, nbones, - inBoneTransforms, outBoneTransforms, visited); + ComputeAbsolute(bones[index].siblingIndex, parent, nbones, inBoneTransforms, outBoneTransforms, visited); } if (bones[index].childIndex != ModelBone::c_Invalid) { - ComputeAbsolute(bones[index].childIndex, local, nbones, - inBoneTransforms, outBoneTransforms, visited); + ComputeAbsolute(bones[index].childIndex, local, nbones, inBoneTransforms, outBoneTransforms, visited); } } - // Copy the model bone matrices from an array. -_Use_decl_annotations_ -void Model::CopyBoneTransformsFrom(size_t nbones, const XMMATRIX* boneTransforms) +_Use_decl_annotations_ void Model::CopyBoneTransformsFrom(size_t nbones, const XMMATRIX* boneTransforms) { if (!nbones || !boneTransforms) { @@ -690,10 +639,8 @@ void Model::CopyBoneTransformsFrom(size_t nbones, const XMMATRIX* boneTransforms memcpy(boneMatrices.get(), boneTransforms, bones.size() * sizeof(XMMATRIX)); } - // Copy the model bone matrices to an array. -_Use_decl_annotations_ -void Model::CopyBoneTransformsTo(size_t nbones, XMMATRIX* boneTransforms) const +_Use_decl_annotations_ void Model::CopyBoneTransformsTo(size_t nbones, XMMATRIX* boneTransforms) const { if (!nbones || !boneTransforms) { @@ -713,13 +660,8 @@ void Model::CopyBoneTransformsTo(size_t nbones, XMMATRIX* boneTransforms) const memcpy(boneTransforms, boneMatrices.get(), bones.size() * sizeof(XMMATRIX)); } - // Updates effect matrices (if applicable). -void XM_CALLCONV Model::UpdateEffectMatrices( - EffectCollection& effects, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX proj) +void XM_CALLCONV Model::UpdateEffectMatrices(EffectCollection& effects, FXMMATRIX world, CXMMATRIX view, CXMMATRIX proj) { for (auto& fx : effects) { @@ -731,16 +673,14 @@ void XM_CALLCONV Model::UpdateEffectMatrices( } } - // Transition static VB/IB resources (if applicable). -void Model::Transition( - _In_ ID3D12GraphicsCommandList* commandList, - D3D12_RESOURCE_STATES stateBeforeVB, - D3D12_RESOURCE_STATES stateAfterVB, - D3D12_RESOURCE_STATES stateBeforeIB, - D3D12_RESOURCE_STATES stateAfterIB) +void Model::Transition(_In_ ID3D12GraphicsCommandList* commandList, + D3D12_RESOURCE_STATES stateBeforeVB, + D3D12_RESOURCE_STATES stateAfterVB, + D3D12_RESOURCE_STATES stateBeforeIB, + D3D12_RESOURCE_STATES stateAfterIB) { - UINT count = 0; + UINT count = 0; D3D12_RESOURCE_BARRIER barrier[64] = {}; for (auto& mit : meshes) @@ -752,11 +692,11 @@ void Model::Transition( if (stateBeforeIB != stateAfterIB && pit->staticIndexBuffer) { - barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier[count].Transition.pResource = pit->staticIndexBuffer.Get(); + barrier[count].Transition.pResource = pit->staticIndexBuffer.Get(); barrier[count].Transition.StateBefore = stateBeforeIB; - barrier[count].Transition.StateAfter = stateAfterIB; + barrier[count].Transition.StateAfter = stateAfterIB; ++count; if (count >= std::size(barrier)) @@ -768,11 +708,11 @@ void Model::Transition( if (stateBeforeVB != stateAfterVB && pit->staticVertexBuffer) { - barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier[count].Transition.pResource = pit->staticVertexBuffer.Get(); + barrier[count].Transition.pResource = pit->staticVertexBuffer.Get(); barrier[count].Transition.StateBefore = stateBeforeVB; - barrier[count].Transition.StateAfter = stateAfterVB; + barrier[count].Transition.StateAfter = stateAfterVB; ++count; if (count >= std::size(barrier)) @@ -790,11 +730,11 @@ void Model::Transition( if (stateBeforeIB != stateAfterIB && pit->staticIndexBuffer) { - barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier[count].Transition.pResource = pit->staticIndexBuffer.Get(); + barrier[count].Transition.pResource = pit->staticIndexBuffer.Get(); barrier[count].Transition.StateBefore = stateBeforeIB; - barrier[count].Transition.StateAfter = stateAfterIB; + barrier[count].Transition.StateAfter = stateAfterIB; ++count; if (count >= std::size(barrier)) @@ -806,11 +746,11 @@ void Model::Transition( if (stateBeforeVB != stateAfterVB && pit->staticVertexBuffer) { - barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier[count].Transition.pResource = pit->staticVertexBuffer.Get(); + barrier[count].Transition.pResource = pit->staticVertexBuffer.Get(); barrier[count].Transition.StateBefore = stateBeforeVB; - barrier[count].Transition.StateAfter = stateAfterVB; + barrier[count].Transition.StateAfter = stateAfterVB; ++count; if (count >= std::size(barrier)) @@ -828,18 +768,15 @@ void Model::Transition( } } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -_Use_decl_annotations_ -std::unique_ptr Model::LoadTextures( - ID3D12Device* device, - ResourceUploadBatch& resourceUploadBatch, - const __wchar_t* texturesPath, - D3D12_DESCRIPTOR_HEAP_FLAGS flags) const +_Use_decl_annotations_ std::unique_ptr Model::LoadTextures(ID3D12Device* device, + ResourceUploadBatch& resourceUploadBatch, + const __wchar_t* texturesPath, + D3D12_DESCRIPTOR_HEAP_FLAGS flags) const { return LoadTextures(device, resourceUploadBatch, reinterpret_cast(texturesPath), flags); } diff --git a/Src/ModelLoadCMO.cpp b/Src/ModelLoadCMO.cpp index 64000a23..d8f74593 100644 --- a/Src/ModelLoadCMO.cpp +++ b/Src/ModelLoadCMO.cpp @@ -19,7 +19,6 @@ using Microsoft::WRL::ComPtr; #include "CMO.h" - namespace { int GetUniqueTextureIndex(const wchar_t* textureName, std::map& textureDictionary) @@ -30,7 +29,7 @@ namespace auto i = textureDictionary.find(textureName); if (i == std::cend(textureDictionary)) { - int index = static_cast(textureDictionary.size()); + int index = static_cast(textureDictionary.size()); textureDictionary[textureName] = index; return index; } @@ -51,28 +50,24 @@ namespace static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 5; + static constexpr unsigned int InputElementCount = 5; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; static_assert(sizeof(VertexPositionNormalTangentColorTexture) == sizeof(VSD3DStarter::Vertex), "mismatch with CMO vertex type"); - const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTexture::InputElements[] = - { - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalTangentColorTexture) == 52, "mismatch with CMO vertex type"); - const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalTangentColorTexture::InputLayout = - { - VertexPositionNormalTangentColorTexture::InputElements, - VertexPositionNormalTangentColorTexture::InputElementCount - }; + const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalTangentColorTexture::InputLayout + = { VertexPositionNormalTangentColorTexture::InputElements, VertexPositionNormalTangentColorTexture::InputElementCount }; struct VertexPositionNormalTangentColorTextureSkinning : public VertexPositionNormalTangentColorTexture { @@ -84,7 +79,7 @@ namespace this->indices = ((iindices.w & 0xff) << 24) | ((iindices.z & 0xff) << 16) | ((iindices.y & 0xff) << 8) | (iindices.x & 0xff); } - void SetBlendWeights(XMFLOAT4 const& iweights) noexcept { SetBlendWeights(XMLoadFloat4(&iweights)); } + void SetBlendWeights(XMFLOAT4 const& iweights) noexcept { SetBlendWeights(XMLoadFloat4(&iweights)); } void XM_CALLCONV SetBlendWeights(FXMVECTOR iweights) noexcept { using namespace DirectX::PackedVector; @@ -97,51 +92,48 @@ namespace static const D3D12_INPUT_LAYOUT_DESC InputLayout; private: - static constexpr unsigned int InputElementCount = 7; + static constexpr unsigned int InputElementCount = 7; static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTextureSkinning::InputElements[] = - { - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "BLENDINDICES",0, DXGI_FORMAT_R8G8B8A8_UINT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "BLENDWEIGHT", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTextureSkinning::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "BLENDINDICES", 0, DXGI_FORMAT_R8G8B8A8_UINT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "BLENDWEIGHT", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalTangentColorTextureSkinning) == 60, "Vertex struct/layout mismatch"); - const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalTangentColorTextureSkinning::InputLayout = - { - VertexPositionNormalTangentColorTextureSkinning::InputElements, - VertexPositionNormalTangentColorTextureSkinning::InputElementCount - }; + const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalTangentColorTextureSkinning::InputLayout + = { VertexPositionNormalTangentColorTextureSkinning::InputElements, + VertexPositionNormalTangentColorTextureSkinning::InputElementCount }; //---------------------------------------------------------------------------------- struct MaterialRecordCMO { - const VSD3DStarter::Material* pMaterial; - uint32_t materialIndex; - std::wstring name; - std::wstring pixelShader; - std::wstring texture[VSD3DStarter::MAX_TEXTURE]; - - MaterialRecordCMO() noexcept : - pMaterial(nullptr), - materialIndex(0), - texture{} + const VSD3DStarter::Material* pMaterial; + uint32_t materialIndex; + std::wstring name; + std::wstring pixelShader; + std::wstring texture[VSD3DStarter::MAX_TEXTURE]; + + MaterialRecordCMO() noexcept + : pMaterial(nullptr), + materialIndex(0), + texture{} {} }; // Shared VB input element description - INIT_ONCE g_InitOnce = INIT_ONCE_STATIC_INIT; + INIT_ONCE g_InitOnce = INIT_ONCE_STATIC_INIT; std::shared_ptr g_vbdecl; std::shared_ptr g_vbdeclSkinning; - BOOL CALLBACK InitializeDecl(PINIT_ONCE initOnce, PVOID Parameter, PVOID *lpContext) + BOOL CALLBACK InitializeDecl(PINIT_ONCE initOnce, PVOID Parameter, PVOID* lpContext) { UNREFERENCED_PARAMETER(initOnce); UNREFERENCED_PARAMETER(Parameter); @@ -150,12 +142,12 @@ namespace g_vbdecl = std::make_shared( VertexPositionNormalTangentColorTexture::InputLayout.pInputElementDescs, VertexPositionNormalTangentColorTexture::InputLayout.pInputElementDescs - + VertexPositionNormalTangentColorTexture::InputLayout.NumElements); + + VertexPositionNormalTangentColorTexture::InputLayout.NumElements); g_vbdeclSkinning = std::make_shared( VertexPositionNormalTangentColorTextureSkinning::InputLayout.pInputElementDescs, VertexPositionNormalTangentColorTextureSkinning::InputLayout.pInputElementDescs - + VertexPositionNormalTangentColorTextureSkinning::InputLayout.NumElements); + + VertexPositionNormalTangentColorTextureSkinning::InputLayout.NumElements); return TRUE; } @@ -164,7 +156,7 @@ namespace if (srgb) { XMVECTOR v = XMVectorSet(r, g, b, 1.f); - v = XMColorSRGBToRGB(v); + v = XMColorSRGBToRGB(v); XMFLOAT3 result; XMStoreFloat3(&result, v); @@ -175,19 +167,14 @@ namespace return XMFLOAT3(r, g, b); } } -} - +} // namespace //====================================================================================== // Model Loader //====================================================================================== -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromCMO( - ID3D12Device* device, - const uint8_t* meshData, size_t dataSize, - ModelLoaderFlags flags, - size_t* animsOffset) +_Use_decl_annotations_ std::unique_ptr +Model::CreateFromCMO(ID3D12Device* device, const uint8_t* meshData, size_t dataSize, ModelLoaderFlags flags, size_t* animsOffset) { if (animsOffset) { @@ -201,7 +188,7 @@ std::unique_ptr Model::CreateFromCMO( throw std::invalid_argument("Device and meshData cannot be null"); // Meshes - auto nMesh = reinterpret_cast(meshData); + auto nMesh = reinterpret_cast(meshData); size_t usedSize = sizeof(uint32_t); if (dataSize < usedSize) throw std::runtime_error("End of file"); @@ -212,7 +199,7 @@ std::unique_ptr Model::CreateFromCMO( if (*nMesh > UINT16_MAX) throw std::runtime_error("Too many meshes in a file"); - std::map textureDictionary; + std::map textureDictionary; std::vector modelmats; auto model = std::make_unique(); @@ -228,9 +215,10 @@ std::unique_ptr Model::CreateFromCMO( if (dataSize < usedSize) throw std::runtime_error("End of file"); - auto meshName = reinterpret_cast(static_cast(meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. + auto meshName = reinterpret_cast(static_cast( + meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. - usedSize += sizeof(wchar_t)*(*nName); + usedSize += sizeof(wchar_t) * (*nName); if (dataSize < usedSize) throw std::runtime_error("End of file"); @@ -260,9 +248,10 @@ std::unique_ptr Model::CreateFromCMO( if (dataSize < usedSize) throw std::runtime_error("End of file"); - auto matName = reinterpret_cast(static_cast(meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. + auto matName = reinterpret_cast(static_cast( + meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. - usedSize += sizeof(wchar_t)*(*nName); + usedSize += sizeof(wchar_t) * (*nName); if (dataSize < usedSize) throw std::runtime_error("End of file"); @@ -282,9 +271,10 @@ std::unique_ptr Model::CreateFromCMO( if (dataSize < usedSize) throw std::runtime_error("End of file"); - auto psName = reinterpret_cast(static_cast(meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. + auto psName = reinterpret_cast(static_cast( + meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. - usedSize += sizeof(wchar_t)*(*nName); + usedSize += sizeof(wchar_t) * (*nName); if (dataSize < usedSize) throw std::runtime_error("End of file"); @@ -297,9 +287,10 @@ std::unique_ptr Model::CreateFromCMO( if (dataSize < usedSize) throw std::runtime_error("End of file"); - auto txtName = reinterpret_cast(static_cast(meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. + auto txtName = reinterpret_cast(static_cast( + meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. - usedSize += sizeof(wchar_t)*(*nName); + usedSize += sizeof(wchar_t) * (*nName); if (dataSize < usedSize) throw std::runtime_error("End of file"); @@ -316,8 +307,8 @@ std::unique_ptr Model::CreateFromCMO( // Add default material if none defined MaterialRecordCMO m; m.materialIndex = static_cast(baseMaterialIndex); - m.pMaterial = &VSD3DStarter::s_defMaterial; - m.name = L"Default"; + m.pMaterial = &VSD3DStarter::s_defMaterial; + m.name = L"Default"; materials.emplace_back(m); } @@ -395,7 +386,7 @@ std::unique_ptr Model::CreateFromCMO( IBData ib; ib.nIndices = *nIndexes; - ib.ptr = indexes; + ib.ptr = indexes; ibData.emplace_back(ib); ibs[j] = GraphicsMemory::Get(device).Allocate(ibBytes, 16, GraphicsMemory::TAG_INDEX); @@ -419,9 +410,9 @@ std::unique_ptr Model::CreateFromCMO( struct VBData { - size_t nVerts; - const VertexPositionNormalTangentColorTexture* ptr; - const VSD3DStarter::SkinningVertex* skinPtr; + size_t nVerts; + const VertexPositionNormalTangentColorTexture* ptr; + const VSD3DStarter::SkinningVertex* skinPtr; }; std::vector vbData; @@ -444,8 +435,8 @@ std::unique_ptr Model::CreateFromCMO( throw std::runtime_error("End of file"); VBData vb; - vb.nVerts = *nVerts; - vb.ptr = verts; + vb.nVerts = *nVerts; + vb.ptr = verts; vb.skinPtr = nullptr; vbData.emplace_back(vb); } @@ -496,7 +487,7 @@ std::unique_ptr Model::CreateFromCMO( mesh->boundingSphere.Center.x = extents->CenterX; mesh->boundingSphere.Center.y = extents->CenterY; mesh->boundingSphere.Center.z = extents->CenterZ; - mesh->boundingSphere.Radius = extents->Radius; + mesh->boundingSphere.Radius = extents->Radius; const XMVECTOR min = XMVectorSet(extents->MinX, extents->MinY, extents->MinZ, 0.f); const XMVECTOR max = XMVectorSet(extents->MaxX, extents->MaxY, extents->MaxZ, 0.f); @@ -516,7 +507,7 @@ std::unique_ptr Model::CreateFromCMO( ModelBone::Collection bones; bones.resize(*nBones); - auto transforms = ModelBone::MakeArray(*nBones); + auto transforms = ModelBone::MakeArray(*nBones); auto invTransforms = ModelBone::MakeArray(*nBones); for (uint32_t j = 0; j < *nBones; ++j) @@ -527,7 +518,8 @@ std::unique_ptr Model::CreateFromCMO( if (dataSize < usedSize) throw std::runtime_error("End of file"); - auto boneName = reinterpret_cast(static_cast(meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. + auto boneName = reinterpret_cast(static_cast( + meshData + usedSize)); // CodeQL [SM02986] The cast here is intentional to interpret the string in the buffer. usedSize += sizeof(wchar_t) * (*nName); if (dataSize < usedSize) @@ -541,7 +533,7 @@ std::unique_ptr Model::CreateFromCMO( if (dataSize < usedSize) throw std::runtime_error("End of file"); - transforms[j] = XMLoadFloat4x4(&cmobones->LocalTransform); + transforms[j] = XMLoadFloat4x4(&cmobones->LocalTransform); invTransforms[j] = XMLoadFloat4x4(&cmobones->InvBindPos); if (cmobones->ParentIndex < 0) @@ -641,8 +633,8 @@ std::unique_ptr Model::CreateFromCMO( std::vector vbs; vbs.resize(*nVBs); - const size_t stride = enableSkinning ? sizeof(VertexPositionNormalTangentColorTextureSkinning) - : sizeof(VertexPositionNormalTangentColorTexture); + const size_t stride + = enableSkinning ? sizeof(VertexPositionNormalTangentColorTextureSkinning) : sizeof(VertexPositionNormalTangentColorTexture); for (size_t j = 0; j < *nVBs; ++j) { @@ -704,8 +696,7 @@ std::unique_ptr Model::CreateFromCMO( if (sm.VertexBufferIndex != j) continue; - if ((sm.IndexBufferIndex >= *nIBs) - || (sm.MaterialIndex >= materials.size())) + if ((sm.IndexBufferIndex >= *nIBs) || (sm.MaterialIndex >= materials.size())) throw std::out_of_range("Invalid submesh found\n"); const XMMATRIX uvTransform = XMLoadFloat4x4(&materials[sm.MaterialIndex].pMaterial->UVTransform); @@ -736,17 +727,18 @@ std::unique_ptr Model::CreateFromCMO( } else if (visited[v] != sm.MaterialIndex) { - #ifdef _DEBUG +#ifdef _DEBUG const XMMATRIX uv2 = XMLoadFloat4x4(&materials[visited[v]].pMaterial->UVTransform); - if (XMVector4NotEqual(uvTransform.r[0], uv2.r[0]) - || XMVector4NotEqual(uvTransform.r[1], uv2.r[1]) - || XMVector4NotEqual(uvTransform.r[2], uv2.r[2]) - || XMVector4NotEqual(uvTransform.r[3], uv2.r[3])) + if (XMVector4NotEqual(uvTransform.r[0], uv2.r[0]) || XMVector4NotEqual(uvTransform.r[1], uv2.r[1]) + || XMVector4NotEqual(uvTransform.r[2], uv2.r[2]) || XMVector4NotEqual(uvTransform.r[3], uv2.r[3])) { - DebugTrace("WARNING: %ls - mismatched UV transforms for the same vertex; texture coordinates may not be correct\n", mesh->name.c_str()); + DebugTrace( + "WARNING: %ls - mismatched UV transforms for the same vertex; texture coordinates may not be " + "correct\n", + mesh->name.c_str()); } - #endif +#endif } } } @@ -767,15 +759,15 @@ std::unique_ptr Model::CreateFromCMO( auto& m = materials[j]; ModelMaterialInfo info; - info.name = m.name.c_str(); - info.specularPower = m.pMaterial->SpecularPower; - info.perVertexColor = true; - info.enableSkinning = enableSkinning; - info.alphaValue = m.pMaterial->Diffuse.w; - info.ambientColor = GetMaterialColor(m.pMaterial->Ambient.x, m.pMaterial->Ambient.y, m.pMaterial->Ambient.z, srgb); - info.diffuseColor = GetMaterialColor(m.pMaterial->Diffuse.x, m.pMaterial->Diffuse.y, m.pMaterial->Diffuse.z, srgb); - info.specularColor = GetMaterialColor(m.pMaterial->Specular.x, m.pMaterial->Specular.y, m.pMaterial->Specular.z, srgb); - info.emissiveColor = GetMaterialColor(m.pMaterial->Emissive.x, m.pMaterial->Emissive.y, m.pMaterial->Emissive.z, srgb); + info.name = m.name.c_str(); + info.specularPower = m.pMaterial->SpecularPower; + info.perVertexColor = true; + info.enableSkinning = enableSkinning; + info.alphaValue = m.pMaterial->Diffuse.w; + info.ambientColor = GetMaterialColor(m.pMaterial->Ambient.x, m.pMaterial->Ambient.y, m.pMaterial->Ambient.z, srgb); + info.diffuseColor = GetMaterialColor(m.pMaterial->Diffuse.x, m.pMaterial->Diffuse.y, m.pMaterial->Diffuse.z, srgb); + info.specularColor = GetMaterialColor(m.pMaterial->Specular.x, m.pMaterial->Specular.y, m.pMaterial->Specular.z, srgb); + info.emissiveColor = GetMaterialColor(m.pMaterial->Emissive.x, m.pMaterial->Emissive.y, m.pMaterial->Emissive.z, srgb); info.diffuseTextureIndex = GetUniqueTextureIndex(m.texture[0].c_str(), textureDictionary); info.samplerIndex = (info.diffuseTextureIndex == -1) ? -1 : static_cast(CommonStates::SamplerIndex::AnisotropicWrap); @@ -787,24 +779,22 @@ std::unique_ptr Model::CreateFromCMO( { auto& sm = subMesh[j]; - if ((sm.IndexBufferIndex >= *nIBs) - || (sm.VertexBufferIndex >= *nVBs) - || (sm.MaterialIndex >= materials.size())) + if ((sm.IndexBufferIndex >= *nIBs) || (sm.VertexBufferIndex >= *nVBs) || (sm.MaterialIndex >= materials.size())) throw std::out_of_range("Invalid submesh found\n"); auto& mat = materials[sm.MaterialIndex]; auto part = std::make_unique(partCount++); - part->indexCount = sm.PrimCount * 3; - part->materialIndex = mat.materialIndex; - part->startIndex = sm.StartIndex; - part->vertexStride = static_cast(stride); - part->indexBuffer = ibs[sm.IndexBufferIndex]; - part->indexBufferSize = static_cast(ibs[sm.IndexBufferIndex].Size()); - part->vertexBuffer = vbs[sm.VertexBufferIndex]; + part->indexCount = sm.PrimCount * 3; + part->materialIndex = mat.materialIndex; + part->startIndex = sm.StartIndex; + part->vertexStride = static_cast(stride); + part->indexBuffer = ibs[sm.IndexBufferIndex]; + part->indexBufferSize = static_cast(ibs[sm.IndexBufferIndex].Size()); + part->vertexBuffer = vbs[sm.VertexBufferIndex]; part->vertexBufferSize = static_cast(vbs[sm.VertexBufferIndex].Size()); - part->vbDecl = enableSkinning ? g_vbdeclSkinning : g_vbdecl; + part->vbDecl = enableSkinning ? g_vbdeclSkinning : g_vbdecl; if (mat.pMaterial->Diffuse.w < 1) { @@ -830,27 +820,21 @@ std::unique_ptr Model::CreateFromCMO( return model; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromCMO( - ID3D12Device* device, - const wchar_t* szFileName, - ModelLoaderFlags flags, - size_t* animsOffset) +_Use_decl_annotations_ std::unique_ptr + Model::CreateFromCMO(ID3D12Device* device, const wchar_t* szFileName, ModelLoaderFlags flags, size_t* animsOffset) { if (animsOffset) { *animsOffset = 0; } - size_t dataSize = 0; + size_t dataSize = 0; std::unique_ptr data; - HRESULT hr = BinaryReader::ReadEntireFile(szFileName, data, &dataSize); + HRESULT hr = BinaryReader::ReadEntireFile(szFileName, data, &dataSize); if (FAILED(hr)) { - DebugTrace("ERROR: CreateFromCMO failed (%08X) loading '%ls'\n", - static_cast(hr), szFileName); + DebugTrace("ERROR: CreateFromCMO failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); throw std::runtime_error("CreateFromCMO"); } @@ -861,18 +845,13 @@ std::unique_ptr Model::CreateFromCMO( return model; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromCMO( - ID3D12Device* device, - const __wchar_t* szFileName, - ModelLoaderFlags flags, - size_t* animsOffset) +_Use_decl_annotations_ std::unique_ptr + Model::CreateFromCMO(ID3D12Device* device, const __wchar_t* szFileName, ModelLoaderFlags flags, size_t* animsOffset) { return CreateFromCMO(device, reinterpret_cast(szFileName), flags, animsOffset); } diff --git a/Src/ModelLoadSDKMESH.cpp b/Src/ModelLoadSDKMESH.cpp index 10e18531..fbae3b3a 100644 --- a/Src/ModelLoadSDKMESH.cpp +++ b/Src/ModelLoadSDKMESH.cpp @@ -28,12 +28,12 @@ namespace { enum : unsigned int { - PER_VERTEX_COLOR = 0x1, - SKINNING = 0x2, - DUAL_TEXTURE = 0x4, - NORMAL_MAPS = 0x8, + PER_VERTEX_COLOR = 0x1, + SKINNING = 0x2, + DUAL_TEXTURE = 0x4, + NORMAL_MAPS = 0x8, BIASED_VERTEX_NORMALS = 0x10, - USES_OBSOLETE_DEC3N = 0x20, + USES_OBSOLETE_DEC3N = 0x20, }; int GetUniqueTextureIndex(const wchar_t* textureName, std::map& textureDictionary) @@ -44,7 +44,7 @@ namespace auto i = textureDictionary.find(textureName); if (i == std::cend(textureDictionary)) { - int index = static_cast(textureDictionary.size()); + int index = static_cast(textureDictionary.size()); textureDictionary[textureName] = index; return index; } @@ -59,7 +59,7 @@ namespace if (srgb) { XMVECTOR v = XMVectorSet(r, g, b, 1.f); - v = XMColorSRGBToRGB(v); + v = XMColorSRGBToRGB(v); XMFLOAT3 result; XMStoreFloat3(&result, v); @@ -72,17 +72,16 @@ namespace } template - inline void ASCIIToWChar(wchar_t(&buffer)[sizeOfBuffer], const char *ascii) + inline void ASCIIToWChar(wchar_t (&buffer)[sizeOfBuffer], const char* ascii) { MultiByteToWideChar(CP_UTF8, 0, ascii, -1, buffer, sizeOfBuffer); } - void InitMaterial( - const DXUT::SDKMESH_MATERIAL& mh, - unsigned int flags, + void InitMaterial(const DXUT::SDKMESH_MATERIAL& mh, + unsigned int flags, _Out_ Model::ModelMaterialInfo& m, _Inout_ std::map& textureDictionary, - bool srgb) + bool srgb) { wchar_t matName[DXUT::MAX_MATERIAL_NAME] = {}; ASCIIToWChar(matName, mh.Name); @@ -107,25 +106,25 @@ namespace flags |= NORMAL_MAPS; } - m = {}; - m.name = matName; - m.perVertexColor = (flags & PER_VERTEX_COLOR) != 0; - m.enableSkinning = (flags & SKINNING) != 0; - m.enableDualTexture = (flags & DUAL_TEXTURE) != 0; - m.enableNormalMaps = (flags & NORMAL_MAPS) != 0; + m = {}; + m.name = matName; + m.perVertexColor = (flags & PER_VERTEX_COLOR) != 0; + m.enableSkinning = (flags & SKINNING) != 0; + m.enableDualTexture = (flags & DUAL_TEXTURE) != 0; + m.enableNormalMaps = (flags & NORMAL_MAPS) != 0; m.biasedVertexNormals = (flags & BIASED_VERTEX_NORMALS) != 0; - if (mh.Ambient.x == 0 && mh.Ambient.y == 0 && mh.Ambient.z == 0 && mh.Ambient.w == 0 - && mh.Diffuse.x == 0 && mh.Diffuse.y == 0 && mh.Diffuse.z == 0 && mh.Diffuse.w == 0) + if (mh.Ambient.x == 0 && mh.Ambient.y == 0 && mh.Ambient.z == 0 && mh.Ambient.w == 0 && mh.Diffuse.x == 0 && mh.Diffuse.y == 0 + && mh.Diffuse.z == 0 && mh.Diffuse.w == 0) { // SDKMESH material color block is uninitalized; assume defaults m.diffuseColor = XMFLOAT3(1.f, 1.f, 1.f); - m.alphaValue = 1.f; + m.alphaValue = 1.f; } else { - m.ambientColor = GetMaterialColor(mh.Ambient.x, mh.Ambient.y, mh.Ambient.z, srgb); - m.diffuseColor = GetMaterialColor(mh.Diffuse.x, mh.Diffuse.y, mh.Diffuse.z, srgb); + m.ambientColor = GetMaterialColor(mh.Ambient.x, mh.Ambient.y, mh.Ambient.z, srgb); + m.diffuseColor = GetMaterialColor(mh.Diffuse.x, mh.Diffuse.y, mh.Diffuse.z, srgb); m.emissiveColor = GetMaterialColor(mh.Emissive.x, mh.Emissive.y, mh.Emissive.z, srgb); if (mh.Diffuse.w != 1.f && mh.Diffuse.w != 0.f) @@ -142,17 +141,16 @@ namespace } } - m.diffuseTextureIndex = GetUniqueTextureIndex(diffuseName, textureDictionary); + m.diffuseTextureIndex = GetUniqueTextureIndex(diffuseName, textureDictionary); m.specularTextureIndex = GetUniqueTextureIndex(specularName, textureDictionary); - m.normalTextureIndex = GetUniqueTextureIndex(normalName, textureDictionary); + m.normalTextureIndex = GetUniqueTextureIndex(normalName, textureDictionary); - m.samplerIndex = (m.diffuseTextureIndex == -1) ? -1 : static_cast(CommonStates::SamplerIndex::AnisotropicWrap); + m.samplerIndex = (m.diffuseTextureIndex == -1) ? -1 : static_cast(CommonStates::SamplerIndex::AnisotropicWrap); m.samplerIndex2 = (flags & DUAL_TEXTURE) ? static_cast(CommonStates::SamplerIndex::AnisotropicWrap) : -1; } - void InitMaterial( - const DXUT::SDKMESH_MATERIAL_V2& mh, - unsigned int flags, + void InitMaterial(const DXUT::SDKMESH_MATERIAL_V2& mh, + unsigned int flags, _Out_ Model::ModelMaterialInfo& m, _Inout_ std::map& textureDictionary) { @@ -171,50 +169,64 @@ namespace wchar_t emissiveName[DXUT::MAX_TEXTURE_NAME] = {}; ASCIIToWChar(emissiveName, mh.EmissiveTexture); - m = {}; - m.name = matName; - m.perVertexColor = false; - m.enableSkinning = (flags & SKINNING) != 0; - m.enableDualTexture = false; - m.enableNormalMaps = true; + m = {}; + m.name = matName; + m.perVertexColor = false; + m.enableSkinning = (flags & SKINNING) != 0; + m.enableDualTexture = false; + m.enableNormalMaps = true; m.biasedVertexNormals = (flags & BIASED_VERTEX_NORMALS) != 0; - m.alphaValue = (mh.Alpha == 0.f) ? 1.f : mh.Alpha; + m.alphaValue = (mh.Alpha == 0.f) ? 1.f : mh.Alpha; - m.diffuseTextureIndex = GetUniqueTextureIndex(albedoTexture, textureDictionary); + m.diffuseTextureIndex = GetUniqueTextureIndex(albedoTexture, textureDictionary); m.specularTextureIndex = GetUniqueTextureIndex(rmaName, textureDictionary); - m.normalTextureIndex = GetUniqueTextureIndex(normalName, textureDictionary); + m.normalTextureIndex = GetUniqueTextureIndex(normalName, textureDictionary); m.emissiveTextureIndex = GetUniqueTextureIndex(emissiveName, textureDictionary); m.samplerIndex = m.samplerIndex2 = static_cast(CommonStates::SamplerIndex::AnisotropicWrap); } - //-------------------------------------------------------------------------------------- // Direct3D 9 Vertex Declaration to Direct3D 12 Input Layout mapping static_assert(D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT >= 32, "SDKMESH supports decls up to 32 entries"); - unsigned int GetInputLayoutDesc( - _In_reads_(32) const DXUT::D3DVERTEXELEMENT9 decl[], - ModelMeshPart::InputLayoutCollection& inputDesc) + unsigned int GetInputLayoutDesc(_In_reads_(32) const DXUT::D3DVERTEXELEMENT9 decl[], ModelMeshPart::InputLayoutCollection& inputDesc) { - static const D3D12_INPUT_ELEMENT_DESC s_elements[] = - { - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "BINORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "BLENDINDICES", 0, DXGI_FORMAT_R8G8B8A8_UINT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "BLENDWEIGHT", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + static const D3D12_INPUT_ELEMENT_DESC s_elements[] = { + { "SV_Position", + 0, + DXGI_FORMAT_R32G32B32_FLOAT, + 0, + D3D12_APPEND_ALIGNED_ELEMENT, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "BINORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "BLENDINDICES", + 0, + DXGI_FORMAT_R8G8B8A8_UINT, + 0, + D3D12_APPEND_ALIGNED_ELEMENT, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + 0 }, + { "BLENDWEIGHT", + 0, + DXGI_FORMAT_R8G8B8A8_UNORM, + 0, + D3D12_APPEND_ALIGNED_ELEMENT, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + 0 }, }; using namespace DXUT; - uint32_t offset = 0; - uint32_t texcoords = 0; - unsigned int flags = 0; + uint32_t offset = 0; + uint32_t texcoords = 0; + unsigned int flags = 0; bool posfound = false; @@ -240,9 +252,8 @@ namespace else break; } - else if (decl[index].Usage == D3DDECLUSAGE_NORMAL - || decl[index].Usage == D3DDECLUSAGE_TANGENT - || decl[index].Usage == D3DDECLUSAGE_BINORMAL) + else if (decl[index].Usage == D3DDECLUSAGE_NORMAL || decl[index].Usage == D3DDECLUSAGE_TANGENT + || decl[index].Usage == D3DDECLUSAGE_BINORMAL) { size_t base = 1; if (decl[index].Usage == D3DDECLUSAGE_TANGENT) @@ -255,24 +266,56 @@ namespace bool unk = false; switch (decl[index].Type) { - case D3DDECLTYPE_FLOAT3: assert(desc.Format == DXGI_FORMAT_R32G32B32_FLOAT); offset += 12; break; - case D3DDECLTYPE_UBYTE4N: desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; flags |= BIASED_VERTEX_NORMALS; offset += 4; break; - case D3DDECLTYPE_SHORT4N: desc.Format = DXGI_FORMAT_R16G16B16A16_SNORM; offset += 8; break; - case D3DDECLTYPE_FLOAT16_4: desc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; offset += 8; break; - case D3DDECLTYPE_DXGI_R10G10B10A2_UNORM: desc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; flags |= BIASED_VERTEX_NORMALS; offset += 4; break; - case D3DDECLTYPE_DXGI_R11G11B10_FLOAT: desc.Format = DXGI_FORMAT_R11G11B10_FLOAT; flags |= BIASED_VERTEX_NORMALS; offset += 4; break; - case D3DDECLTYPE_DXGI_R8G8B8A8_SNORM: desc.Format = DXGI_FORMAT_R8G8B8A8_SNORM; offset += 4; break; - - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) - case D3DDECLTYPE_DEC3N: desc.Format = DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM; offset += 4; break; - case (32 + DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM): desc.Format = DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM; offset += 4; break; - #else - case D3DDECLTYPE_DEC3N: desc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; flags |= USES_OBSOLETE_DEC3N; offset += 4; break; - #endif - - default: - unk = true; + case D3DDECLTYPE_FLOAT3: + assert(desc.Format == DXGI_FORMAT_R32G32B32_FLOAT); + offset += 12; + break; + case D3DDECLTYPE_UBYTE4N: + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + flags |= BIASED_VERTEX_NORMALS; + offset += 4; + break; + case D3DDECLTYPE_SHORT4N: + desc.Format = DXGI_FORMAT_R16G16B16A16_SNORM; + offset += 8; break; + case D3DDECLTYPE_FLOAT16_4: + desc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + offset += 8; + break; + case D3DDECLTYPE_DXGI_R10G10B10A2_UNORM: + desc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; + flags |= BIASED_VERTEX_NORMALS; + offset += 4; + break; + case D3DDECLTYPE_DXGI_R11G11B10_FLOAT: + desc.Format = DXGI_FORMAT_R11G11B10_FLOAT; + flags |= BIASED_VERTEX_NORMALS; + offset += 4; + break; + case D3DDECLTYPE_DXGI_R8G8B8A8_SNORM: + desc.Format = DXGI_FORMAT_R8G8B8A8_SNORM; + offset += 4; + break; + +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) + case D3DDECLTYPE_DEC3N: + desc.Format = DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM; + offset += 4; + break; + case (32 + DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM): + desc.Format = DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM; + offset += 4; + break; +#else + case D3DDECLTYPE_DEC3N: + desc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; + flags |= USES_OBSOLETE_DEC3N; + offset += 4; + break; +#endif + + default: unk = true; break; } if (unk) @@ -287,16 +330,32 @@ namespace bool unk = false; switch (decl[index].Type) { - case D3DDECLTYPE_FLOAT4: desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; offset += 16; break; - case D3DDECLTYPE_D3DCOLOR: assert(desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM); offset += 4; break; - case D3DDECLTYPE_UBYTE4N: desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; offset += 4; break; - case D3DDECLTYPE_FLOAT16_4: desc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; offset += 8; break; - case D3DDECLTYPE_DXGI_R10G10B10A2_UNORM: desc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; offset += 4; break; - case D3DDECLTYPE_DXGI_R11G11B10_FLOAT: desc.Format = DXGI_FORMAT_R11G11B10_FLOAT; offset += 4; break; - - default: - unk = true; + case D3DDECLTYPE_FLOAT4: + desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + offset += 16; + break; + case D3DDECLTYPE_D3DCOLOR: + assert(desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM); + offset += 4; + break; + case D3DDECLTYPE_UBYTE4N: + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + offset += 4; + break; + case D3DDECLTYPE_FLOAT16_4: + desc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + offset += 8; + break; + case D3DDECLTYPE_DXGI_R10G10B10A2_UNORM: + desc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; + offset += 4; break; + case D3DDECLTYPE_DXGI_R11G11B10_FLOAT: + desc.Format = DXGI_FORMAT_R11G11B10_FLOAT; + offset += 4; + break; + + default: unk = true; break; } if (unk) @@ -309,21 +368,37 @@ namespace else if (decl[index].Usage == D3DDECLUSAGE_TEXCOORD) { D3D12_INPUT_ELEMENT_DESC desc = s_elements[5]; - desc.SemanticIndex = decl[index].UsageIndex; + desc.SemanticIndex = decl[index].UsageIndex; bool unk = false; switch (decl[index].Type) { - case D3DDECLTYPE_FLOAT1: desc.Format = DXGI_FORMAT_R32_FLOAT; offset += 4; break; - case D3DDECLTYPE_FLOAT2: assert(desc.Format == DXGI_FORMAT_R32G32_FLOAT); offset += 8; break; - case D3DDECLTYPE_FLOAT3: desc.Format = DXGI_FORMAT_R32G32B32_FLOAT; offset += 12; break; - case D3DDECLTYPE_FLOAT4: desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; offset += 16; break; - case D3DDECLTYPE_FLOAT16_2: desc.Format = DXGI_FORMAT_R16G16_FLOAT; offset += 4; break; - case D3DDECLTYPE_FLOAT16_4: desc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; offset += 8; break; - - default: - unk = true; + case D3DDECLTYPE_FLOAT1: + desc.Format = DXGI_FORMAT_R32_FLOAT; + offset += 4; + break; + case D3DDECLTYPE_FLOAT2: + assert(desc.Format == DXGI_FORMAT_R32G32_FLOAT); + offset += 8; break; + case D3DDECLTYPE_FLOAT3: + desc.Format = DXGI_FORMAT_R32G32B32_FLOAT; + offset += 12; + break; + case D3DDECLTYPE_FLOAT4: + desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + offset += 16; + break; + case D3DDECLTYPE_FLOAT16_2: + desc.Format = DXGI_FORMAT_R16G16_FLOAT; + offset += 4; + break; + case D3DDECLTYPE_FLOAT16_4: + desc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + offset += 8; + break; + + default: unk = true; break; } if (unk) @@ -369,18 +444,14 @@ namespace return flags; } -} +} // namespace //====================================================================================== // Model Loader //====================================================================================== -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromSDKMESH( - ID3D12Device* device, - const uint8_t* meshData, - size_t idataSize, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr + Model::CreateFromSDKMESH(ID3D12Device* device, const uint8_t* meshData, size_t idataSize, ModelLoaderFlags flags) { if (!meshData) throw std::invalid_argument("meshData cannot be null"); @@ -393,8 +464,8 @@ std::unique_ptr Model::CreateFromSDKMESH( auto header = reinterpret_cast(meshData); const uint64_t headerSize = sizeof(DXUT::SDKMESH_HEADER) - + uint64_t(header->NumVertexBuffers) * sizeof(DXUT::SDKMESH_VERTEX_BUFFER_HEADER) - + uint64_t(header->NumIndexBuffers) * sizeof(DXUT::SDKMESH_INDEX_BUFFER_HEADER); + + uint64_t(header->NumVertexBuffers) * sizeof(DXUT::SDKMESH_VERTEX_BUFFER_HEADER) + + uint64_t(header->NumIndexBuffers) * sizeof(DXUT::SDKMESH_INDEX_BUFFER_HEADER); if (header->HeaderSize != headerSize) throw std::runtime_error("Not a valid SDKMESH file"); @@ -427,8 +498,7 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes > UINT32_MAX) throw std::overflow_error("Too many vertex buffers"); - if (dataSize < header->VertexStreamHeadersOffset - || (dataSize < (header->VertexStreamHeadersOffset + sizeBytes))) + if (dataSize < header->VertexStreamHeadersOffset || (dataSize < (header->VertexStreamHeadersOffset + sizeBytes))) throw std::runtime_error("End of file"); auto vbArray = reinterpret_cast(meshData + header->VertexStreamHeadersOffset); @@ -436,8 +506,7 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes > UINT32_MAX) throw std::runtime_error("Too many index buffers"); - if (dataSize < header->IndexStreamHeadersOffset - || (dataSize < (header->IndexStreamHeadersOffset + sizeBytes))) + if (dataSize < header->IndexStreamHeadersOffset || (dataSize < (header->IndexStreamHeadersOffset + sizeBytes))) throw std::runtime_error("End of file"); auto ibArray = reinterpret_cast(meshData + header->IndexStreamHeadersOffset); @@ -445,8 +514,7 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes > UINT32_MAX) throw std::runtime_error("Too many meshes"); - if (dataSize < header->MeshDataOffset - || (dataSize < (header->MeshDataOffset + sizeBytes))) + if (dataSize < header->MeshDataOffset || (dataSize < (header->MeshDataOffset + sizeBytes))) throw std::runtime_error("End of file"); auto meshArray = reinterpret_cast(meshData + header->MeshDataOffset); @@ -454,8 +522,7 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes > UINT32_MAX) throw std::runtime_error("Too many subsets"); - if (dataSize < header->SubsetDataOffset - || (dataSize < (header->SubsetDataOffset + sizeBytes))) + if (dataSize < header->SubsetDataOffset || (dataSize < (header->SubsetDataOffset + sizeBytes))) throw std::runtime_error("End of file"); auto subsetArray = reinterpret_cast(meshData + header->SubsetDataOffset); @@ -466,8 +533,7 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes > UINT32_MAX) throw std::runtime_error("Too many frames"); - if (dataSize < header->FrameDataOffset - || (dataSize < (header->FrameDataOffset + sizeBytes))) + if (dataSize < header->FrameDataOffset || (dataSize < (header->FrameDataOffset + sizeBytes))) throw std::runtime_error("End of file"); if (flags & ModelLoader_IncludeBones) @@ -480,11 +546,10 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes > UINT32_MAX) throw std::runtime_error("Too many materials"); - if (dataSize < header->MaterialDataOffset - || (dataSize < (header->MaterialDataOffset + sizeBytes))) + if (dataSize < header->MaterialDataOffset || (dataSize < (header->MaterialDataOffset + sizeBytes))) throw std::runtime_error("End of file"); - const DXUT::SDKMESH_MATERIAL* materialArray = nullptr; + const DXUT::SDKMESH_MATERIAL* materialArray = nullptr; const DXUT::SDKMESH_MATERIAL_V2* materialArray_v2 = nullptr; if (header->Version == DXUT::SDKMESH_FILE_VERSION_V2) { @@ -497,8 +562,7 @@ std::unique_ptr Model::CreateFromSDKMESH( // Buffer data const uint64_t bufferDataOffset = header->HeaderSize + header->NonBufferDataSize; - if ((dataSize < bufferDataOffset) - || (dataSize < bufferDataOffset + header->BufferDataSize)) + if ((dataSize < bufferDataOffset) || (dataSize < bufferDataOffset + header->BufferDataSize)) throw std::runtime_error("End of file"); const uint8_t* bufferData = meshData + bufferDataOffset; @@ -523,11 +587,10 @@ std::unique_ptr Model::CreateFromSDKMESH( throw std::runtime_error("VB too large for DirectX 12"); } - if (dataSize < vh.DataOffset - || (dataSize < vh.DataOffset + vh.SizeBytes)) + if (dataSize < vh.DataOffset || (dataSize < vh.DataOffset + vh.SizeBytes)) throw std::runtime_error("End of file"); - vbDecls[j] = std::make_shared(); + vbDecls[j] = std::make_shared(); unsigned int ilflags = GetInputLayoutDesc(vh.Decl, *vbDecls[j].get()); if (flags & ModelLoader_DisableSkinning) @@ -549,7 +612,8 @@ std::unique_ptr Model::CreateFromSDKMESH( if (dec3nwarning) { - DebugTrace("WARNING: Vertex declaration uses legacy Direct3D 9 D3DDECLTYPE_DEC3N which has no DXGI equivalent\n" + DebugTrace( + "WARNING: Vertex declaration uses legacy Direct3D 9 D3DDECLTYPE_DEC3N which has no DXGI equivalent\n" " (treating as DXGI_FORMAT_R10G10B10A2_UNORM which is not a signed format)\n"); } @@ -567,8 +631,7 @@ std::unique_ptr Model::CreateFromSDKMESH( throw std::runtime_error("IB too large for DirectX 12"); } - if (dataSize < ih.DataOffset - || (dataSize < ih.DataOffset + ih.SizeBytes)) + if (dataSize < ih.DataOffset || (dataSize < ih.DataOffset + ih.SizeBytes)) throw std::runtime_error("End of file"); if (ih.IndexType != DXUT::IT_16BIT && ih.IndexType != DXUT::IT_32BIT) @@ -590,9 +653,7 @@ std::unique_ptr Model::CreateFromSDKMESH( { auto& mh = meshArray[meshIndex]; - if (!mh.NumSubsets - || !mh.NumVertexBuffers - || mh.IndexBuffer >= header->NumIndexBuffers + if (!mh.NumSubsets || !mh.NumVertexBuffers || mh.IndexBuffer >= header->NumIndexBuffers || mh.VertexBuffers[0] >= header->NumVertexBuffers) throw std::out_of_range("Invalid mesh found"); @@ -602,8 +663,7 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes >= UINT32_MAX) throw std::runtime_error("Too many subsets"); - if (dataSize < mh.SubsetOffset - || (dataSize < mh.SubsetOffset + sizeBytes)) + if (dataSize < mh.SubsetOffset || (dataSize < mh.SubsetOffset + sizeBytes)) throw std::runtime_error("End of file"); auto subsets = reinterpret_cast(meshData + mh.SubsetOffset); @@ -615,8 +675,7 @@ std::unique_ptr Model::CreateFromSDKMESH( if (sizeBytes >= UINT32_MAX) throw std::runtime_error("Too many frame influences"); - if (dataSize < mh.FrameInfluenceOffset - || (dataSize < mh.FrameInfluenceOffset + sizeBytes)) + if (dataSize < mh.FrameInfluenceOffset || (dataSize < mh.FrameInfluenceOffset + sizeBytes)) throw std::runtime_error("End of file"); if (flags & ModelLoader_IncludeBones) @@ -625,14 +684,14 @@ std::unique_ptr Model::CreateFromSDKMESH( } } - auto mesh = std::make_shared(); + auto mesh = std::make_shared(); wchar_t meshName[DXUT::MAX_MESH_NAME] = {}; ASCIIToWChar(meshName, mh.Name); mesh->name = meshName; // Extents - mesh->boundingBox.Center = mh.BoundingBoxCenter; + mesh->boundingBox.Center = mh.BoundingBoxCenter; mesh->boundingBox.Extents = mh.BoundingBoxExtents; BoundingSphere::CreateFromBoundingBox(mesh->boundingSphere, mesh->boundingBox); @@ -654,22 +713,20 @@ std::unique_ptr Model::CreateFromSDKMESH( D3D_PRIMITIVE_TOPOLOGY primType; switch (subset.PrimitiveType) { - case DXUT::PT_TRIANGLE_LIST: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; - case DXUT::PT_TRIANGLE_STRIP: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; - case DXUT::PT_LINE_LIST: primType = D3D_PRIMITIVE_TOPOLOGY_LINELIST; break; - case DXUT::PT_LINE_STRIP: primType = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; break; - case DXUT::PT_POINT_LIST: primType = D3D_PRIMITIVE_TOPOLOGY_POINTLIST; break; - case DXUT::PT_TRIANGLE_LIST_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; break; - case DXUT::PT_TRIANGLE_STRIP_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; break; - case DXUT::PT_LINE_LIST_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; break; - case DXUT::PT_LINE_STRIP_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; break; + case DXUT::PT_TRIANGLE_LIST: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; + case DXUT::PT_TRIANGLE_STRIP: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; + case DXUT::PT_LINE_LIST: primType = D3D_PRIMITIVE_TOPOLOGY_LINELIST; break; + case DXUT::PT_LINE_STRIP: primType = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; break; + case DXUT::PT_POINT_LIST: primType = D3D_PRIMITIVE_TOPOLOGY_POINTLIST; break; + case DXUT::PT_TRIANGLE_LIST_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; break; + case DXUT::PT_TRIANGLE_STRIP_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; break; + case DXUT::PT_LINE_LIST_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; break; + case DXUT::PT_LINE_STRIP_ADJ: primType = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; break; case DXUT::PT_QUAD_PATCH_LIST: - case DXUT::PT_TRIANGLE_PATCH_LIST: - throw std::runtime_error("Direct3D9 era tessellation not supported"); + case DXUT::PT_TRIANGLE_PATCH_LIST: throw std::runtime_error("Direct3D9 era tessellation not supported"); - default: - throw std::runtime_error("Unknown primitive type"); + default: throw std::runtime_error("Unknown primitive type"); } if (subset.MaterialID >= header->NumMaterials) @@ -680,16 +737,11 @@ std::unique_ptr Model::CreateFromSDKMESH( const size_t vi = mh.VertexBuffers[0]; if (materialArray_v2) { - InitMaterial( - materialArray_v2[subset.MaterialID], - materialFlags[vi], - mat, - textureDictionary); + InitMaterial(materialArray_v2[subset.MaterialID], materialFlags[vi], mat, textureDictionary); } else { - InitMaterial( - materialArray[subset.MaterialID], + InitMaterial(materialArray[subset.MaterialID], materialFlags[vi], mat, textureDictionary, @@ -701,30 +753,30 @@ std::unique_ptr Model::CreateFromSDKMESH( const auto& vh = vbArray[mh.VertexBuffers[0]]; const auto& ih = ibArray[mh.IndexBuffer]; - part->indexCount = static_cast(subset.IndexCount); - part->startIndex = static_cast(subset.IndexStart); - part->vertexOffset = static_cast(subset.VertexStart); - part->vertexStride = static_cast(vh.StrideBytes); - part->vertexCount = static_cast(subset.VertexCount); + part->indexCount = static_cast(subset.IndexCount); + part->startIndex = static_cast(subset.IndexStart); + part->vertexOffset = static_cast(subset.VertexStart); + part->vertexStride = static_cast(vh.StrideBytes); + part->vertexCount = static_cast(subset.VertexCount); part->primitiveType = primType; - part->indexFormat = (ibArray[mh.IndexBuffer].IndexType == DXUT::IT_32BIT) ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; + part->indexFormat = (ibArray[mh.IndexBuffer].IndexType == DXUT::IT_32BIT) ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; // Vertex data - auto verts = bufferData + (vh.DataOffset - bufferDataOffset); - const auto vbytes = static_cast(vh.SizeBytes); + auto verts = bufferData + (vh.DataOffset - bufferDataOffset); + const auto vbytes = static_cast(vh.SizeBytes); part->vertexBufferSize = static_cast(vh.SizeBytes); - part->vertexBuffer = GraphicsMemory::Get(device).Allocate(vbytes, 16, GraphicsMemory::TAG_VERTEX); + part->vertexBuffer = GraphicsMemory::Get(device).Allocate(vbytes, 16, GraphicsMemory::TAG_VERTEX); memcpy(part->vertexBuffer.Memory(), verts, vbytes); // Index data - auto indices = bufferData + (ih.DataOffset - bufferDataOffset); - const auto ibytes = static_cast(ih.SizeBytes); + auto indices = bufferData + (ih.DataOffset - bufferDataOffset); + const auto ibytes = static_cast(ih.SizeBytes); part->indexBufferSize = static_cast(ih.SizeBytes); - part->indexBuffer = GraphicsMemory::Get(device).Allocate(ibytes, 16, GraphicsMemory::TAG_INDEX); + part->indexBuffer = GraphicsMemory::Get(device).Allocate(ibytes, 16, GraphicsMemory::TAG_INDEX); memcpy(part->indexBuffer.Memory(), indices, ibytes); part->materialIndex = subset.MaterialID; - part->vbDecl = vbDecls[mh.VertexBuffers[0]]; + part->vbDecl = vbDecls[mh.VertexBuffers[0]]; if (mat.alphaValue < 1.0f) mesh->alphaMeshParts.emplace_back(std::move(part)); @@ -754,10 +806,7 @@ std::unique_ptr Model::CreateFromSDKMESH( for (uint32_t j = 0; j < header->NumFrames; ++j) { - ModelBone bone( - frameArray[j].ParentFrame, - frameArray[j].ChildFrame, - frameArray[j].SiblingFrame); + ModelBone bone(frameArray[j].ParentFrame, frameArray[j].ChildFrame, frameArray[j].SiblingFrame); wchar_t boneName[DXUT::MAX_FRAME_NAME] = {}; ASCIIToWChar(boneName, frameArray[j].Name); @@ -801,21 +850,16 @@ std::unique_ptr Model::CreateFromSDKMESH( return model; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromSDKMESH( - ID3D12Device* device, - const wchar_t* szFileName, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr + Model::CreateFromSDKMESH(ID3D12Device* device, const wchar_t* szFileName, ModelLoaderFlags flags) { - size_t dataSize = 0; + size_t dataSize = 0; std::unique_ptr data; - HRESULT hr = BinaryReader::ReadEntireFile(szFileName, data, &dataSize); + HRESULT hr = BinaryReader::ReadEntireFile(szFileName, data, &dataSize); if (FAILED(hr)) { - DebugTrace("ERROR: CreateFromSDKMESH failed (%08X) loading '%ls'\n", - static_cast(hr), szFileName); + DebugTrace("ERROR: CreateFromSDKMESH failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); throw std::runtime_error("CreateFromSDKMESH"); } @@ -826,17 +870,13 @@ std::unique_ptr Model::CreateFromSDKMESH( return model; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromSDKMESH( - ID3D12Device* device, - const __wchar_t* szFileName, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr + Model::CreateFromSDKMESH(ID3D12Device* device, const __wchar_t* szFileName, ModelLoaderFlags flags) { return CreateFromSDKMESH(device, reinterpret_cast(szFileName), flags); } diff --git a/Src/ModelLoadVBO.cpp b/Src/ModelLoadVBO.cpp index 79b0b556..b7ede69b 100644 --- a/Src/ModelLoadVBO.cpp +++ b/Src/ModelLoadVBO.cpp @@ -28,10 +28,10 @@ namespace { //-------------------------------------------------------------------------------------- // Shared VB input element description - INIT_ONCE g_InitOnce = INIT_ONCE_STATIC_INIT; + INIT_ONCE g_InitOnce = INIT_ONCE_STATIC_INIT; std::shared_ptr g_vbdecl; - BOOL CALLBACK InitializeDecl(PINIT_ONCE initOnce, PVOID Parameter, PVOID *lpContext) + BOOL CALLBACK InitializeDecl(PINIT_ONCE initOnce, PVOID Parameter, PVOID* lpContext) { UNREFERENCED_PARAMETER(initOnce); UNREFERENCED_PARAMETER(Parameter); @@ -42,15 +42,11 @@ namespace return TRUE; } -} - +} // namespace //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromVBO( - ID3D12Device* device, - const uint8_t* meshData, size_t dataSize, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr + Model::CreateFromVBO(ID3D12Device* device, const uint8_t* meshData, size_t dataSize, ModelLoaderFlags flags) { if (!InitOnceExecuteOnce(&g_InitOnce, InitializeDecl, nullptr, nullptr)) throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "InitOnceExecuteOnce"); @@ -106,17 +102,17 @@ std::unique_ptr Model::CreateFromVBO( auto ib = GraphicsMemory::Get(device).Allocate(indexSize, 16, GraphicsMemory::TAG_INDEX); memcpy(ib.Memory(), indices, indexSize); - auto part = std::make_unique(0); - part->materialIndex = 0; - part->indexCount = header->numIndices; - part->startIndex = 0; - part->vertexStride = static_cast(sizeof(VertexPositionNormalTexture)); - part->vertexCount = header->numVertices; - part->indexBufferSize = static_cast(indexSize); + auto part = std::make_unique(0); + part->materialIndex = 0; + part->indexCount = header->numIndices; + part->startIndex = 0; + part->vertexStride = static_cast(sizeof(VertexPositionNormalTexture)); + part->vertexCount = header->numVertices; + part->indexBufferSize = static_cast(indexSize); part->vertexBufferSize = static_cast(vertSize); - part->indexBuffer = std::move(ib); - part->vertexBuffer = std::move(vb); - part->vbDecl = g_vbdecl; + part->indexBuffer = std::move(ib); + part->vertexBuffer = std::move(vb); + part->vbDecl = g_vbdecl; auto mesh = std::make_shared(); BoundingSphere::CreateFromPoints(mesh->boundingSphere, header->numVertices, &verts->position, sizeof(VertexPositionNormalTexture)); @@ -131,21 +127,15 @@ std::unique_ptr Model::CreateFromVBO( return model; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromVBO( - ID3D12Device* device, - const wchar_t* szFileName, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr Model::CreateFromVBO(ID3D12Device* device, const wchar_t* szFileName, ModelLoaderFlags flags) { - size_t dataSize = 0; + size_t dataSize = 0; std::unique_ptr data; - HRESULT hr = BinaryReader::ReadEntireFile(szFileName, data, &dataSize); + HRESULT hr = BinaryReader::ReadEntireFile(szFileName, data, &dataSize); if (FAILED(hr)) { - DebugTrace("ERROR: CreateFromVBO failed (%08X) loading '%ls'\n", - static_cast(hr), szFileName); + DebugTrace("ERROR: CreateFromVBO failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); throw std::runtime_error("CreateFromVBO"); } @@ -156,17 +146,13 @@ std::unique_ptr Model::CreateFromVBO( return model; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromVBO( - ID3D12Device* device, - const __wchar_t* szFileName, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr + Model::CreateFromVBO(ID3D12Device* device, const __wchar_t* szFileName, ModelLoaderFlags flags) { return CreateFromVBO(device, reinterpret_cast(szFileName), flags); } diff --git a/Src/Mouse.cpp b/Src/Mouse.cpp index b49f4d23..2a01a634 100644 --- a/Src/Mouse.cpp +++ b/Src/Mouse.cpp @@ -31,7 +31,7 @@ using namespace GameInput::v2; using namespace GameInput::v3; #endif -using GameInputCreateFn = HRESULT(*)(IGameInput**); +using GameInputCreateFn = HRESULT (*)(IGameInput**); #ifdef __clang__ #pragma clang diagnostic ignored "-Wmicrosoft-cast" @@ -66,21 +66,21 @@ using GameInputCreateFn = HRESULT(*)(IGameInput**); class Mouse::Impl { public: - explicit Impl(Mouse* owner) noexcept(false) : - mState{}, - mOwner(owner), - mScale(1.f), - mConnected(0), - mDeviceToken(0), - mWindow(nullptr), - mMode(MODE_ABSOLUTE), - mAutoReset(true), - mScrollWheelCurrent(0), - mRelativeX(INT64_MAX), - mRelativeY(INT64_MAX), - mLastX(INT64_MAX), - mLastY(INT64_MAX), - mRelativeWheelY(INT64_MAX) + explicit Impl(Mouse* owner) noexcept(false) + : mState{}, + mOwner(owner), + mScale(1.f), + mConnected(0), + mDeviceToken(0), + mWindow(nullptr), + mMode(MODE_ABSOLUTE), + mAutoReset(true), + mScrollWheelCurrent(0), + mRelativeX(INT64_MAX), + mRelativeY(INT64_MAX), + mLastX(INT64_MAX), + mLastY(INT64_MAX), + mRelativeWheelY(INT64_MAX) { if (s_mouse) { @@ -89,15 +89,16 @@ class Mouse::Impl s_mouse = this; - #if defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION) +#if defined(_GAMING_XBOX) || defined(GAMEINPUT_API_VERSION) HRESULT hr = GameInputCreate(mGameInput.GetAddressOf()); - #else +#else if (!s_gameInputCreate) { s_gameInputModule = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (s_gameInputModule) { - s_gameInputCreate = reinterpret_cast(reinterpret_cast(GetProcAddress(s_gameInputModule, "GameInputCreate"))); + s_gameInputCreate + = reinterpret_cast(reinterpret_cast(GetProcAddress(s_gameInputModule, "GameInputCreate"))); } if (!s_gameInputCreate) @@ -108,11 +109,10 @@ class Mouse::Impl } HRESULT hr = s_gameInputCreate(mGameInput.GetAddressOf()); - #endif +#endif if (SUCCEEDED(hr)) { - ThrowIfFailed(mGameInput->RegisterDeviceCallback( - nullptr, + ThrowIfFailed(mGameInput->RegisterDeviceCallback(nullptr, GameInputKindMouse, GameInputDeviceConnected, GameInputBlockingEnumeration, @@ -123,13 +123,13 @@ class Mouse::Impl else { DebugTrace("ERROR: GameInputCreate [mouse] failed with %08X\n", static_cast(hr)); - #ifdef _GAMING_XBOX +#ifdef _GAMING_XBOX throw com_exception(hr); - #else +#else DebugTrace( "\t**** Install the latest GameInputRedist package on this system. ****\n" "\t**** NOTE: All calls to GetState will be reported as 'not connected'. ****\n"); - #endif +#endif } mScrollWheelValue.reset(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE)); @@ -139,11 +139,11 @@ class Mouse::Impl } } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; ~Impl() { @@ -151,11 +151,11 @@ class Mouse::Impl { if (mGameInput) { - #if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) +#if defined(GAMEINPUT_API_VERSION) && (GAMEINPUT_API_VERSION >= 1) if (!mGameInput->UnregisterCallback(mDeviceToken)) - #else +#else if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) - #endif +#endif { DebugTrace("ERROR: GameInput::UnregisterCallback [mouse] failed"); } @@ -193,16 +193,16 @@ class Mouse::Impl GameInputMouseState mouse; if (reading->GetMouseState(&mouse)) { - state.leftButton = (mouse.buttons & GameInputMouseLeftButton) != 0; + state.leftButton = (mouse.buttons & GameInputMouseLeftButton) != 0; state.middleButton = (mouse.buttons & GameInputMouseMiddleButton) != 0; - state.rightButton = (mouse.buttons & GameInputMouseRightButton) != 0; - state.xButton1 = (mouse.buttons & GameInputMouseButton4) != 0; - state.xButton2 = (mouse.buttons & GameInputMouseButton5) != 0; + state.rightButton = (mouse.buttons & GameInputMouseRightButton) != 0; + state.xButton1 = (mouse.buttons & GameInputMouseButton4) != 0; + state.xButton2 = (mouse.buttons & GameInputMouseButton5) != 0; if (mRelativeX != INT64_MAX) { - state.x = static_cast(mouse.positionX - mRelativeX); - state.y = static_cast(mouse.positionY - mRelativeY); + state.x = static_cast(mouse.positionX - mRelativeX); + state.y = static_cast(mouse.positionY - mRelativeY); int scrollDelta = static_cast(mouse.wheelY - mRelativeWheelY); mScrollWheelCurrent += scrollDelta; } @@ -213,8 +213,8 @@ class Mouse::Impl mRelativeY = mouse.positionY; } - mLastX = mouse.positionX; - mLastY = mouse.positionY; + mLastX = mouse.positionX; + mLastY = mouse.positionY; mRelativeWheelY = mouse.wheelY; } } @@ -224,25 +224,19 @@ class Mouse::Impl state.scrollWheelValue = mScrollWheelCurrent; } - void ResetScrollWheelValue() noexcept - { - SetEvent(mScrollWheelValue.get()); - } + void ResetScrollWheelValue() noexcept { SetEvent(mScrollWheelValue.get()); } - void SetWindow(HWND window) - { - mWindow = window; - } + void SetWindow(HWND window) { mWindow = window; } void SetMode(Mode mode) { if (mMode == mode) return; - mMode = mode; + mMode = mode; mLastX = mRelativeX = INT64_MAX; mLastY = mRelativeY = INT64_MAX; - mRelativeWheelY = INT64_MAX; + mRelativeWheelY = INT64_MAX; if (mode == MODE_RELATIVE) { @@ -253,7 +247,7 @@ class Mouse::Impl { ShowCursor(TRUE); - #ifndef _GAMING_XBOX +#ifndef _GAMING_XBOX POINT point; point.x = mState.x; point.y = mState.y; @@ -264,7 +258,7 @@ class Mouse::Impl } ClipCursor(nullptr); - #endif +#endif } } @@ -279,10 +273,7 @@ class Mouse::Impl } } - bool IsConnected() const noexcept - { - return mConnected > 0; - } + bool IsConnected() const noexcept { return mConnected > 0; } bool IsVisible() const noexcept { @@ -314,44 +305,43 @@ class Mouse::Impl } } - State mState; - Mouse* mOwner; - float mScale; - uint32_t mConnected; + State mState; + Mouse* mOwner; + float mScale; + uint32_t mConnected; static Mouse::Impl* s_mouse; private: - ComPtr mGameInput; - GameInputCallbackToken mDeviceToken; + ComPtr mGameInput; + GameInputCallbackToken mDeviceToken; - HWND mWindow; - Mode mMode; - bool mAutoReset; + HWND mWindow; + Mode mMode; + bool mAutoReset; - ScopedHandle mScrollWheelValue; + ScopedHandle mScrollWheelValue; - mutable int mScrollWheelCurrent; - mutable int64_t mRelativeX; - mutable int64_t mRelativeY; - mutable int64_t mLastX; - mutable int64_t mLastY; - mutable int64_t mRelativeWheelY; + mutable int mScrollWheelCurrent; + mutable int64_t mRelativeX; + mutable int64_t mRelativeY; + mutable int64_t mLastX; + mutable int64_t mLastY; + mutable int64_t mRelativeWheelY; friend void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam); - static void CALLBACK OnGameInputDevice( - _In_ GameInputCallbackToken, - _In_ void * context, - _In_ IGameInputDevice *, - _In_ uint64_t, + static void CALLBACK OnGameInputDevice(_In_ GameInputCallbackToken, + _In_ void* context, + _In_ IGameInputDevice*, + _In_ uint64_t, _In_ GameInputDeviceStatus currentStatus, _In_ GameInputDeviceStatus previousStatus) noexcept { auto impl = reinterpret_cast(context); const bool wasConnected = (previousStatus & GameInputDeviceConnected) != 0; - const bool isConnected = (currentStatus & GameInputDeviceConnected) != 0; + const bool isConnected = (currentStatus & GameInputDeviceConnected) != 0; if (isConnected && !wasConnected) { @@ -365,7 +355,7 @@ class Mouse::Impl void ClipToWindow() noexcept { - #ifndef _GAMING_XBOX +#ifndef _GAMING_XBOX assert(mWindow != nullptr); RECT rect; @@ -383,23 +373,23 @@ class Mouse::Impl std::ignore = MapWindowPoints(mWindow, nullptr, &lr, 1); rect.left = ul.x; - rect.top = ul.y; + rect.top = ul.y; - rect.right = lr.x; + rect.right = lr.x; rect.bottom = lr.y; ClipCursor(&rect); - #endif +#endif } #if !defined(_GAMING_XBOX) && !defined(GAMEINPUT_API_VERSION) - static HMODULE s_gameInputModule; + static HMODULE s_gameInputModule; static GameInputCreateFn s_gameInputCreate; #endif }; #if !defined(_GAMING_XBOX) && !defined(GAMEINPUT_API_VERSION) -HMODULE Mouse::Impl::s_gameInputModule = nullptr; +HMODULE Mouse::Impl::s_gameInputModule = nullptr; GameInputCreateFn Mouse::Impl::s_gameInputCreate = nullptr; #endif @@ -438,9 +428,9 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) } else { - #ifndef _GAMING_XBOX +#ifndef _GAMING_XBOX ClipCursor(nullptr); - #endif +#endif } } else @@ -449,32 +439,19 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) } return; - case WM_MOUSEMOVE: - break; + case WM_MOUSEMOVE: break; - case WM_LBUTTONDOWN: - pImpl->mState.leftButton = true; - break; + case WM_LBUTTONDOWN: pImpl->mState.leftButton = true; break; - case WM_LBUTTONUP: - pImpl->mState.leftButton = false; - break; + case WM_LBUTTONUP: pImpl->mState.leftButton = false; break; - case WM_RBUTTONDOWN: - pImpl->mState.rightButton = true; - break; + case WM_RBUTTONDOWN: pImpl->mState.rightButton = true; break; - case WM_RBUTTONUP: - pImpl->mState.rightButton = false; - break; + case WM_RBUTTONUP: pImpl->mState.rightButton = false; break; - case WM_MBUTTONDOWN: - pImpl->mState.middleButton = true; - break; + case WM_MBUTTONDOWN: pImpl->mState.middleButton = true; break; - case WM_MBUTTONUP: - pImpl->mState.middleButton = false; - break; + case WM_MBUTTONUP: pImpl->mState.middleButton = false; break; case WM_MOUSEWHEEL: if (pImpl->mMode == MODE_ABSOLUTE) @@ -486,32 +463,22 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) case WM_XBUTTONDOWN: switch (GET_XBUTTON_WPARAM(wParam)) { - case XBUTTON1: - pImpl->mState.xButton1 = true; - break; + case XBUTTON1: pImpl->mState.xButton1 = true; break; - case XBUTTON2: - pImpl->mState.xButton2 = true; - break; + case XBUTTON2: pImpl->mState.xButton2 = true; break; - default: - break; + default: break; } break; case WM_XBUTTONUP: switch (GET_XBUTTON_WPARAM(wParam)) { - case XBUTTON1: - pImpl->mState.xButton1 = false; - break; + case XBUTTON1: pImpl->mState.xButton1 = false; break; - case XBUTTON2: - pImpl->mState.xButton2 = false; - break; + case XBUTTON2: pImpl->mState.xButton2 = false; break; - default: - break; + default: break; } break; @@ -548,7 +515,6 @@ void Mouse::SetWindow(HWND window) pImpl->SetWindow(window); } - #elif defined(USING_COREWINDOW) //====================================================================================== @@ -578,20 +544,20 @@ constexpr float USER_DEFAULT_SCREEN_DPI = 96.f; class Mouse::Impl { public: - explicit Impl(Mouse* owner) noexcept(false) : - mState{}, - mOwner(owner), - mDPI(USER_DEFAULT_SCREEN_DPI), - mMode(MODE_ABSOLUTE), - mAutoReset(true), - mLastX(0), - mLastY(0), - mPointerPressedToken{}, - mPointerReleasedToken{}, - mPointerMovedToken{}, - mPointerWheelToken{}, - mPointerMouseMovedToken{}, - mActivatedToken{} + explicit Impl(Mouse* owner) noexcept(false) + : mState{}, + mOwner(owner), + mDPI(USER_DEFAULT_SCREEN_DPI), + mMode(MODE_ABSOLUTE), + mAutoReset(true), + mLastX(0), + mLastY(0), + mPointerPressedToken{}, + mPointerReleasedToken{}, + mPointerMovedToken{}, + mPointerWheelToken{}, + mPointerMouseMovedToken{}, + mActivatedToken{} { if (s_mouse) { @@ -602,8 +568,7 @@ class Mouse::Impl mScrollWheelValue.reset(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE)); mRelativeRead.reset(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE)); - if (!mScrollWheelValue - || !mRelativeRead) + if (!mScrollWheelValue || !mRelativeRead) { throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } @@ -654,10 +619,7 @@ class Mouse::Impl state.positionMode = mMode; } - void ResetScrollWheelValue() noexcept - { - SetEvent(mScrollWheelValue.get()); - } + void ResetScrollWheelValue() noexcept { SetEvent(mScrollWheelValue.get()); } void SetMode(Mode mode) { @@ -814,18 +776,20 @@ class Mouse::Impl } ComPtr mouseStatics; - HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Devices_Input_MouseDevice).Get(), mouseStatics.GetAddressOf()); + HRESULT hr + = GetActivationFactory(HStringReference(RuntimeClass_Windows_Devices_Input_MouseDevice).Get(), mouseStatics.GetAddressOf()); ThrowIfFailed(hr); hr = mouseStatics->GetForCurrentView(mMouse.ReleaseAndGetAddressOf()); ThrowIfFailed(hr); - using MouseMovedHandler = __FITypedEventHandler_2_Windows__CDevices__CInput__CMouseDevice_Windows__CDevices__CInput__CMouseEventArgs; + using MouseMovedHandler + = __FITypedEventHandler_2_Windows__CDevices__CInput__CMouseDevice_Windows__CDevices__CInput__CMouseEventArgs; hr = mMouse->add_MouseMoved(Callback(MouseMovedEvent).Get(), &mPointerMouseMovedToken); ThrowIfFailed(hr); using PointerHandler = __FITypedEventHandler_2_Windows__CUI__CCore__CCoreWindow_Windows__CUI__CCore__CPointerEventArgs; - auto cb = Callback(PointerEvent); + auto cb = Callback(PointerEvent); hr = window->add_PointerPressed(cb.Get(), &mPointerPressedToken); ThrowIfFailed(hr); @@ -840,28 +804,28 @@ class Mouse::Impl ThrowIfFailed(hr); using ActivatedHandler = __FITypedEventHandler_2_Windows__CUI__CCore__CCoreWindow_Windows__CUI__CCore__CWindowActivatedEventArgs; - hr = window->add_Activated(Callback(ActivatedEvent).Get(), &mActivatedToken); + hr = window->add_Activated(Callback(ActivatedEvent).Get(), &mActivatedToken); ThrowIfFailed(hr); } - mutable State mState; - Mouse* mOwner; - float mDPI; + mutable State mState; + Mouse* mOwner; + float mDPI; static Mouse::Impl* s_mouse; private: - Mode mMode; - bool mAutoReset; - int mLastX; - int mLastY; + Mode mMode; + bool mAutoReset; + int mLastX; + int mLastY; - ComPtr mWindow; + ComPtr mWindow; ComPtr mMouse; - ComPtr mCursor; + ComPtr mCursor; - ScopedHandle mScrollWheelValue; - ScopedHandle mRelativeRead; + ScopedHandle mScrollWheelValue; + ScopedHandle mRelativeRead; EventRegistrationToken mPointerPressedToken; EventRegistrationToken mPointerReleasedToken; @@ -874,25 +838,25 @@ class Mouse::Impl { if (mWindow) { - std::ignore = mWindow->remove_PointerPressed(mPointerPressedToken); + std::ignore = mWindow->remove_PointerPressed(mPointerPressedToken); mPointerPressedToken.value = 0; - std::ignore = mWindow->remove_PointerReleased(mPointerReleasedToken); + std::ignore = mWindow->remove_PointerReleased(mPointerReleasedToken); mPointerReleasedToken.value = 0; - std::ignore = mWindow->remove_PointerMoved(mPointerMovedToken); + std::ignore = mWindow->remove_PointerMoved(mPointerMovedToken); mPointerMovedToken.value = 0; - std::ignore = mWindow->remove_PointerWheelChanged(mPointerWheelToken); + std::ignore = mWindow->remove_PointerWheelChanged(mPointerWheelToken); mPointerWheelToken.value = 0; - std::ignore = mWindow->remove_Activated(mActivatedToken); + std::ignore = mWindow->remove_Activated(mActivatedToken); mActivatedToken.value = 0; } if (mMouse) { - std::ignore = mMouse->remove_MouseMoved(mPointerMouseMovedToken); + std::ignore = mMouse->remove_MouseMoved(mPointerMouseMovedToken); mPointerMouseMovedToken.value = 0; } } @@ -907,7 +871,7 @@ class Mouse::Impl return S_OK; ComPtr currentPoint; - HRESULT hr = args->get_CurrentPoint(currentPoint.GetAddressOf()); + HRESULT hr = args->get_CurrentPoint(currentPoint.GetAddressOf()); ThrowIfFailed(hr); ComPtr pointerDevice; @@ -971,7 +935,7 @@ class Mouse::Impl return S_OK; ComPtr currentPoint; - HRESULT hr = args->get_CurrentPoint(currentPoint.GetAddressOf()); + HRESULT hr = args->get_CurrentPoint(currentPoint.GetAddressOf()); ThrowIfFailed(hr); ComPtr pointerDevice; @@ -1036,7 +1000,7 @@ class Mouse::Impl if (s_mouse->mMode == MODE_RELATIVE) { MouseDelta delta; - HRESULT hr = args->get_MouseDelta(&delta); + HRESULT hr = args->get_MouseDelta(&delta); ThrowIfFailed(hr); s_mouse->mState.x += delta.X; @@ -1062,16 +1026,13 @@ class Mouse::Impl } }; - Mouse::Impl* Mouse::Impl::s_mouse = nullptr; - void Mouse::SetWindow(ABI::Windows::UI::Core::ICoreWindow* window) { pImpl->SetWindow(window); } - void Mouse::SetDpi(float dpi) { auto pImpl = Impl::s_mouse; @@ -1082,7 +1043,6 @@ void Mouse::SetDpi(float dpi) pImpl->mDPI = dpi; } - #else //====================================================================================== @@ -1124,17 +1084,17 @@ void Mouse::SetDpi(float dpi) class Mouse::Impl { public: - explicit Impl(Mouse* owner) noexcept(false) : - mState{}, - mOwner(owner), - mWindow(nullptr), - mMode(MODE_ABSOLUTE), - mLastX(0), - mLastY(0), - mRelativeX(INT32_MAX), - mRelativeY(INT32_MAX), - mInFocus(true), - mAutoReset(true) + explicit Impl(Mouse* owner) noexcept(false) + : mState{}, + mOwner(owner), + mWindow(nullptr), + mMode(MODE_ABSOLUTE), + mLastX(0), + mLastY(0), + mRelativeX(INT32_MAX), + mRelativeY(INT32_MAX), + mInFocus(true), + mAutoReset(true) { if (s_mouse) { @@ -1147,25 +1107,19 @@ class Mouse::Impl mRelativeRead.reset(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE)); mAbsoluteMode.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); mRelativeMode.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); - if (!mScrollWheelValue - || !mRelativeRead - || !mAbsoluteMode - || !mRelativeMode) + if (!mScrollWheelValue || !mRelativeRead || !mAbsoluteMode || !mRelativeMode) { throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } - Impl(Impl&&) = default; - Impl& operator= (Impl&&) = default; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - Impl(Impl const&) = delete; - Impl& operator= (Impl const&) = delete; + Impl(Impl const&) = delete; + Impl& operator=(Impl const&) = delete; - ~Impl() - { - s_mouse = nullptr; - } + ~Impl() { s_mouse = nullptr; } void GetState(State& state) const { @@ -1204,10 +1158,7 @@ class Mouse::Impl } } - void ResetScrollWheelValue() noexcept - { - SetEvent(mScrollWheelValue.get()); - } + void ResetScrollWheelValue() noexcept { SetEvent(mScrollWheelValue.get()); } void SetMode(Mode mode) { @@ -1220,9 +1171,9 @@ class Mouse::Impl // Send a WM_HOVER as a way to 'kick' the message processing even if the mouse is still. TRACKMOUSEEVENT tme; - tme.cbSize = sizeof(tme); - tme.dwFlags = TME_HOVER; - tme.hwndTrack = mWindow; + tme.cbSize = sizeof(tme); + tme.dwFlags = TME_HOVER; + tme.hwndTrack = mWindow; tme.dwHoverTime = 1; if (!TrackMouseEvent(&tme)) { @@ -1240,10 +1191,7 @@ class Mouse::Impl } } - bool IsConnected() const noexcept - { - return GetSystemMetrics(SM_MOUSEPRESENT) != 0; - } + bool IsConnected() const noexcept { return GetSystemMetrics(SM_MOUSEPRESENT) != 0; } bool IsVisible() const noexcept { @@ -1284,9 +1232,9 @@ class Mouse::Impl RAWINPUTDEVICE Rid; Rid.usUsagePage = 0x1 /* HID_USAGE_PAGE_GENERIC */; - Rid.usUsage = 0x2 /* HID_USAGE_GENERIC_MOUSE */; - Rid.dwFlags = RIDEV_INPUTSINK; - Rid.hwndTarget = window; + Rid.usUsage = 0x2 /* HID_USAGE_GENERIC_MOUSE */; + Rid.dwFlags = RIDEV_INPUTSINK; + Rid.hwndTarget = window; if (!RegisterRawInputDevices(&Rid, 1, sizeof(RAWINPUTDEVICE))) { throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "RegisterRawInputDevices"); @@ -1295,28 +1243,28 @@ class Mouse::Impl mWindow = window; } - mutable State mState; + mutable State mState; - Mouse* mOwner; + Mouse* mOwner; static Mouse::Impl* s_mouse; private: - HWND mWindow; - Mode mMode; + HWND mWindow; + Mode mMode; - ScopedHandle mScrollWheelValue; - ScopedHandle mRelativeRead; - ScopedHandle mAbsoluteMode; - ScopedHandle mRelativeMode; + ScopedHandle mScrollWheelValue; + ScopedHandle mRelativeRead; + ScopedHandle mAbsoluteMode; + ScopedHandle mRelativeMode; - int mLastX; - int mLastY; - int mRelativeX; - int mRelativeY; + int mLastX; + int mLastY; + int mRelativeX; + int mRelativeY; - bool mInFocus; - bool mAutoReset; + bool mInFocus; + bool mAutoReset; friend void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam); @@ -1324,7 +1272,7 @@ class Mouse::Impl { assert(mWindow != nullptr); - RECT rect = {}; + RECT rect = {}; std::ignore = GetClientRect(mWindow, &rect); POINT ul; @@ -1339,25 +1287,22 @@ class Mouse::Impl std::ignore = MapWindowPoints(mWindow, nullptr, &lr, 1); rect.left = ul.x; - rect.top = ul.y; + rect.top = ul.y; - rect.right = lr.x; + rect.right = lr.x; rect.bottom = lr.y; ClipCursor(&rect); } }; - Mouse::Impl* Mouse::Impl::s_mouse = nullptr; - void Mouse::SetWindow(HWND window) { pImpl->SetWindow(window); } - void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) { auto pImpl = Impl::s_mouse; @@ -1369,8 +1314,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) switch (WaitForSingleObjectEx(pImpl->mScrollWheelValue.get(), 0, FALSE)) { default: - case WAIT_TIMEOUT: - break; + case WAIT_TIMEOUT: break; case WAIT_OBJECT_0: pImpl->mState.scrollWheelValue = 0; @@ -1386,44 +1330,41 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { default: - case WAIT_TIMEOUT: - break; + case WAIT_TIMEOUT: break; - case WAIT_OBJECT_0: - { - pImpl->mMode = MODE_ABSOLUTE; - ClipCursor(nullptr); + case WAIT_OBJECT_0: { + pImpl->mMode = MODE_ABSOLUTE; + ClipCursor(nullptr); - POINT point; - point.x = pImpl->mLastX; - point.y = pImpl->mLastY; + POINT point; + point.x = pImpl->mLastX; + point.y = pImpl->mLastY; - // We show the cursor before moving it to support Remote Desktop - ShowCursor(TRUE); + // We show the cursor before moving it to support Remote Desktop + ShowCursor(TRUE); - if (MapWindowPoints(pImpl->mWindow, nullptr, &point, 1)) - { - SetCursorPos(point.x, point.y); - } - pImpl->mState.x = pImpl->mLastX; - pImpl->mState.y = pImpl->mLastY; + if (MapWindowPoints(pImpl->mWindow, nullptr, &point, 1)) + { + SetCursorPos(point.x, point.y); } - break; + pImpl->mState.x = pImpl->mLastX; + pImpl->mState.y = pImpl->mLastY; + } + break; - case (WAIT_OBJECT_0 + 1): - { - ResetEvent(pImpl->mRelativeRead.get()); + case (WAIT_OBJECT_0 + 1): { + ResetEvent(pImpl->mRelativeRead.get()); - pImpl->mMode = MODE_RELATIVE; - pImpl->mState.x = pImpl->mState.y = 0; - pImpl->mRelativeX = INT32_MAX; - pImpl->mRelativeY = INT32_MAX; + pImpl->mMode = MODE_RELATIVE; + pImpl->mState.x = pImpl->mState.y = 0; + pImpl->mRelativeX = INT32_MAX; + pImpl->mRelativeY = INT32_MAX; - ShowCursor(FALSE); + ShowCursor(FALSE); - pImpl->ClipToWindow(); - } - break; + pImpl->ClipToWindow(); + } + break; case WAIT_FAILED: throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx"); @@ -1465,7 +1406,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) if (pImpl->mInFocus && pImpl->mMode == MODE_RELATIVE) { RAWINPUT raw; - UINT rawSize = sizeof(raw); + UINT rawSize = sizeof(raw); const UINT resultData = GetRawInputData(reinterpret_cast(lParam), RID_INPUT, &raw, &rawSize, sizeof(RAWINPUTHEADER)); if (resultData == UINT(-1)) @@ -1485,7 +1426,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) else if (raw.data.mouse.usFlags & MOUSE_VIRTUAL_DESKTOP) { // This is used to make Remote Desktop sessons work - const int width = GetSystemMetrics(SM_CXVIRTUALSCREEN); + const int width = GetSystemMetrics(SM_CXVIRTUALSCREEN); const int height = GetSystemMetrics(SM_CYVIRTUALSCREEN); const auto x = static_cast((float(raw.data.mouse.lLastX) / 65535.0f) * float(width)); @@ -1510,71 +1451,45 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) } return; - case WM_MOUSEMOVE: - break; + case WM_MOUSEMOVE: break; - case WM_LBUTTONDOWN: - pImpl->mState.leftButton = true; - break; + case WM_LBUTTONDOWN: pImpl->mState.leftButton = true; break; - case WM_LBUTTONUP: - pImpl->mState.leftButton = false; - break; + case WM_LBUTTONUP: pImpl->mState.leftButton = false; break; - case WM_RBUTTONDOWN: - pImpl->mState.rightButton = true; - break; + case WM_RBUTTONDOWN: pImpl->mState.rightButton = true; break; - case WM_RBUTTONUP: - pImpl->mState.rightButton = false; - break; + case WM_RBUTTONUP: pImpl->mState.rightButton = false; break; - case WM_MBUTTONDOWN: - pImpl->mState.middleButton = true; - break; + case WM_MBUTTONDOWN: pImpl->mState.middleButton = true; break; - case WM_MBUTTONUP: - pImpl->mState.middleButton = false; - break; + case WM_MBUTTONUP: pImpl->mState.middleButton = false; break; - case WM_MOUSEWHEEL: - pImpl->mState.scrollWheelValue += GET_WHEEL_DELTA_WPARAM(wParam); - return; + case WM_MOUSEWHEEL: pImpl->mState.scrollWheelValue += GET_WHEEL_DELTA_WPARAM(wParam); return; case WM_XBUTTONDOWN: switch (GET_XBUTTON_WPARAM(wParam)) { - case XBUTTON1: - pImpl->mState.xButton1 = true; - break; + case XBUTTON1: pImpl->mState.xButton1 = true; break; - case XBUTTON2: - pImpl->mState.xButton2 = true; - break; + case XBUTTON2: pImpl->mState.xButton2 = true; break; - default: - break; + default: break; } break; case WM_XBUTTONUP: switch (GET_XBUTTON_WPARAM(wParam)) { - case XBUTTON1: - pImpl->mState.xButton1 = false; - break; + case XBUTTON1: pImpl->mState.xButton1 = false; break; - case XBUTTON2: - pImpl->mState.xButton2 = false; - break; + case XBUTTON2: pImpl->mState.xButton2 = false; break; - default: - break; + default: break; } break; - case WM_MOUSEHOVER: - break; + case WM_MOUSEHOVER: break; default: // Not a mouse message, so exit @@ -1596,7 +1511,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) #pragma endregion #ifdef _MSC_VER -#pragma warning( disable : 4355 ) +#pragma warning(disable : 4355) #endif // Public constructor. @@ -1604,7 +1519,6 @@ Mouse::Mouse() noexcept(false) : pImpl(std::make_unique(this)) {} - // Move constructor. Mouse::Mouse(Mouse&& moveFrom) noexcept : pImpl(std::move(moveFrom.pImpl)) @@ -1612,20 +1526,17 @@ Mouse::Mouse(Mouse&& moveFrom) noexcept pImpl->mOwner = this; } - // Move assignment. -Mouse& Mouse::operator= (Mouse&& moveFrom) noexcept +Mouse& Mouse::operator=(Mouse&& moveFrom) noexcept { - pImpl = std::move(moveFrom.pImpl); + pImpl = std::move(moveFrom.pImpl); pImpl->mOwner = this; return *this; } - // Public destructor. Mouse::~Mouse() = default; - Mouse::State Mouse::GetState() const { State state; @@ -1633,25 +1544,21 @@ Mouse::State Mouse::GetState() const return state; } - void Mouse::ResetScrollWheelValue() noexcept { pImpl->ResetScrollWheelValue(); } - void Mouse::SetMode(Mode mode) { pImpl->SetMode(mode); } - void Mouse::EndOfInputFrame() noexcept { pImpl->EndOfInputFrame(); } - bool Mouse::IsConnected() const { return pImpl->IsConnected(); @@ -1675,13 +1582,11 @@ Mouse& Mouse::Get() return *Impl::s_mouse->mOwner; } - - //====================================================================================== // ButtonStateTracker //====================================================================================== -#define UPDATE_BUTTON_STATE(field) field = static_cast( ( !!state.field ) | ( ( !!state.field ^ !!lastState.field ) << 1 ) ) +#define UPDATE_BUTTON_STATE(field) field = static_cast((!!state.field) | ((!!state.field ^ !!lastState.field) << 1)) void Mouse::ButtonStateTracker::Update(const Mouse::State& state) noexcept { @@ -1702,7 +1607,6 @@ void Mouse::ButtonStateTracker::Update(const Mouse::State& state) noexcept #undef UPDATE_BUTTON_STATE - void Mouse::ButtonStateTracker::Reset() noexcept { memset(this, 0, sizeof(ButtonStateTracker)); diff --git a/Src/NPREffect.cpp b/Src/NPREffect.cpp index 2917d51e..1ae8ffcd 100644 --- a/Src/NPREffect.cpp +++ b/Src/NPREffect.cpp @@ -16,7 +16,7 @@ namespace DirectX { constexpr int ConstantBufferBones = 0x100000; } -} +} // namespace DirectX using namespace DirectX; @@ -47,29 +47,26 @@ namespace static_assert((sizeof(BoneConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct NPREffectTraits { using ConstantBufferType = NPREffectConstants; - static constexpr int VertexShaderCount = 36; - static constexpr int PixelShaderCount = 9; + static constexpr int VertexShaderCount = 36; + static constexpr int PixelShaderCount = 9; static constexpr int ShaderPermutationCount = 54; - static constexpr int RootSignatureCount = 5; + static constexpr int RootSignatureCount = 5; }; - // Default values - constexpr XMVECTORF32 s_defaultLightDir = { { { 0.f, -1.f, 0.f, 4.f } } }; - constexpr XMVECTORF32 s_defaultDiffuse = { { { 1.f, 1.f, 1.f, 1.f } } }; - constexpr XMVECTORF32 s_defaultSpecular = { { { 1.f, 1.f, 1.f, 0.95f } } }; - constexpr XMVECTORF32 s_defaultRim = { { { 0.f, 0.f, 0.f, 4.f } } }; + constexpr XMVECTORF32 s_defaultLightDir = { { { 0.f, -1.f, 0.f, 4.f } } }; + constexpr XMVECTORF32 s_defaultDiffuse = { { { 1.f, 1.f, 1.f, 1.f } } }; + constexpr XMVECTORF32 s_defaultSpecular = { { { 1.f, 1.f, 1.f, 0.95f } } }; + constexpr XMVECTORF32 s_defaultRim = { { { 0.f, 0.f, 0.f, 4.f } } }; constexpr XMVECTORF32 s_defaultExtraSettings = { { { 0.004f, 0.75f, 0.2f, 0.6f } } }; - constexpr XMVECTORF32 s_defaultCool = { { { 0.f, 0.f, 0.55f, 0.25f } } }; - constexpr XMVECTORF32 s_defaultWarm = { { { 0.3f, 0.3f, 0.f, 0.25f } } }; -} - + constexpr XMVECTORF32 s_defaultCool = { { { 0.f, 0.f, 0.55f, 0.25f } } }; + constexpr XMVECTORF32 s_defaultWarm = { { { 0.3f, 0.3f, 0.f, 0.25f } } }; +} // namespace // Internal NPREffect implementation class. class NPREffect::Impl : public EffectBase @@ -77,18 +74,17 @@ class NPREffect::Impl : public EffectBase public: Impl(_In_ ID3D12Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; - void Initialize( - _In_ ID3D12Device* device, - uint32_t effectFlags, + void Initialize(_In_ ID3D12Device* device, + uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - NPREffect::Mode nprMode, - bool enableSkinning); + NPREffect::Mode nprMode, + bool enableSkinning); enum RootParameterIndex { @@ -109,7 +105,7 @@ class NPREffect::Impl : public EffectBase SkinRootParameterCount }; - int weightsPerVertex; + int weightsPerVertex; bool matCapEnabled; bool textureEnabled; @@ -128,7 +124,6 @@ class NPREffect::Impl : public EffectBase GraphicsResource mBones; }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -406,217 +401,209 @@ namespace #include "NPREffect_PSMatCapShadingSkinTx.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { NPREffect_VSNPREffect, sizeof(NPREffect_VSNPREffect) }, - { NPREffect_VSNPREffectVc, sizeof(NPREffect_VSNPREffectVc) }, - { NPREffect_VSNPREffectBn, sizeof(NPREffect_VSNPREffectBn) }, - { NPREffect_VSNPREffectVcBn, sizeof(NPREffect_VSNPREffectVcBn) }, - { NPREffect_VSNPREffectInst, sizeof(NPREffect_VSNPREffectInst) }, - { NPREffect_VSNPREffectVcInst, sizeof(NPREffect_VSNPREffectVcInst) }, - { NPREffect_VSNPREffectBnInst, sizeof(NPREffect_VSNPREffectBnInst) }, - { NPREffect_VSNPREffectVcBnInst, sizeof(NPREffect_VSNPREffectVcBnInst) }, - { NPREffect_VSNPREffectTx, sizeof(NPREffect_VSNPREffectTx) }, - { NPREffect_VSNPREffectVcTx, sizeof(NPREffect_VSNPREffectVcTx) }, - { NPREffect_VSNPREffectBnTx, sizeof(NPREffect_VSNPREffectBnTx) }, - { NPREffect_VSNPREffectVcBnTx, sizeof(NPREffect_VSNPREffectVcBnTx) }, - { NPREffect_VSNPREffectInstTx, sizeof(NPREffect_VSNPREffectInstTx) }, - { NPREffect_VSNPREffectVcInstTx, sizeof(NPREffect_VSNPREffectVcInstTx) }, - { NPREffect_VSNPREffectBnInstTx, sizeof(NPREffect_VSNPREffectBnInstTx) }, - { NPREffect_VSNPREffectVcBnInstTx, sizeof(NPREffect_VSNPREffectVcBnInstTx) }, - { NPREffect_VSNPREffectMC, sizeof(NPREffect_VSNPREffectMC) }, // Different rootsig - { NPREffect_VSNPREffectVcMC, sizeof(NPREffect_VSNPREffectVcMC) }, - { NPREffect_VSNPREffectBnMC, sizeof(NPREffect_VSNPREffectBnMC) }, - { NPREffect_VSNPREffectVcBnMC, sizeof(NPREffect_VSNPREffectVcBnMC) }, - { NPREffect_VSNPREffectInstMC, sizeof(NPREffect_VSNPREffectInstMC) }, - { NPREffect_VSNPREffectVcInstMC, sizeof(NPREffect_VSNPREffectVcInstMC) }, - { NPREffect_VSNPREffectBnInstMC, sizeof(NPREffect_VSNPREffectBnInstMC) }, - { NPREffect_VSNPREffectVcBnInstMC, sizeof(NPREffect_VSNPREffectVcBnInstMC) }, - { NPREffect_VSNPREffectTxMC, sizeof(NPREffect_VSNPREffectTxMC) }, - { NPREffect_VSNPREffectVcTxMC, sizeof(NPREffect_VSNPREffectVcTxMC) }, - { NPREffect_VSNPREffectBnTxMC, sizeof(NPREffect_VSNPREffectBnTxMC) }, - { NPREffect_VSNPREffectVcBnTxMC, sizeof(NPREffect_VSNPREffectVcBnTxMC) }, - { NPREffect_VSNPREffectInstTxMC, sizeof(NPREffect_VSNPREffectInstTxMC) }, - { NPREffect_VSNPREffectVcInstTxMC, sizeof(NPREffect_VSNPREffectVcInstTxMC) }, - { NPREffect_VSNPREffectBnInstTxMC, sizeof(NPREffect_VSNPREffectBnInstTxMC) }, - { NPREffect_VSNPREffectVcBnInstTxMC, sizeof(NPREffect_VSNPREffectVcBnInstTxMC) }, - { NPREffect_VSSkinnedNPREffectTx, sizeof(NPREffect_VSSkinnedNPREffectTx) }, - { NPREffect_VSSkinnedNPREffectTxBn, sizeof(NPREffect_VSSkinnedNPREffectTxBn) }, - { NPREffect_VSSkinnedNPREffectTxMC, sizeof(NPREffect_VSSkinnedNPREffectTxMC) }, - { NPREffect_VSSkinnedNPREffectTxBnMC, sizeof(NPREffect_VSSkinnedNPREffectTxBnMC) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { NPREffect_VSNPREffect, sizeof(NPREffect_VSNPREffect) }, + { NPREffect_VSNPREffectVc, sizeof(NPREffect_VSNPREffectVc) }, + { NPREffect_VSNPREffectBn, sizeof(NPREffect_VSNPREffectBn) }, + { NPREffect_VSNPREffectVcBn, sizeof(NPREffect_VSNPREffectVcBn) }, + { NPREffect_VSNPREffectInst, sizeof(NPREffect_VSNPREffectInst) }, + { NPREffect_VSNPREffectVcInst, sizeof(NPREffect_VSNPREffectVcInst) }, + { NPREffect_VSNPREffectBnInst, sizeof(NPREffect_VSNPREffectBnInst) }, + { NPREffect_VSNPREffectVcBnInst, sizeof(NPREffect_VSNPREffectVcBnInst) }, + { NPREffect_VSNPREffectTx, sizeof(NPREffect_VSNPREffectTx) }, + { NPREffect_VSNPREffectVcTx, sizeof(NPREffect_VSNPREffectVcTx) }, + { NPREffect_VSNPREffectBnTx, sizeof(NPREffect_VSNPREffectBnTx) }, + { NPREffect_VSNPREffectVcBnTx, sizeof(NPREffect_VSNPREffectVcBnTx) }, + { NPREffect_VSNPREffectInstTx, sizeof(NPREffect_VSNPREffectInstTx) }, + { NPREffect_VSNPREffectVcInstTx, sizeof(NPREffect_VSNPREffectVcInstTx) }, + { NPREffect_VSNPREffectBnInstTx, sizeof(NPREffect_VSNPREffectBnInstTx) }, + { NPREffect_VSNPREffectVcBnInstTx, sizeof(NPREffect_VSNPREffectVcBnInstTx) }, + { NPREffect_VSNPREffectMC, sizeof(NPREffect_VSNPREffectMC) }, // Different rootsig + { NPREffect_VSNPREffectVcMC, sizeof(NPREffect_VSNPREffectVcMC) }, + { NPREffect_VSNPREffectBnMC, sizeof(NPREffect_VSNPREffectBnMC) }, + { NPREffect_VSNPREffectVcBnMC, sizeof(NPREffect_VSNPREffectVcBnMC) }, + { NPREffect_VSNPREffectInstMC, sizeof(NPREffect_VSNPREffectInstMC) }, + { NPREffect_VSNPREffectVcInstMC, sizeof(NPREffect_VSNPREffectVcInstMC) }, + { NPREffect_VSNPREffectBnInstMC, sizeof(NPREffect_VSNPREffectBnInstMC) }, + { NPREffect_VSNPREffectVcBnInstMC, sizeof(NPREffect_VSNPREffectVcBnInstMC) }, + { NPREffect_VSNPREffectTxMC, sizeof(NPREffect_VSNPREffectTxMC) }, + { NPREffect_VSNPREffectVcTxMC, sizeof(NPREffect_VSNPREffectVcTxMC) }, + { NPREffect_VSNPREffectBnTxMC, sizeof(NPREffect_VSNPREffectBnTxMC) }, + { NPREffect_VSNPREffectVcBnTxMC, sizeof(NPREffect_VSNPREffectVcBnTxMC) }, + { NPREffect_VSNPREffectInstTxMC, sizeof(NPREffect_VSNPREffectInstTxMC) }, + { NPREffect_VSNPREffectVcInstTxMC, sizeof(NPREffect_VSNPREffectVcInstTxMC) }, + { NPREffect_VSNPREffectBnInstTxMC, sizeof(NPREffect_VSNPREffectBnInstTxMC) }, + { NPREffect_VSNPREffectVcBnInstTxMC, sizeof(NPREffect_VSNPREffectVcBnInstTxMC) }, + { NPREffect_VSSkinnedNPREffectTx, sizeof(NPREffect_VSSkinnedNPREffectTx) }, + { NPREffect_VSSkinnedNPREffectTxBn, sizeof(NPREffect_VSSkinnedNPREffectTxBn) }, + { NPREffect_VSSkinnedNPREffectTxMC, sizeof(NPREffect_VSSkinnedNPREffectTxMC) }, + { NPREffect_VSSkinnedNPREffectTxBnMC, sizeof(NPREffect_VSSkinnedNPREffectTxBnMC) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // cel shading - 0, // gooch shading - 16, // matcap shading - - 1, // vertex color + cel shading - 1, // vertex color + gooch shading - 17, // vertex color + matcap shading - - 2, // cel shading (biased vertex normal) - 2, // gooch shading (biased vertex normal) - 18, // matcap shading (biased vertex normal) - - 3, // vertex color (biased vertex normal) + cel shading - 3, // vertex color (biased vertex normal) + gooch shading - 19, // vertex color (biased vertex normal) + matcap shading - - 4, // instancing + cel shading - 4, // instancing + gooch shading - 20, // instancing + matcap shading - - 5, // instancing + vertex color + cel shading - 5, // instancing + vertex color + gooch shading - 21, // instancing + vertex color + matcap shading - - 6, // instancing (biased vertex normal) + cel shading - 6, // instancing (biased vertex normal) + gooch shading - 22, // instancing (biased vertex normal) + matcap shading - - 7, // instancing + vertex color (biased vertex normal) + cel shading - 7, // instancing + vertex color (biased vertex normal) + gooch shading - 23, // instancing + vertex color (biased vertex normal) + matcap shading - - 8, // cel shading + texture - 8, // gooch shading + texture - 24, // matcap shading + texture - - 9, // vertex color + cel shading + texture - 9, // vertex color + gooch shading + texture - 25, // vertex color + matcap shading + texture - - 10, // cel shading (biased vertex normal) + texture - 10, // gooch shading (biased vertex normal) + texture - 26, // matcap shading (biased vertex normal) + texture - - 11, // vertex color (biased vertex normal) + cel shading + texture - 11, // vertex color (biased vertex normal) + gooch shading + texture - 27, // vertex color (biased vertex normal) + matcap shading + texture - - 12, // instancing + cel shading + texture - 12, // instancing + gooch shading + texture - 28, // instancing + matcap shading + texture - - 13, // instancing + vertex color + cel shading + texture - 13, // instancing + vertex color + gooch shading + texture - 29, // instancing + vertex color + matcap shading + texture - - 14, // instancing (biased vertex normal) + cel shading + texture - 14, // instancing (biased vertex normal) + gooch shading + texture - 30, // instancing (biased vertex normal) + matcap shading + texture - - 15, // instancing + vertex color (biased vertex normal) + cel shading + texture - 15, // instancing + vertex color (biased vertex normal) + gooch shading + texture - 31, // instancing + vertex color (biased vertex normal) + matcap shading + texture - - 32, // skinning + cel shading - 32, // skinning + gooch shading - 34, // skinning + matcap shading - - 33, // skinning (biased vertex normal) + cel shading - 33, // skinning (biased vertex normal) + gooch shading - 35, // skinning (biased vertex normal) + matcap shading +const int EffectBase::VertexShaderIndices[] = { + 0, // cel shading + 0, // gooch shading + 16, // matcap shading + + 1, // vertex color + cel shading + 1, // vertex color + gooch shading + 17, // vertex color + matcap shading + + 2, // cel shading (biased vertex normal) + 2, // gooch shading (biased vertex normal) + 18, // matcap shading (biased vertex normal) + + 3, // vertex color (biased vertex normal) + cel shading + 3, // vertex color (biased vertex normal) + gooch shading + 19, // vertex color (biased vertex normal) + matcap shading + + 4, // instancing + cel shading + 4, // instancing + gooch shading + 20, // instancing + matcap shading + + 5, // instancing + vertex color + cel shading + 5, // instancing + vertex color + gooch shading + 21, // instancing + vertex color + matcap shading + + 6, // instancing (biased vertex normal) + cel shading + 6, // instancing (biased vertex normal) + gooch shading + 22, // instancing (biased vertex normal) + matcap shading + + 7, // instancing + vertex color (biased vertex normal) + cel shading + 7, // instancing + vertex color (biased vertex normal) + gooch shading + 23, // instancing + vertex color (biased vertex normal) + matcap shading + + 8, // cel shading + texture + 8, // gooch shading + texture + 24, // matcap shading + texture + + 9, // vertex color + cel shading + texture + 9, // vertex color + gooch shading + texture + 25, // vertex color + matcap shading + texture + + 10, // cel shading (biased vertex normal) + texture + 10, // gooch shading (biased vertex normal) + texture + 26, // matcap shading (biased vertex normal) + texture + + 11, // vertex color (biased vertex normal) + cel shading + texture + 11, // vertex color (biased vertex normal) + gooch shading + texture + 27, // vertex color (biased vertex normal) + matcap shading + texture + + 12, // instancing + cel shading + texture + 12, // instancing + gooch shading + texture + 28, // instancing + matcap shading + texture + + 13, // instancing + vertex color + cel shading + texture + 13, // instancing + vertex color + gooch shading + texture + 29, // instancing + vertex color + matcap shading + texture + + 14, // instancing (biased vertex normal) + cel shading + texture + 14, // instancing (biased vertex normal) + gooch shading + texture + 30, // instancing (biased vertex normal) + matcap shading + texture + + 15, // instancing + vertex color (biased vertex normal) + cel shading + texture + 15, // instancing + vertex color (biased vertex normal) + gooch shading + texture + 31, // instancing + vertex color (biased vertex normal) + matcap shading + texture + + 32, // skinning + cel shading + 32, // skinning + gooch shading + 34, // skinning + matcap shading + + 33, // skinning (biased vertex normal) + cel shading + 33, // skinning (biased vertex normal) + gooch shading + 35, // skinning (biased vertex normal) + matcap shading }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { NPREffect_PSCelShading, sizeof(NPREffect_PSCelShading) }, - { NPREffect_PSGoochShading, sizeof(NPREffect_PSGoochShading) }, - { NPREffect_PSMatCapShading, sizeof(NPREffect_PSMatCapShading) }, - { NPREffect_PSCelShadingTx, sizeof(NPREffect_PSCelShadingTx) }, - { NPREffect_PSGoochShadingTx, sizeof(NPREffect_PSGoochShadingTx) }, - { NPREffect_PSMatCapShadingTx, sizeof(NPREffect_PSMatCapShadingTx) }, - { NPREffect_PSCelShadingSkinTx, sizeof(NPREffect_PSCelShadingSkinTx) }, // Different rootsig - { NPREffect_PSGoochShadingSkinTx, sizeof(NPREffect_PSGoochShadingSkinTx) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { NPREffect_PSCelShading, sizeof(NPREffect_PSCelShading) }, + { NPREffect_PSGoochShading, sizeof(NPREffect_PSGoochShading) }, + { NPREffect_PSMatCapShading, sizeof(NPREffect_PSMatCapShading) }, + { NPREffect_PSCelShadingTx, sizeof(NPREffect_PSCelShadingTx) }, + { NPREffect_PSGoochShadingTx, sizeof(NPREffect_PSGoochShadingTx) }, + { NPREffect_PSMatCapShadingTx, sizeof(NPREffect_PSMatCapShadingTx) }, + { NPREffect_PSCelShadingSkinTx, sizeof(NPREffect_PSCelShadingSkinTx) }, // Different rootsig + { NPREffect_PSGoochShadingSkinTx, sizeof(NPREffect_PSGoochShadingSkinTx) }, { NPREffect_PSMatCapShadingSkinTx, sizeof(NPREffect_PSMatCapShadingSkinTx) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // cel shading - 1, // gooch shading - 2, // matcap shading - - 0, // vertex color + cel shading - 1, // vertex color + gooch shading - 2, // vertex color + matcap shading - - 0, // cel shading (biased vertex normal) - 1, // gooch shading (biased vertex normal) - 2, // matcap shading (biased vertex normal) - - 0, // vertex color (biased vertex normal) + cel shading - 1, // vertex color (biased vertex normal) + gooch shading - 2, // vertex color (biased vertex normal) + matcap shading - - 0, // instancing + cel shading - 1, // instancing + gooch shading - 2, // instancing + matcap shading - - 0, // instancing + vertex color + cel shading - 1, // instancing + vertex color + gooch shading - 2, // instancing + vertex color + matcap shading - - 0, // instancing (biased vertex normal) + cel shading - 1, // instancing (biased vertex normal) + gooch shading - 2, // instancing (biased vertex normal) + matcap shading - - 0, // instancing + vertex color (biased vertex normal) + cel shading - 1, // instancing + vertex color (biased vertex normal) + gooch shading - 2, // instancing + vertex color (biased vertex normal) + matcap shading - - 3, // cel shading + texture - 4, // gooch shading + texture - 5, // matcap shading + texture - - 3, // vertex color + cel shading + texture - 4, // vertex color + gooch shading + texture - 5, // vertex color + matcap shading + texture - - 3, // cel shading (biased vertex normal) + texture - 4, // gooch shading (biased vertex normal) + texture - 5, // matcap shading (biased vertex normal) + texture - - 3, // vertex color (biased vertex normal) + cel shading + texture - 4, // vertex color (biased vertex normal) + gooch shading + texture - 5, // vertex color (biased vertex normal) + matcap shading + texture - - 3, // instancing + cel shading + texture - 4, // instancing + gooch shading + texture - 5, // instancing + matcap shading + texture - - 3, // instancing + vertex color + cel shading + texture - 4, // instancing + vertex color + gooch shading + texture - 5, // instancing + vertex color + matcap shading + texture - - 3, // instancing (biased vertex normal) + cel shading + texture - 4, // instancing (biased vertex normal) + gooch shading + texture - 5, // instancing (biased vertex normal) + matcap shading + texture - - 3, // instancing + vertex color (biased vertex normal) + cel shading + texture - 4, // instancing + vertex color (biased vertex normal) + gooch shading + texture - 5, // instancing + vertex color (biased vertex normal) + matcap shading + texture - - 6, // skinning + cel shading - 7, // skinning + gooch shading - 8, // skinning + matcap shading - - 6, // skinning (biased vertex normal) + cel shading - 7, // skinning (biased vertex normal) + gooch shading - 8, // skinning (biased vertex normal) + matcap shading +const int EffectBase::PixelShaderIndices[] = { + 0, // cel shading + 1, // gooch shading + 2, // matcap shading + + 0, // vertex color + cel shading + 1, // vertex color + gooch shading + 2, // vertex color + matcap shading + + 0, // cel shading (biased vertex normal) + 1, // gooch shading (biased vertex normal) + 2, // matcap shading (biased vertex normal) + + 0, // vertex color (biased vertex normal) + cel shading + 1, // vertex color (biased vertex normal) + gooch shading + 2, // vertex color (biased vertex normal) + matcap shading + + 0, // instancing + cel shading + 1, // instancing + gooch shading + 2, // instancing + matcap shading + + 0, // instancing + vertex color + cel shading + 1, // instancing + vertex color + gooch shading + 2, // instancing + vertex color + matcap shading + + 0, // instancing (biased vertex normal) + cel shading + 1, // instancing (biased vertex normal) + gooch shading + 2, // instancing (biased vertex normal) + matcap shading + + 0, // instancing + vertex color (biased vertex normal) + cel shading + 1, // instancing + vertex color (biased vertex normal) + gooch shading + 2, // instancing + vertex color (biased vertex normal) + matcap shading + + 3, // cel shading + texture + 4, // gooch shading + texture + 5, // matcap shading + texture + + 3, // vertex color + cel shading + texture + 4, // vertex color + gooch shading + texture + 5, // vertex color + matcap shading + texture + + 3, // cel shading (biased vertex normal) + texture + 4, // gooch shading (biased vertex normal) + texture + 5, // matcap shading (biased vertex normal) + texture + + 3, // vertex color (biased vertex normal) + cel shading + texture + 4, // vertex color (biased vertex normal) + gooch shading + texture + 5, // vertex color (biased vertex normal) + matcap shading + texture + + 3, // instancing + cel shading + texture + 4, // instancing + gooch shading + texture + 5, // instancing + matcap shading + texture + + 3, // instancing + vertex color + cel shading + texture + 4, // instancing + vertex color + gooch shading + texture + 5, // instancing + vertex color + matcap shading + texture + + 3, // instancing (biased vertex normal) + cel shading + texture + 4, // instancing (biased vertex normal) + gooch shading + texture + 5, // instancing (biased vertex normal) + matcap shading + texture + + 3, // instancing + vertex color (biased vertex normal) + cel shading + texture + 4, // instancing + vertex color (biased vertex normal) + gooch shading + texture + 5, // instancing + vertex color (biased vertex normal) + matcap shading + texture + + 6, // skinning + cel shading + 7, // skinning + gooch shading + 8, // skinning + matcap shading + + 6, // skinning (biased vertex normal) + cel shading + 7, // skinning (biased vertex normal) + gooch shading + 8, // skinning (biased vertex normal) + matcap shading }; #pragma endregion @@ -624,56 +611,53 @@ const int EffectBase::PixelShaderIndices[] = template<> SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - // Constructor. -NPREffect::Impl::Impl( - _In_ ID3D12Device* device) +NPREffect::Impl::Impl(_In_ ID3D12Device* device) : EffectBase(device), - weightsPerVertex(0), - matCapEnabled(false), - textureEnabled(false), - texture{}, - sampler{}, - matcap{}, - boneConstants{} + weightsPerVertex(0), + matCapEnabled(false), + textureEnabled(false), + texture{}, + sampler{}, + matcap{}, + boneConstants{} { - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == NPREffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == NPREffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == NPREffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == NPREffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == NPREffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == NPREffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == NPREffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == NPREffectTraits::ShaderPermutationCount, + "array/max mismatch"); } -void NPREffect::Impl::Initialize( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - NPREffect::Mode nprMode, - bool enableSkinning) +void NPREffect::Impl::Initialize(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + NPREffect::Mode nprMode, + bool enableSkinning) { switch (nprMode) { case Mode_Cel: - case Mode_Gooch: - break; + case Mode_Gooch: break; - case Mode_MatCap: - matCapEnabled = true; - break; + case Mode_MatCap: matCapEnabled = true; break; - default: - throw std::invalid_argument("Invalid nprMode"); + default: throw std::invalid_argument("Invalid nprMode"); } textureEnabled = (effectFlags & EffectFlags::Texture) != 0; - constants.lightDirectionAndCelBands = s_defaultLightDir; - constants.diffuseColorAndAlpha = s_defaultDiffuse; + constants.lightDirectionAndCelBands = s_defaultLightDir; + constants.diffuseColorAndAlpha = s_defaultDiffuse; constants.specularColorAndSpecularThreshold = s_defaultSpecular; - constants.rimColorAndPower = s_defaultRim; - constants.extraSettings = s_defaultExtraSettings; - constants.goochCoolColorAndAlpha = s_defaultCool; - constants.goochWarmColorAndBeta = s_defaultWarm; - constants.eyePosition = g_XMZero; + constants.rimColorAndPower = s_defaultRim; + constants.extraSettings = s_defaultExtraSettings; + constants.goochCoolColorAndAlpha = s_defaultCool; + constants.goochWarmColorAndBeta = s_defaultWarm; + constants.eyePosition = g_XMZero; if (enableSkinning) { @@ -689,7 +673,7 @@ void NPREffect::Impl::Initialize( } weightsPerVertex = 4; - textureEnabled = true; + textureEnabled = true; for (size_t j = 0; j < SkinnedNPREffect::MaxBones; ++j) { @@ -701,15 +685,12 @@ void NPREffect::Impl::Initialize( // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; if (enableSkinning) @@ -723,7 +704,9 @@ void NPREffect::Impl::Initialize( const CD3DX12_DESCRIPTOR_RANGE textureSampler(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0); rootParameters[SkinRootParameterIndex::SkinTextureSRV].InitAsDescriptorTable(1, &textureSRV, D3D12_SHADER_VISIBILITY_PIXEL); - rootParameters[SkinRootParameterIndex::SkinTextureSampler].InitAsDescriptorTable(1, &textureSampler, D3D12_SHADER_VISIBILITY_PIXEL); + rootParameters[SkinRootParameterIndex::SkinTextureSampler].InitAsDescriptorTable(1, + &textureSampler, + D3D12_SHADER_VISIBILITY_PIXEL); rootParameters[SkinRootParameterIndex::SkinConstantBufferBones].InitAsConstantBufferView(1, 0, D3D12_SHADER_VISIBILITY_VERTEX); @@ -734,7 +717,9 @@ void NPREffect::Impl::Initialize( { // Include second texture const CD3DX12_DESCRIPTOR_RANGE texture2Range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1); - rootParameters[SkinRootParameterIndex::SkinTexture2SRV].InitAsDescriptorTable(1, &texture2Range, D3D12_SHADER_VISIBILITY_PIXEL); + rootParameters[SkinRootParameterIndex::SkinTexture2SRV].InitAsDescriptorTable(1, + &texture2Range, + D3D12_SHADER_VISIBILITY_PIXEL); // use all parameters rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); @@ -819,8 +804,7 @@ void NPREffect::Impl::Initialize( assert(pi >= 0 && pi < NPREffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < NPREffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -836,7 +820,6 @@ void NPREffect::Impl::Initialize( } } - int NPREffect::Impl::GetPipelineStatePermutation(NPREffect::Mode nprMode, uint32_t effectFlags) const noexcept { int permutation = static_cast(nprMode); @@ -882,19 +865,13 @@ int NPREffect::Impl::GetPipelineStatePermutation(NPREffect::Mode nprMode, uint32 return permutation; } - // Sets our state onto the D3D device. void NPREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { assert(weightsPerVertex == 0); // Compute derived parameter values. - matrices.SetConstants( - dirtyFlags, - constants.world, - constants.worldInverseTranspose, - constants.worldViewProj, - constants.eyePosition); + matrices.SetConstants(dirtyFlags, constants.world, constants.worldInverseTranspose, constants.worldViewProj, constants.eyePosition); UpdateConstants(); @@ -906,8 +883,7 @@ void NPREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { if (!texture.ptr || !sampler.ptr) { - DebugTrace("ERROR: Missing texture or sampler for NPREffect (texture %llu, sampler %llu)\n", - texture.ptr, sampler.ptr); + DebugTrace("ERROR: Missing texture or sampler for NPREffect (texture %llu, sampler %llu)\n", texture.ptr, sampler.ptr); throw std::runtime_error("NPREffect"); } @@ -933,8 +909,7 @@ void NPREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { if (!matcap.ptr || !sampler.ptr) { - DebugTrace("ERROR: Missing matcap texture or sampler for NPREffect (texture %llu, sampler %llu)\n", - matcap.ptr, sampler.ptr); + DebugTrace("ERROR: Missing matcap texture or sampler for NPREffect (texture %llu, sampler %llu)\n", matcap.ptr, sampler.ptr); throw std::runtime_error("NPREffect"); } @@ -951,19 +926,13 @@ void NPREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - void NPREffect::Impl::ApplySkinning(_In_ ID3D12GraphicsCommandList* commandList) { assert(weightsPerVertex > 0); assert(textureEnabled); // Compute derived parameter values. - matrices.SetConstants( - dirtyFlags, - constants.world, - constants.worldInverseTranspose, - constants.worldViewProj, - constants.eyePosition); + matrices.SetConstants(dirtyFlags, constants.world, constants.worldInverseTranspose, constants.worldViewProj, constants.eyePosition); UpdateConstants(); @@ -979,8 +948,7 @@ void NPREffect::Impl::ApplySkinning(_In_ ID3D12GraphicsCommandList* commandList) // Set the texture(s) if (!texture.ptr || !sampler.ptr) { - DebugTrace("ERROR: Missing texture or sampler for SkinnedNPREffect (texture %llu, sampler %llu)\n", - texture.ptr, sampler.ptr); + DebugTrace("ERROR: Missing texture or sampler for SkinnedNPREffect (texture %llu, sampler %llu)\n", texture.ptr, sampler.ptr); throw std::runtime_error("SkinnedNPREffect"); } @@ -1012,28 +980,24 @@ void NPREffect::Impl::ApplySkinning(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - //-------------------------------------------------------------------------------------- // NPREffect //-------------------------------------------------------------------------------------- // Public constructor. -NPREffect::NPREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, +NPREffect::NPREffect(_In_ ID3D12Device* device, + uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - Mode nprMode, - bool skinningEnabled) + Mode nprMode, + bool skinningEnabled) : pImpl(std::make_unique(device)) { pImpl->Initialize(device, effectFlags, pipelineDescription, nprMode, skinningEnabled); } - -NPREffect::NPREffect(NPREffect&&) noexcept = default; -NPREffect& NPREffect::operator= (NPREffect&&) noexcept = default; -NPREffect::~NPREffect() = default; - +NPREffect::NPREffect(NPREffect&&) noexcept = default; +NPREffect& NPREffect::operator=(NPREffect&&) noexcept = default; +NPREffect::~NPREffect() = default; // IEffect methods. void NPREffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -1041,7 +1005,6 @@ void NPREffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings. void NPREffect::SetWorld(FXMMATRIX value) { @@ -1050,7 +1013,6 @@ void NPREffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose; } - void NPREffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -1058,7 +1020,6 @@ void NPREffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition; } - void NPREffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -1066,30 +1027,26 @@ void NPREffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void NPREffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition; } - // Light settings. void NPREffect::SetAmbientLightColor(FXMVECTOR) { // Unsupported interface. } - void NPREffect::SetLightEnabled(int, bool) { // Unsupported interface. } - void NPREffect::SetLightDirection(int whichLight, FXMVECTOR value) { if (whichLight != 0) @@ -1104,28 +1061,25 @@ void NPREffect::SetLightDirection(int whichLight, FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetLightDiffuseColor(int, FXMVECTOR) { // Unsupported interface. } - void NPREffect::SetLightSpecularColor(int, FXMVECTOR) { // Unsupported interface. } - void NPREffect::EnableDefaultLighting() { // Set xyz to new value, but preserve existing w (cel bands). - pImpl->constants.lightDirectionAndCelBands = XMVectorSelect(pImpl->constants.lightDirectionAndCelBands, s_defaultLightDir, g_XMSelect1110); + pImpl->constants.lightDirectionAndCelBands + = XMVectorSelect(pImpl->constants.lightDirectionAndCelBands, s_defaultLightDir, g_XMSelect1110); pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Material settings. void NPREffect::SetDiffuseColor(FXMVECTOR value) { @@ -1135,16 +1089,15 @@ void NPREffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetSpecularColor(FXMVECTOR value) { // Set xyz, preserve w (specular threshold). - pImpl->constants.specularColorAndSpecularThreshold = XMVectorSelect(pImpl->constants.specularColorAndSpecularThreshold, value, g_XMSelect1110); + pImpl->constants.specularColorAndSpecularThreshold + = XMVectorSelect(pImpl->constants.specularColorAndSpecularThreshold, value, g_XMSelect1110); pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetSpecularThreshold(float threshold, float smoothing) { if (threshold < 0.f || threshold > 1.f) @@ -1166,7 +1119,6 @@ void NPREffect::SetSpecularThreshold(float threshold, float smoothing) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::DisableSpecular() { // Set specular color to black, threshold to 1 @@ -1175,7 +1127,6 @@ void NPREffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetAlpha(float value) { // Set w of diffuseColorAndAlpha. @@ -1184,7 +1135,6 @@ void NPREffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->constants.diffuseColorAndAlpha = value; @@ -1192,7 +1142,6 @@ void NPREffect::SetColorAndAlpha(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture setting. void NPREffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { @@ -1200,7 +1149,6 @@ void NPREffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_ pImpl->sampler = samplerDescriptor; } - // Cel shading setting. void NPREffect::SetCelShaderBands(int bands) { @@ -1215,7 +1163,6 @@ void NPREffect::SetCelShaderBands(int bands) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Gooch shading settings. void NPREffect::SetGoochCoolColor(FXMVECTOR value, float alpha) { @@ -1224,7 +1171,6 @@ void NPREffect::SetGoochCoolColor(FXMVECTOR value, float alpha) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetGoochWarmColor(FXMVECTOR value, float beta) { pImpl->constants.goochWarmColorAndBeta = XMVectorSetW(value, beta); @@ -1232,21 +1178,18 @@ void NPREffect::SetGoochWarmColor(FXMVECTOR value, float beta) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // MatCap shading setting. void NPREffect::SetMatCap(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { pImpl->matcap = srvDescriptor; } - void NPREffect::SetMatCap(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { - pImpl->matcap = srvDescriptor; + pImpl->matcap = srvDescriptor; pImpl->sampler = samplerDescriptor; } - // Rim lighting settings. void NPREffect::SetRimLightingColor(FXMVECTOR value) { @@ -1256,7 +1199,6 @@ void NPREffect::SetRimLightingColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetRimLightingPower(float power) { // Set w of rimColorAndPower. @@ -1265,7 +1207,6 @@ void NPREffect::SetRimLightingPower(float power) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetRimLightingIntensity(float strength) { if (strength < 0.f || strength > 1.f) @@ -1279,7 +1220,6 @@ void NPREffect::SetRimLightingIntensity(float strength) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetRimLightingRange(float start, float end) { if (start < 0.f || end > 1.f || start > end) @@ -1288,13 +1228,12 @@ void NPREffect::SetRimLightingRange(float start, float end) } // Set zw of extraSettings. - XMVECTORF32 range = { { { 0.f, 0.f, start, end } } }; + XMVECTORF32 range = { { { 0.f, 0.f, start, end } } }; pImpl->constants.extraSettings = XMVectorSelect(range, pImpl->constants.extraSettings, g_XMSelect1100); pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::DisableRimLighting() { pImpl->constants.rimColorAndPower = g_XMIdentityR3; @@ -1302,14 +1241,11 @@ void NPREffect::DisableRimLighting() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - //-------------------------------------------------------------------------------------- // SkinnedNPREffect //-------------------------------------------------------------------------------------- -SkinnedNPREffect::~SkinnedNPREffect() -{} - +SkinnedNPREffect::~SkinnedNPREffect() {} // IEffect methods. void SkinnedNPREffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -1317,7 +1253,6 @@ void SkinnedNPREffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->ApplySkinning(commandList); } - // Animation settings. void SkinnedNPREffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { @@ -1328,22 +1263,21 @@ void SkinnedNPREffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value for (size_t i = 0; i < count; i++) { - #if DIRECTX_MATH_VERSION >= 313 +#if DIRECTX_MATH_VERSION >= 313 XMStoreFloat3x4A(reinterpret_cast(&boneConstant[i]), value[i]); - #else - // Xbox One XDK has an older version of DirectXMath +#else + // Xbox One XDK has an older version of DirectXMath XMMATRIX boneMatrix = XMMatrixTranspose(value[i]); boneConstant[i][0] = boneMatrix.r[0]; boneConstant[i][1] = boneMatrix.r[1]; boneConstant[i][2] = boneMatrix.r[2]; - #endif +#endif } pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferBones; } - void SkinnedNPREffect::ResetBoneTransforms() { auto boneConstant = pImpl->boneConstants.Bones; diff --git a/Src/NPREffectFactory.cpp b/Src/NPREffectFactory.cpp index 0311c1f0..8a0b0b49 100644 --- a/Src/NPREffectFactory.cpp +++ b/Src/NPREffectFactory.cpp @@ -16,7 +16,6 @@ #include - using namespace DirectX; using Microsoft::WRL::ComPtr; @@ -44,23 +43,24 @@ namespace effect->DisableSpecular(); } } -} +} // namespace // Internal NPREffectFactory implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing NPREffectFactory instances. class NPREffectFactory::Impl { public: - Impl(_In_ ID3D12Device* device, _In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept(false) - : mTextureDescriptors(nullptr) - , mSamplerDescriptors(nullptr) - , mMode(NPREffect::Mode_Cel) - , mSharing(true) - , mEnableInstancing(false) - , mUseEmissiveForMatCap(true) - , mMatcapTextureIndex(-1) - , mMatcapSamplerIndex(-1) - , mDevice(device) + Impl(_In_ ID3D12Device* device, _In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept( + false) + : mTextureDescriptors(nullptr), + mSamplerDescriptors(nullptr), + mMode(NPREffect::Mode_Cel), + mSharing(true), + mEnableInstancing(false), + mUseEmissiveForMatCap(true), + mMatcapTextureIndex(-1), + mMatcapSamplerIndex(-1), + mDevice(device) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -71,19 +71,18 @@ class NPREffectFactory::Impl mSamplerDescriptors = std::make_unique(samplerDescriptors); } - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = delete; + Impl(Impl&&) = delete; Impl& operator=(Impl&&) = delete; - std::shared_ptr CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset, - int samplerDescriptorOffset); + std::shared_ptr CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset, + int samplerDescriptorOffset); void ReleaseCache(); @@ -91,44 +90,48 @@ class NPREffectFactory::Impl std::unique_ptr mSamplerDescriptors; NPREffect::Mode mMode; - bool mSharing; - bool mEnableInstancing; - bool mUseEmissiveForMatCap; - int mMatcapTextureIndex; - int mMatcapSamplerIndex; + bool mSharing; + bool mEnableInstancing; + bool mUseEmissiveForMatCap; + int mMatcapTextureIndex; + int mMatcapSamplerIndex; ComPtr mDevice; private: - using EffectCache = std::map< std::wstring, std::shared_ptr >; + using EffectCache = std::map>; - EffectCache mEffectCache; - EffectCache mEffectCacheSkinning; - EffectCache mEffectCacheDualTexture; + EffectCache mEffectCache; + EffectCache mEffectCacheSkinning; + EffectCache mEffectCacheDualTexture; std::mutex mutex; }; - -std::shared_ptr NPREffectFactory::Impl::CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayoutDesc, - int textureDescriptorOffset, - int samplerDescriptorOffset) +std::shared_ptr NPREffectFactory::Impl::CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayoutDesc, + int textureDescriptorOffset, + int samplerDescriptorOffset) { // If textures are required, make sure we have a descriptor heap if (!mTextureDescriptors && (info.diffuseTextureIndex != -1 || info.specularTextureIndex != -1 || info.emissiveTextureIndex != -1)) { - DebugTrace("ERROR: NPREffectFactory created without texture descriptor heap with texture index set (diffuse %d, specular %d, emissive %d)!\n", - info.diffuseTextureIndex, info.specularTextureIndex, info.emissiveTextureIndex); + DebugTrace( + "ERROR: NPREffectFactory created without texture descriptor heap with texture index set (diffuse %d, specular %d, emissive " + "%d)!\n", + info.diffuseTextureIndex, + info.specularTextureIndex, + info.emissiveTextureIndex); throw std::runtime_error("NPREffectFactory"); } if (!mSamplerDescriptors && (info.samplerIndex != -1 || info.samplerIndex2 != -1)) { - DebugTrace("ERROR: NPREffectFactory created without sampler descriptor heap with sampler index set (samplerIndex %d, samplerIndex2 %d)!\n", - info.samplerIndex, info.samplerIndex2); + DebugTrace( + "ERROR: NPREffectFactory created without sampler descriptor heap with sampler index set (samplerIndex %d, samplerIndex2 %d)!\n", + info.samplerIndex, + info.samplerIndex2); throw std::runtime_error("NPREffectFactory"); } @@ -146,15 +149,19 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( throw std::runtime_error("NPREffectFactory"); } - const int diffuseTextureIndex = (info.diffuseTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.diffuseTextureIndex + textureDescriptorOffset : -1; - const int specularTextureIndex = (info.specularTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.specularTextureIndex + textureDescriptorOffset : -1; - const int emissiveTextureIndex = (info.emissiveTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.emissiveTextureIndex + textureDescriptorOffset : -1; + const int diffuseTextureIndex + = (info.diffuseTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.diffuseTextureIndex + textureDescriptorOffset : -1; + const int specularTextureIndex + = (info.specularTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.specularTextureIndex + textureDescriptorOffset : -1; + const int emissiveTextureIndex + = (info.emissiveTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.emissiveTextureIndex + textureDescriptorOffset : -1; const int samplerIndex = (info.samplerIndex != -1 && mSamplerDescriptors != nullptr) ? info.samplerIndex + samplerDescriptorOffset : -1; - const int samplerIndex2 = (info.samplerIndex2 != -1 && mSamplerDescriptors != nullptr) ? info.samplerIndex2 + samplerDescriptorOffset : -1; + const int samplerIndex2 + = (info.samplerIndex2 != -1 && mSamplerDescriptors != nullptr) ? info.samplerIndex2 + samplerDescriptorOffset : -1; // Modify base pipeline state EffectPipelineStateDescription derivedPSD = (info.alphaValue < 1.0f) ? alphaPipelineState : opaquePipelineState; - derivedPSD.inputLayout = inputLayoutDesc; + derivedPSD.inputLayout = inputLayoutDesc; std::wstring cacheName; if (info.enableSkinning) @@ -170,7 +177,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + std::to_wstring(mMode) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + std::to_wstring(mMode) + info.name + std::to_wstring(hash); auto it = mEffectCacheSkinning.find(cacheName); if (mSharing && it != mEffectCacheSkinning.end()) @@ -185,8 +192,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } @@ -200,8 +206,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( throw std::runtime_error("NPREffectFactory"); } - effect->SetMatCap( - mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), + effect->SetMatCap(mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } else if (mMatcapTextureIndex != -1) @@ -209,13 +214,11 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( auto matcap = mTextureDescriptors->GetGpuHandle(static_cast(mMatcapTextureIndex)); if (samplerIndex != -1) { - effect->SetMatCap(matcap, - mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); + effect->SetMatCap(matcap, mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } else if (mMatcapSamplerIndex != -1) { - effect->SetMatCap(matcap, - mSamplerDescriptors->GetGpuHandle(static_cast(mMatcapSamplerIndex))); + effect->SetMatCap(matcap, mSamplerDescriptors->GetGpuHandle(static_cast(mMatcapSamplerIndex))); } } } @@ -223,7 +226,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCacheSkinning.insert(v); } @@ -237,7 +240,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCacheDualTexture.find(cacheName); if (mSharing && it != mEffectCacheDualTexture.end()) @@ -261,8 +264,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } @@ -274,8 +276,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( throw std::runtime_error("NPREffectFactory"); } - effect->SetTexture2( - mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), + effect->SetTexture2(mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex2))); } else if (specularTextureIndex != -1) @@ -287,15 +288,14 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( throw std::runtime_error("NPREffectFactory"); } - effect->SetTexture2( - mTextureDescriptors->GetGpuHandle(static_cast(specularTextureIndex)), + effect->SetTexture2(mTextureDescriptors->GetGpuHandle(static_cast(specularTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex2))); } if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCacheDualTexture.insert(v); } @@ -325,7 +325,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + std::to_wstring(mMode) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + std::to_wstring(mMode) + info.name + std::to_wstring(hash); auto it = mEffectCache.find(cacheName); if (mSharing && it != mEffectCache.end()) @@ -340,8 +340,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (diffuseTextureIndex != -1) { - effect->SetTexture( - mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), + effect->SetTexture(mTextureDescriptors->GetGpuHandle(static_cast(diffuseTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } @@ -355,8 +354,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( throw std::runtime_error("NPREffectFactory"); } - effect->SetMatCap( - mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), + effect->SetMatCap(mTextureDescriptors->GetGpuHandle(static_cast(emissiveTextureIndex)), mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } else if (mMatcapTextureIndex != -1) @@ -364,13 +362,11 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( auto matcap = mTextureDescriptors->GetGpuHandle(static_cast(mMatcapTextureIndex)); if (samplerIndex != -1) { - effect->SetMatCap(matcap, - mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); + effect->SetMatCap(matcap, mSamplerDescriptors->GetGpuHandle(static_cast(samplerIndex))); } else if (mMatcapSamplerIndex != -1) { - effect->SetMatCap(matcap, - mSamplerDescriptors->GetGpuHandle(static_cast(mMatcapSamplerIndex))); + effect->SetMatCap(matcap, mSamplerDescriptors->GetGpuHandle(static_cast(mMatcapSamplerIndex))); } } } @@ -378,7 +374,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCache.insert(v); } @@ -394,32 +390,32 @@ void NPREffectFactory::Impl::ReleaseCache() mEffectCacheDualTexture.clear(); } - - //-------------------------------------------------------------------------------------- // NPREffectFactory //-------------------------------------------------------------------------------------- -NPREffectFactory::NPREffectFactory(_In_ ID3D12Device* device) : - pImpl(std::make_shared(device, nullptr, nullptr)) +NPREffectFactory::NPREffectFactory(_In_ ID3D12Device* device) + : pImpl(std::make_shared(device, nullptr, nullptr)) {} NPREffectFactory::NPREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) { if (!textureDescriptors) { - throw std::invalid_argument("Texture descriptor heap cannot be null if no device is provided. Use the alternative NPREffectFactory constructor instead."); + throw std::invalid_argument( + "Texture descriptor heap cannot be null if no device is provided. Use the alternative NPREffectFactory constructor instead."); } if (!samplerDescriptors) { - throw std::invalid_argument("Descriptor heap cannot be null if no device is provided. Use the alternative NPREffectFactory constructor instead."); + throw std::invalid_argument( + "Descriptor heap cannot be null if no device is provided. Use the alternative NPREffectFactory constructor instead."); } #if defined(_MSC_VER) || !defined(_WIN32) const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc().Type; const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc().Type; #else - D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2; + D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2; const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc(&tmpDesc1)->Type; const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc(&tmpDesc2)->Type; #endif @@ -444,30 +440,26 @@ NPREffectFactory::NPREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors pImpl = std::make_shared(device.Get(), textureDescriptors, samplerDescriptors); } +NPREffectFactory::NPREffectFactory(NPREffectFactory&&) noexcept = default; +NPREffectFactory& NPREffectFactory::operator=(NPREffectFactory&&) noexcept = default; +NPREffectFactory::~NPREffectFactory() = default; -NPREffectFactory::NPREffectFactory(NPREffectFactory&&) noexcept = default; -NPREffectFactory& NPREffectFactory::operator= (NPREffectFactory&&) noexcept = default; -NPREffectFactory::~NPREffectFactory() = default; - - -std::shared_ptr NPREffectFactory::CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset, - int samplerDescriptorOffset) +std::shared_ptr NPREffectFactory::CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset, + int samplerDescriptorOffset) { - return pImpl->CreateEffect(info, opaquePipelineState, alphaPipelineState, inputLayout, textureDescriptorOffset, samplerDescriptorOffset); + return pImpl + ->CreateEffect(info, opaquePipelineState, alphaPipelineState, inputLayout, textureDescriptorOffset, samplerDescriptorOffset); } - void NPREffectFactory::ReleaseCache() { pImpl->ReleaseCache(); } - // Properties. void NPREffectFactory::SetSharing(bool enabled) noexcept { diff --git a/Src/NormalMapEffect.cpp b/Src/NormalMapEffect.cpp index 2206d635..6bd0a7e7 100644 --- a/Src/NormalMapEffect.cpp +++ b/Src/NormalMapEffect.cpp @@ -16,7 +16,7 @@ namespace DirectX { constexpr int ConstantBufferBones = 0x100000; } -} +} // namespace DirectX using namespace DirectX; @@ -52,18 +52,17 @@ namespace static_assert((sizeof(BoneConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct NormalMapEffectTraits { using ConstantBufferType = NormalMapEffectConstants; - static constexpr int VertexShaderCount = 20; - static constexpr int PixelShaderCount = 4; + static constexpr int VertexShaderCount = 20; + static constexpr int PixelShaderCount = 4; static constexpr int ShaderPermutationCount = 40; - static constexpr int RootSignatureCount = 2; + static constexpr int RootSignatureCount = 2; }; -} +} // namespace // Internal NormalMapEffect implementation class. class NormalMapEffect::Impl : public EffectBase @@ -71,17 +70,16 @@ class NormalMapEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D12Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; - void Initialize( - _In_ ID3D12Device* device, - uint32_t effectFlags, + void Initialize(_In_ ID3D12Device* device, + uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - bool enableSkinning); + bool enableSkinning); enum RootParameterIndex { @@ -94,7 +92,7 @@ class NormalMapEffect::Impl : public EffectBase RootParameterCount }; - int weightsPerVertex; + int weightsPerVertex; bool specularMap; D3D12_GPU_DESCRIPTOR_HANDLE texture; @@ -114,7 +112,6 @@ class NormalMapEffect::Impl : public EffectBase GraphicsResource mBones; }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -240,195 +237,196 @@ namespace #include "NormalMapEffect_PSNormalPixelLightingTxNoSpec.inc" #include "NormalMapEffect_PSNormalPixelLightingTxNoFogSpec.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { NormalMapEffect_VSNormalPixelLightingTx, sizeof(NormalMapEffect_VSNormalPixelLightingTx) }, - { NormalMapEffect_VSNormalPixelLightingTxVc, sizeof(NormalMapEffect_VSNormalPixelLightingTxVc) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { NormalMapEffect_VSNormalPixelLightingTx, sizeof(NormalMapEffect_VSNormalPixelLightingTx) }, + { NormalMapEffect_VSNormalPixelLightingTxVc, sizeof(NormalMapEffect_VSNormalPixelLightingTxVc) }, - { NormalMapEffect_VSNormalPixelLightingTxBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxBn) }, - { NormalMapEffect_VSNormalPixelLightingTxVcBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcBn) }, + { NormalMapEffect_VSNormalPixelLightingTxBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxBn) }, + { NormalMapEffect_VSNormalPixelLightingTxVcBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcBn) }, - { NormalMapEffect_VSNormalPixelLightingTxNoSpec, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpec) }, - { NormalMapEffect_VSNormalPixelLightingTxVcNoSpec, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcNoSpec) }, + { NormalMapEffect_VSNormalPixelLightingTxNoSpec, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpec) }, + { NormalMapEffect_VSNormalPixelLightingTxVcNoSpec, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcNoSpec) }, - { NormalMapEffect_VSNormalPixelLightingTxNoSpecBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpecBn) }, - { NormalMapEffect_VSNormalPixelLightingTxVcNoSpecBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcNoSpecBn) }, + { NormalMapEffect_VSNormalPixelLightingTxNoSpecBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpecBn) }, + { NormalMapEffect_VSNormalPixelLightingTxVcNoSpecBn, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcNoSpecBn) }, - { NormalMapEffect_VSNormalPixelLightingTxInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxInst) }, - { NormalMapEffect_VSNormalPixelLightingTxVcInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcInst) }, + { NormalMapEffect_VSNormalPixelLightingTxInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxInst) }, + { NormalMapEffect_VSNormalPixelLightingTxVcInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcInst) }, - { NormalMapEffect_VSNormalPixelLightingTxBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxBnInst) }, - { NormalMapEffect_VSNormalPixelLightingTxVcBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcBnInst) }, + { NormalMapEffect_VSNormalPixelLightingTxBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxBnInst) }, + { NormalMapEffect_VSNormalPixelLightingTxVcBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcBnInst) }, - { NormalMapEffect_VSNormalPixelLightingTxNoSpecInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpecInst) }, - { NormalMapEffect_VSNormalPixelLightingTxVcNoSpecInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcNoSpecInst) }, + { NormalMapEffect_VSNormalPixelLightingTxNoSpecInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpecInst) }, + { NormalMapEffect_VSNormalPixelLightingTxVcNoSpecInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcNoSpecInst) }, - { NormalMapEffect_VSNormalPixelLightingTxNoSpecBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpecBnInst) }, + { NormalMapEffect_VSNormalPixelLightingTxNoSpecBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxNoSpecBnInst) }, { NormalMapEffect_VSNormalPixelLightingTxVcNoSpecBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcNoSpecBnInst) }, - { NormalMapEffect_VSSkinnedPixelLightingTx, sizeof(NormalMapEffect_VSSkinnedPixelLightingTx) }, - { NormalMapEffect_VSSkinnedPixelLightingTxBn, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxBn) }, - { NormalMapEffect_VSSkinnedPixelLightingTxNoSpec, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxNoSpec) }, - { NormalMapEffect_VSSkinnedPixelLightingTxNoSpecBn, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxNoSpecBn) }, + { NormalMapEffect_VSSkinnedPixelLightingTx, sizeof(NormalMapEffect_VSSkinnedPixelLightingTx) }, + { NormalMapEffect_VSSkinnedPixelLightingTxBn, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxBn) }, + { NormalMapEffect_VSSkinnedPixelLightingTxNoSpec, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxNoSpec) }, + { NormalMapEffect_VSSkinnedPixelLightingTxNoSpecBn, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxNoSpecBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // pixel lighting + texture - 0, // pixel lighting + texture, no fog - 4, // pixel lighting + texture, no specular - 4, // pixel lighting + texture, no fog or specular - - 2, // pixel lighting (biased vertex normal) + texture - 2, // pixel lighting (biased vertex normal) + texture, no fog - 6, // pixel lighting (biased vertex normal) + texture, no specular - 6, // pixel lighting (biased vertex normal) + texture, no fog or specular - - 1, // pixel lighting + texture + vertex color - 1, // pixel lighting + texture + vertex color, no fog - 5, // pixel lighting + texture + vertex color, no specular - 5, // pixel lighting + texture + vertex color, no fog or specular - - 3, // pixel lighting (biased vertex normal) + texture + vertex color - 3, // pixel lighting (biased vertex normal) + texture + vertex color, no fog - 7, // pixel lighting (biased vertex normal) + texture + vertex color, no specular - 7, // pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular - - 8, // instancing + pixel lighting + texture - 8, // instancing + pixel lighting + texture, no fog - 12, // instancing + pixel lighting + texture, no specular - 12, // instancing + pixel lighting + texture, no fog or specular - - 10, // instancing + pixel lighting (biased vertex normal) + texture - 10, // instancing + pixel lighting (biased vertex normal) + texture, no fog - 14, // instancing + pixel lighting (biased vertex normal) + texture, no specular - 14, // instancing + pixel lighting (biased vertex normal) + texture, no fog or specular - - 9, // instancing + pixel lighting + texture + vertex color - 9, // instancing + pixel lighting + texture + vertex color, no fog - 13, // instancing + pixel lighting + texture + vertex color, no specular - 13, // instancing + pixel lighting + texture + vertex color, no fog or specular - - 11, // instancing + pixel lighting (biased vertex normal) + texture + vertex color - 11, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog - 15, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no specular - 15, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular - - 16, // skinning + pixel lighting + texture - 16, // skinning + pixel lighting + texture, no fog - 18, // skinning + pixel lighting + texture, no specular - 18, // skinning + pixel lighting + texture, no fog or specular - - 17, // skinning + pixel lighting (biased vertex normal) + texture - 17, // skinning + pixel lighting (biased vertex normal) + texture, no fog - 19, // skinning + pixel lighting (biased vertex normal) + texture, no specular - 19, // skinning + pixel lighting (biased vertex normal) + texture, no fog or specular +const int EffectBase::VertexShaderIndices[] = { + 0, // pixel lighting + texture + 0, // pixel lighting + texture, no fog + 4, // pixel lighting + texture, no specular + 4, // pixel lighting + texture, no fog or specular + + 2, // pixel lighting (biased vertex normal) + texture + 2, // pixel lighting (biased vertex normal) + texture, no fog + 6, // pixel lighting (biased vertex normal) + texture, no specular + 6, // pixel lighting (biased vertex normal) + texture, no fog or specular + + 1, // pixel lighting + texture + vertex color + 1, // pixel lighting + texture + vertex color, no fog + 5, // pixel lighting + texture + vertex color, no specular + 5, // pixel lighting + texture + vertex color, no fog or specular + + 3, // pixel lighting (biased vertex normal) + texture + vertex color + 3, // pixel lighting (biased vertex normal) + texture + vertex color, no fog + 7, // pixel lighting (biased vertex normal) + texture + vertex color, no specular + 7, // pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular + + 8, // instancing + pixel lighting + texture + 8, // instancing + pixel lighting + texture, no fog + 12, // instancing + pixel lighting + texture, no specular + 12, // instancing + pixel lighting + texture, no fog or specular + + 10, // instancing + pixel lighting (biased vertex normal) + texture + 10, // instancing + pixel lighting (biased vertex normal) + texture, no fog + 14, // instancing + pixel lighting (biased vertex normal) + texture, no specular + 14, // instancing + pixel lighting (biased vertex normal) + texture, no fog or specular + + 9, // instancing + pixel lighting + texture + vertex color + 9, // instancing + pixel lighting + texture + vertex color, no fog + 13, // instancing + pixel lighting + texture + vertex color, no specular + 13, // instancing + pixel lighting + texture + vertex color, no fog or specular + + 11, // instancing + pixel lighting (biased vertex normal) + texture + vertex color + 11, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog + 15, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no specular + 15, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular + + 16, // skinning + pixel lighting + texture + 16, // skinning + pixel lighting + texture, no fog + 18, // skinning + pixel lighting + texture, no specular + 18, // skinning + pixel lighting + texture, no fog or specular + + 17, // skinning + pixel lighting (biased vertex normal) + texture + 17, // skinning + pixel lighting (biased vertex normal) + texture, no fog + 19, // skinning + pixel lighting (biased vertex normal) + texture, no specular + 19, // skinning + pixel lighting (biased vertex normal) + texture, no fog or specular }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { NormalMapEffect_PSNormalPixelLightingTx, sizeof(NormalMapEffect_PSNormalPixelLightingTx) }, - { NormalMapEffect_PSNormalPixelLightingTxNoFog, sizeof(NormalMapEffect_PSNormalPixelLightingTxNoFog) }, - { NormalMapEffect_PSNormalPixelLightingTxNoSpec, sizeof(NormalMapEffect_PSNormalPixelLightingTxNoSpec) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { NormalMapEffect_PSNormalPixelLightingTx, sizeof(NormalMapEffect_PSNormalPixelLightingTx) }, + { NormalMapEffect_PSNormalPixelLightingTxNoFog, sizeof(NormalMapEffect_PSNormalPixelLightingTxNoFog) }, + { NormalMapEffect_PSNormalPixelLightingTxNoSpec, sizeof(NormalMapEffect_PSNormalPixelLightingTxNoSpec) }, { NormalMapEffect_PSNormalPixelLightingTxNoFogSpec, sizeof(NormalMapEffect_PSNormalPixelLightingTxNoFogSpec) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // pixel lighting + texture - 1, // pixel lighting + texture, no fog - 2, // pixel lighting + texture, no specular - 3, // pixel lighting + texture, no fog or specular - - 0, // pixel lighting (biased vertex normal) + texture - 1, // pixel lighting (biased vertex normal) + texture, no fog - 2, // pixel lighting (biased vertex normal) + texture, no specular - 3, // pixel lighting (biased vertex normal) + texture, no fog or specular - - 0, // pixel lighting + texture + vertex color - 1, // pixel lighting + texture + vertex color, no fog - 2, // pixel lighting + texture + vertex color, no specular - 3, // pixel lighting + texture + vertex color, no fog or specular - - 0, // pixel lighting (biased vertex normal) + texture + vertex color - 1, // pixel lighting (biased vertex normal) + texture + vertex color, no fog - 2, // pixel lighting (biased vertex normal) + texture + vertex color, no specular - 3, // pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular - - 0, // instancing + pixel lighting + texture - 1, // instancing + pixel lighting + texture, no fog - 2, // instancing + pixel lighting + texture, no specular - 3, // instancing + pixel lighting + texture, no fog or specular - - 0, // instancing + pixel lighting (biased vertex normal) + texture - 1, // instancing + pixel lighting (biased vertex normal) + texture, no fog - 2, // instancing + pixel lighting (biased vertex normal) + texture, no specular - 3, // instancing + pixel lighting (biased vertex normal) + texture, no fog or specular - - 0, // instancing + pixel lighting + texture + vertex color - 1, // instancing + pixel lighting + texture + vertex color, no fog - 2, // instancing + pixel lighting + texture + vertex color, no specular - 3, // instancing + pixel lighting + texture + vertex color, no fog or specular - - 0, // instancing + pixel lighting (biased vertex normal) + texture + vertex color - 1, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog - 2, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no specular - 3, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular - - 0, // skinning + pixel lighting + texture - 1, // skinning + pixel lighting + texture, no fog - 2, // skinning + pixel lighting + texture, no specular - 3, // skinning + pixel lighting + texture, no fog or specular - - 0, // skinning + pixel lighting (biased vertex normal) + texture - 1, // skinning + pixel lighting (biased vertex normal) + texture, no fog - 2, // skinning + pixel lighting (biased vertex normal) + texture, no specular - 3, // skinning + pixel lighting (biased vertex normal) + texture, no fog or specular +const int EffectBase::PixelShaderIndices[] = { + 0, // pixel lighting + texture + 1, // pixel lighting + texture, no fog + 2, // pixel lighting + texture, no specular + 3, // pixel lighting + texture, no fog or specular + + 0, // pixel lighting (biased vertex normal) + texture + 1, // pixel lighting (biased vertex normal) + texture, no fog + 2, // pixel lighting (biased vertex normal) + texture, no specular + 3, // pixel lighting (biased vertex normal) + texture, no fog or specular + + 0, // pixel lighting + texture + vertex color + 1, // pixel lighting + texture + vertex color, no fog + 2, // pixel lighting + texture + vertex color, no specular + 3, // pixel lighting + texture + vertex color, no fog or specular + + 0, // pixel lighting (biased vertex normal) + texture + vertex color + 1, // pixel lighting (biased vertex normal) + texture + vertex color, no fog + 2, // pixel lighting (biased vertex normal) + texture + vertex color, no specular + 3, // pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular + + 0, // instancing + pixel lighting + texture + 1, // instancing + pixel lighting + texture, no fog + 2, // instancing + pixel lighting + texture, no specular + 3, // instancing + pixel lighting + texture, no fog or specular + + 0, // instancing + pixel lighting (biased vertex normal) + texture + 1, // instancing + pixel lighting (biased vertex normal) + texture, no fog + 2, // instancing + pixel lighting (biased vertex normal) + texture, no specular + 3, // instancing + pixel lighting (biased vertex normal) + texture, no fog or specular + + 0, // instancing + pixel lighting + texture + vertex color + 1, // instancing + pixel lighting + texture + vertex color, no fog + 2, // instancing + pixel lighting + texture + vertex color, no specular + 3, // instancing + pixel lighting + texture + vertex color, no fog or specular + + 0, // instancing + pixel lighting (biased vertex normal) + texture + vertex color + 1, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog + 2, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no specular + 3, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular + + 0, // skinning + pixel lighting + texture + 1, // skinning + pixel lighting + texture, no fog + 2, // skinning + pixel lighting + texture, no specular + 3, // skinning + pixel lighting + texture, no fog or specular + + 0, // skinning + pixel lighting (biased vertex normal) + texture + 1, // skinning + pixel lighting (biased vertex normal) + texture, no fog + 2, // skinning + pixel lighting (biased vertex normal) + texture, no specular + 3, // skinning + pixel lighting (biased vertex normal) + texture, no fog or specular }; #pragma endregion // Global pool of per-device NormalMapEffect resources. template<> -SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - +SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool + = {}; // Constructor. -NormalMapEffect::Impl::Impl( - _In_ ID3D12Device* device) +NormalMapEffect::Impl::Impl(_In_ ID3D12Device* device) : EffectBase(device), - weightsPerVertex(0), - specularMap(false), - texture{}, - normal{}, - specular{}, - sampler{}, - boneConstants{} -{ - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == NormalMapEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == NormalMapEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); -} - -void NormalMapEffect::Impl::Initialize( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - bool enableSkinning) + weightsPerVertex(0), + specularMap(false), + texture{}, + normal{}, + specular{}, + sampler{}, + boneConstants{} +{ + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) + == NormalMapEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) + == NormalMapEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) + == NormalMapEffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) + == NormalMapEffectTraits::ShaderPermutationCount, + "array/max mismatch"); +} + +void NormalMapEffect::Impl::Initialize(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + bool enableSkinning) { specularMap = (effectFlags & EffectFlags::Specular) != 0; - lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); + lights.InitializeConstants(constants.specularColorAndPower, + constants.lightDirection, + constants.lightDiffuseColor, + constants.lightSpecularColor); if (enableSkinning) { @@ -455,18 +453,15 @@ void NormalMapEffect::Impl::Initialize( // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; - CD3DX12_ROOT_PARAMETER rootParameters[RootParameterIndex::RootParameterCount] = {}; + CD3DX12_ROOT_PARAMETER rootParameters[RootParameterIndex::RootParameterCount] = {}; const CD3DX12_DESCRIPTOR_RANGE textureSRV(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); rootParameters[RootParameterIndex::TextureSRV].InitAsDescriptorTable(1, &textureSRV, D3D12_SHADER_VISIBILITY_PIXEL); @@ -513,8 +508,7 @@ void NormalMapEffect::Impl::Initialize( assert(pi >= 0 && pi < NormalMapEffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < NormalMapEffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -530,7 +524,6 @@ void NormalMapEffect::Impl::Initialize( } } - int NormalMapEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const noexcept { int permutation = 0; @@ -575,14 +568,20 @@ int NormalMapEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) con return permutation; } - // Sets our state onto the D3D device. void NormalMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { // Compute derived parameter values. matrices.SetConstants(dirtyFlags, constants.worldViewProj); fog.SetConstants(dirtyFlags, matrices.worldView, constants.fogVector); - lights.SetConstants(dirtyFlags, matrices, constants.world, constants.worldInverseTranspose, constants.eyePosition, constants.diffuseColor, constants.emissiveColor, true); + lights.SetConstants(dirtyFlags, + matrices, + constants.world, + constants.worldInverseTranspose, + constants.eyePosition, + constants.diffuseColor, + constants.emissiveColor, + true); UpdateConstants(); @@ -601,11 +600,15 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) // Set the texture if (!texture.ptr || !sampler.ptr || !normal.ptr) { - DebugTrace("ERROR: Missing texture(s) or sampler for NormalMapEffect (texture %llu, normal %llu, sampler %llu)\n", texture.ptr, normal.ptr, sampler.ptr); + DebugTrace("ERROR: Missing texture(s) or sampler for NormalMapEffect (texture %llu, normal %llu, sampler %llu)\n", + texture.ptr, + normal.ptr, + sampler.ptr); throw std::runtime_error("NormalMapEffect"); } - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heaps. commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureNormalSRV, normal); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSampler, sampler); @@ -630,25 +633,22 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - //-------------------------------------------------------------------------------------- // NormalMapEffect //-------------------------------------------------------------------------------------- -NormalMapEffect::NormalMapEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - bool skinningEnabled) +NormalMapEffect::NormalMapEffect(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + bool skinningEnabled) : pImpl(std::make_unique(device)) { pImpl->Initialize(device, effectFlags, pipelineDescription, skinningEnabled); } -NormalMapEffect::NormalMapEffect(NormalMapEffect&&) noexcept = default; -NormalMapEffect& NormalMapEffect::operator= (NormalMapEffect&&) noexcept = default; -NormalMapEffect::~NormalMapEffect() = default; - +NormalMapEffect::NormalMapEffect(NormalMapEffect&&) noexcept = default; +NormalMapEffect& NormalMapEffect::operator=(NormalMapEffect&&) noexcept = default; +NormalMapEffect::~NormalMapEffect() = default; // IEffect methods void NormalMapEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -656,7 +656,6 @@ void NormalMapEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings void XM_CALLCONV NormalMapEffect::SetWorld(FXMMATRIX value) { @@ -665,7 +664,6 @@ void XM_CALLCONV NormalMapEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::FogVector; } - void XM_CALLCONV NormalMapEffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -673,7 +671,6 @@ void XM_CALLCONV NormalMapEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; } - void XM_CALLCONV NormalMapEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -681,17 +678,16 @@ void XM_CALLCONV NormalMapEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV NormalMapEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; - pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; + pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition + | EffectDirtyFlags::FogVector; } - // Material settings void XM_CALLCONV NormalMapEffect::SetDiffuseColor(FXMVECTOR value) { @@ -700,7 +696,6 @@ void XM_CALLCONV NormalMapEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV NormalMapEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -708,7 +703,6 @@ void XM_CALLCONV NormalMapEffect::SetEmissiveColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV NormalMapEffect::SetSpecularColor(FXMVECTOR value) { // Set xyz to new value, but preserve existing w (specular power). @@ -717,7 +711,6 @@ void XM_CALLCONV NormalMapEffect::SetSpecularColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NormalMapEffect::SetSpecularPower(float value) { // Set w to new value, but preserve existing xyz (specular color). @@ -726,7 +719,6 @@ void NormalMapEffect::SetSpecularPower(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NormalMapEffect::DisableSpecular() { // Set specular color to black, power to 1 @@ -737,7 +729,6 @@ void NormalMapEffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NormalMapEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -745,16 +736,14 @@ void NormalMapEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV NormalMapEffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->lights.diffuseColor = value; - pImpl->lights.alpha = XMVectorGetW(value); + pImpl->lights.alpha = XMVectorGetW(value); pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - // Light settings void XM_CALLCONV NormalMapEffect::SetAmbientLightColor(FXMVECTOR value) { @@ -763,13 +752,12 @@ void XM_CALLCONV NormalMapEffect::SetAmbientLightColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void NormalMapEffect::SetLightEnabled(int whichLight, bool value) { - pImpl->dirtyFlags |= pImpl->lights.SetLightEnabled(whichLight, value, pImpl->constants.lightDiffuseColor, pImpl->constants.lightSpecularColor); + pImpl->dirtyFlags + |= pImpl->lights.SetLightEnabled(whichLight, value, pImpl->constants.lightDiffuseColor, pImpl->constants.lightSpecularColor); } - void XM_CALLCONV NormalMapEffect::SetLightDirection(int whichLight, FXMVECTOR value) { EffectLights::ValidateLightIndex(whichLight); @@ -779,25 +767,21 @@ void XM_CALLCONV NormalMapEffect::SetLightDirection(int whichLight, FXMVECTOR va pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV NormalMapEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR value) { pImpl->dirtyFlags |= pImpl->lights.SetLightDiffuseColor(whichLight, value, pImpl->constants.lightDiffuseColor); } - void XM_CALLCONV NormalMapEffect::SetLightSpecularColor(int whichLight, FXMVECTOR value) { pImpl->dirtyFlags |= pImpl->lights.SetLightSpecularColor(whichLight, value, pImpl->constants.lightSpecularColor); } - void NormalMapEffect::EnableDefaultLighting() { EffectLights::EnableDefaultLighting(this); } - // Fog settings. void NormalMapEffect::SetFogStart(float value) { @@ -806,7 +790,6 @@ void NormalMapEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void NormalMapEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -814,7 +797,6 @@ void NormalMapEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV NormalMapEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -822,7 +804,6 @@ void XM_CALLCONV NormalMapEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void NormalMapEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { @@ -830,30 +811,27 @@ void NormalMapEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D1 pImpl->sampler = samplerDescriptor; } - void NormalMapEffect::SetNormalTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { pImpl->normal = srvDescriptor; } - void NormalMapEffect::SetSpecularTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { if (!pImpl->specularMap) { - DebugTrace("WARNING: Specular texture set on NormalMapEffect instance created without specular shader (texture %llu)\n", srvDescriptor.ptr); + DebugTrace("WARNING: Specular texture set on NormalMapEffect instance created without specular shader (texture %llu)\n", + srvDescriptor.ptr); } pImpl->specular = srvDescriptor; } - //-------------------------------------------------------------------------------------- // SkinnedNormalMapEffect //-------------------------------------------------------------------------------------- -SkinnedNormalMapEffect::~SkinnedNormalMapEffect() -{} +SkinnedNormalMapEffect::~SkinnedNormalMapEffect() {} // Animation settings. void SkinnedNormalMapEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) @@ -865,22 +843,21 @@ void SkinnedNormalMapEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* for (size_t i = 0; i < count; i++) { - #if DIRECTX_MATH_VERSION >= 313 +#if DIRECTX_MATH_VERSION >= 313 XMStoreFloat3x4A(reinterpret_cast(&boneConstant[i]), value[i]); - #else - // Xbox One XDK has an older version of DirectXMath +#else + // Xbox One XDK has an older version of DirectXMath XMMATRIX boneMatrix = XMMatrixTranspose(value[i]); boneConstant[i][0] = boneMatrix.r[0]; boneConstant[i][1] = boneMatrix.r[1]; boneConstant[i][2] = boneMatrix.r[2]; - #endif +#endif } pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferBones; } - void SkinnedNormalMapEffect::ResetBoneTransforms() { auto boneConstant = pImpl->boneConstants.Bones; diff --git a/Src/PBREffect.cpp b/Src/PBREffect.cpp index 2cde5fff..d9db3c45 100644 --- a/Src/PBREffect.cpp +++ b/Src/PBREffect.cpp @@ -16,7 +16,7 @@ namespace DirectX { constexpr int ConstantBufferBones = 0x100000; } -} +} // namespace DirectX using namespace DirectX; @@ -41,8 +41,8 @@ namespace int numRadianceMipLevels; // Size of render target - float targetWidth; - float targetHeight; + float targetWidth; + float targetHeight; }; static_assert((sizeof(PBREffectConstants) % 16) == 0, "CB size not padded correctly"); @@ -54,18 +54,17 @@ namespace static_assert((sizeof(BoneConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct PBREffectTraits { using ConstantBufferType = PBREffectConstants; - static constexpr int VertexShaderCount = 8; - static constexpr int PixelShaderCount = 5; + static constexpr int VertexShaderCount = 8; + static constexpr int PixelShaderCount = 5; static constexpr int ShaderPermutationCount = 22; - static constexpr int RootSignatureCount = 1; + static constexpr int RootSignatureCount = 1; }; -} +} // namespace // Internal PBREffect implementation class. class PBREffect::Impl : public EffectBase @@ -73,17 +72,16 @@ class PBREffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D12Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; - void Initialize( - _In_ ID3D12Device* device, - uint32_t effectFlags, + void Initialize(_In_ ID3D12Device* device, + uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - bool enableSkinning); + bool enableSkinning); enum RootParameterIndex { @@ -100,7 +98,7 @@ class PBREffect::Impl : public EffectBase RootParametersCount }; - int weightsPerVertex; + int weightsPerVertex; bool textureEnabled; bool emissiveMap; @@ -118,7 +116,6 @@ class PBREffect::Impl : public EffectBase GraphicsResource mBones; }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -196,103 +193,95 @@ namespace #include "PBREffect_PSTexturedVelocity.inc" #include "PBREffect_PSTexturedEmissiveVelocity.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { PBREffect_VSConstant, sizeof(PBREffect_VSConstant) }, - { PBREffect_VSConstantVelocity, sizeof(PBREffect_VSConstantVelocity) }, - { PBREffect_VSConstantBn, sizeof(PBREffect_VSConstantBn) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { PBREffect_VSConstant, sizeof(PBREffect_VSConstant) }, + { PBREffect_VSConstantVelocity, sizeof(PBREffect_VSConstantVelocity) }, + { PBREffect_VSConstantBn, sizeof(PBREffect_VSConstantBn) }, { PBREffect_VSConstantVelocityBn, sizeof(PBREffect_VSConstantVelocityBn) }, - { PBREffect_VSConstantInst, sizeof(PBREffect_VSConstantInst) }, - { PBREffect_VSConstantBnInst, sizeof(PBREffect_VSConstantBnInst) }, + { PBREffect_VSConstantInst, sizeof(PBREffect_VSConstantInst) }, + { PBREffect_VSConstantBnInst, sizeof(PBREffect_VSConstantBnInst) }, - { PBREffect_VSSkinned, sizeof(PBREffect_VSSkinned) }, - { PBREffect_VSSkinnedBn, sizeof(PBREffect_VSSkinnedBn) }, + { PBREffect_VSSkinned, sizeof(PBREffect_VSSkinned) }, + { PBREffect_VSSkinnedBn, sizeof(PBREffect_VSSkinnedBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // constant - 0, // textured - 0, // textured + emissive +const int EffectBase::VertexShaderIndices[] = { + 0, // constant + 0, // textured + 0, // textured + emissive - 4, // instancing + constant - 4, // instancing + textured - 4, // instancing + textured + emissive + 4, // instancing + constant + 4, // instancing + textured + 4, // instancing + textured + emissive - 6, // skinning + constant - 6, // skinning + textured - 6, // skinning + textured + emissive + 6, // skinning + constant + 6, // skinning + textured + 6, // skinning + textured + emissive - 1, // textured + velocity - 1, // textured + emissive + velocity + 1, // textured + velocity + 1, // textured + emissive + velocity - 2, // constant (biased vertex normals) - 2, // textured (biased vertex normals) - 2, // textured + emissive (biased vertex normals) + 2, // constant (biased vertex normals) + 2, // textured (biased vertex normals) + 2, // textured + emissive (biased vertex normals) - 5, // instancing + constant (biased vertex normals) - 5, // instancing + textured (biased vertex normals) - 5, // instancing + textured + emissive (biased vertex normals) + 5, // instancing + constant (biased vertex normals) + 5, // instancing + textured (biased vertex normals) + 5, // instancing + textured + emissive (biased vertex normals) - 7, // skinning + constant (biased vertex normals) - 7, // skinning + textured (biased vertex normals) - 7, // skinning + textured + emissive (biased vertex normals) + 7, // skinning + constant (biased vertex normals) + 7, // skinning + textured (biased vertex normals) + 7, // skinning + textured + emissive (biased vertex normals) - 3, // textured + velocity (biased vertex normals) - 3, // textured + emissive + velocity (biasoed vertex normals) + 3, // textured + velocity (biased vertex normals) + 3, // textured + emissive + velocity (biasoed vertex normals) }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { PBREffect_PSConstant, sizeof(PBREffect_PSConstant) }, - { PBREffect_PSTextured, sizeof(PBREffect_PSTextured) }, - { PBREffect_PSTexturedEmissive, sizeof(PBREffect_PSTexturedEmissive) }, - { PBREffect_PSTexturedVelocity, sizeof(PBREffect_PSTexturedVelocity) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { PBREffect_PSConstant, sizeof(PBREffect_PSConstant) }, + { PBREffect_PSTextured, sizeof(PBREffect_PSTextured) }, + { PBREffect_PSTexturedEmissive, sizeof(PBREffect_PSTexturedEmissive) }, + { PBREffect_PSTexturedVelocity, sizeof(PBREffect_PSTexturedVelocity) }, { PBREffect_PSTexturedEmissiveVelocity, sizeof(PBREffect_PSTexturedEmissiveVelocity) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // constant - 1, // textured - 2, // textured + emissive +const int EffectBase::PixelShaderIndices[] = { + 0, // constant + 1, // textured + 2, // textured + emissive - 0, // instancing + constant - 1, // instancing + textured - 2, // instancing + textured + emissive + 0, // instancing + constant + 1, // instancing + textured + 2, // instancing + textured + emissive - 0, // skinning + constant - 1, // skinning + textured - 2, // skinning + textured + emissive + 0, // skinning + constant + 1, // skinning + textured + 2, // skinning + textured + emissive - 3, // textured + velocity - 4, // textured + emissive + velocity + 3, // textured + velocity + 4, // textured + emissive + velocity - 0, // constant (biased vertex normals) - 1, // textured (biased vertex normals) - 2, // textured + emissive (biased vertex normals) + 0, // constant (biased vertex normals) + 1, // textured (biased vertex normals) + 2, // textured + emissive (biased vertex normals) - 0, // instancing + constant (biased vertex normals) - 1, // instancing + textured (biased vertex normals) - 2, // instancing + textured + emissive (biased vertex normals) + 0, // instancing + constant (biased vertex normals) + 1, // instancing + textured (biased vertex normals) + 2, // instancing + textured + emissive (biased vertex normals) - 0, // skinning + constant (biased vertex normals) - 1, // skinning + textured (biased vertex normals) - 2, // skinning + textured + emissive (biased vertex normals) + 0, // skinning + constant (biased vertex normals) + 1, // skinning + textured (biased vertex normals) + 2, // skinning + textured + emissive (biased vertex normals) - 3, // textured + velocity (biased vertex normals) - 4, // textured + emissive + velocity (biased vertex normals) + 3, // textured + velocity (biased vertex normals) + 4, // textured + emissive + velocity (biased vertex normals) }; #pragma endregion @@ -303,24 +292,27 @@ SharedResourcePool::DeviceResources> // Constructor. PBREffect::Impl::Impl(_In_ ID3D12Device* device) : EffectBase(device), - weightsPerVertex(0), - textureEnabled(false), - emissiveMap(false), - descriptors{}, - lightColor{}, - boneConstants{} -{ - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == PBREffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == PBREffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); -} - -void PBREffect::Impl::Initialize( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription, - bool enableSkinning) + weightsPerVertex(0), + textureEnabled(false), + emissiveMap(false), + descriptors{}, + lightColor{}, + boneConstants{} +{ + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == PBREffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == PBREffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == PBREffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == PBREffectTraits::ShaderPermutationCount, + "array/max mismatch"); +} + +void PBREffect::Impl::Initialize(_In_ ID3D12Device* device, + uint32_t effectFlags, + const EffectPipelineStateDescription& pipelineDescription, + bool enableSkinning) { emissiveMap = (effectFlags & EffectFlags::Emissive) != 0; @@ -328,8 +320,8 @@ void PBREffect::Impl::Initialize( static const XMVECTORF32 defaultLightDirection = { { { 0, -1, 0, 0 } } }; for (int i = 0; i < MaxDirectionalLights; i++) { - lightColor[i] = g_XMOne; - constants.lightDirection[i] = defaultLightDirection; + lightColor[i] = g_XMOne; + constants.lightDirection[i] = defaultLightDirection; constants.lightDiffuseColor[i] = g_XMZero; } @@ -349,9 +341,9 @@ void PBREffect::Impl::Initialize( } // Default PBR values - constants.Albedo = g_XMOne; - constants.Metallic = 0.5f; - constants.Roughness = 0.2f; + constants.Albedo = g_XMOne; + constants.Metallic = 0.5f; + constants.Roughness = 0.2f; constants.numRadianceMipLevels = 1; if (enableSkinning) @@ -379,19 +371,16 @@ void PBREffect::Impl::Initialize( // Create root signature { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; - CD3DX12_ROOT_PARAMETER rootParameters[RootParametersCount] = {}; - CD3DX12_DESCRIPTOR_RANGE textureSRV[6] = { + CD3DX12_ROOT_PARAMETER rootParameters[RootParametersCount] = {}; + CD3DX12_DESCRIPTOR_RANGE textureSRV[6] = { CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0), CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1), CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 2), @@ -400,10 +389,8 @@ void PBREffect::Impl::Initialize( CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 5), }; - CD3DX12_DESCRIPTOR_RANGE textureSampler[2] = { - CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0), - CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 1) - }; + CD3DX12_DESCRIPTOR_RANGE textureSampler[2] = { CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0), + CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 1) }; for (size_t i = 0; i < std::size(textureSRV); i++) { @@ -454,8 +441,7 @@ void PBREffect::Impl::Initialize( assert(pi >= 0 && pi < PBREffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < PBREffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -471,7 +457,6 @@ void PBREffect::Impl::Initialize( } } - int PBREffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const noexcept { int permutation = 0; @@ -513,7 +498,6 @@ int PBREffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const noe return permutation; } - // Sets our state onto the D3D device. void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { @@ -521,12 +505,7 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) constants.prevWorldViewProj = constants.worldViewProj; // Compute derived parameter values. - matrices.SetConstants( - dirtyFlags, - constants.world, - constants.worldInverseTranspose, - constants.worldViewProj, - constants.eyePosition); + matrices.SetConstants(dirtyFlags, constants.world, constants.worldInverseTranspose, constants.worldViewProj, constants.eyePosition); // Set constants to GPU UpdateConstants(); @@ -545,7 +524,9 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!descriptors[RadianceTexture].ptr || !descriptors[RadianceSampler].ptr) { - DebugTrace("ERROR: Missing radiance texture or sampler for PBREffect (texture %llu, sampler %llu)\n", descriptors[RadianceTexture].ptr, descriptors[RadianceSampler].ptr); + DebugTrace("ERROR: Missing radiance texture or sampler for PBREffect (texture %llu, sampler %llu)\n", + descriptors[RadianceTexture].ptr, + descriptors[RadianceSampler].ptr); throw std::runtime_error("PBREffect"); } @@ -560,7 +541,8 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { // only update radiance/irradiance texture and samplers - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heaps. commandList->SetGraphicsRootDescriptorTable(RadianceTexture, descriptors[RadianceTexture]); commandList->SetGraphicsRootDescriptorTable(IrradianceTexture, descriptors[IrradianceTexture]); commandList->SetGraphicsRootDescriptorTable(RadianceSampler, descriptors[RadianceSampler]); @@ -576,7 +558,9 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { if (!descriptors[AlbedoTexture].ptr || !descriptors[SurfaceSampler].ptr) { - DebugTrace("ERROR: Missing albedo texture or sampler for PBREffect (texture %llu, sampler %llu)\n", descriptors[AlbedoTexture].ptr, descriptors[SurfaceSampler].ptr); + DebugTrace("ERROR: Missing albedo texture or sampler for PBREffect (texture %llu, sampler %llu)\n", + descriptors[AlbedoTexture].ptr, + descriptors[SurfaceSampler].ptr); throw std::runtime_error("PBREffect"); } @@ -597,7 +581,8 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (i == EmissiveTexture) continue; - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required + // descriptor heaps. commandList->SetGraphicsRootDescriptorTable(i, descriptors[i]); } @@ -616,7 +601,6 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) // Bind 'empty' textures to avoid warnings on PC commandList->SetGraphicsRootDescriptorTable(EmissiveTexture, descriptors[AlbedoTexture]); } - } // Set constants @@ -629,25 +613,22 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - //-------------------------------------------------------------------------------------- // PBREffect //-------------------------------------------------------------------------------------- -PBREffect::PBREffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, +PBREffect::PBREffect(_In_ ID3D12Device* device, + uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription, - bool skinningEnabled) + bool skinningEnabled) : pImpl(std::make_unique(device)) { pImpl->Initialize(device, effectFlags, pipelineDescription, skinningEnabled); } -PBREffect::PBREffect(PBREffect&&) noexcept = default; -PBREffect& PBREffect::operator= (PBREffect&&) noexcept = default; -PBREffect::~PBREffect() = default; - +PBREffect::PBREffect(PBREffect&&) noexcept = default; +PBREffect& PBREffect::operator=(PBREffect&&) noexcept = default; +PBREffect::~PBREffect() = default; // IEffect methods. void PBREffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -655,7 +636,6 @@ void PBREffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings. void XM_CALLCONV PBREffect::SetWorld(FXMMATRIX value) { @@ -664,7 +644,6 @@ void XM_CALLCONV PBREffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose; } - void XM_CALLCONV PBREffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -672,7 +651,6 @@ void XM_CALLCONV PBREffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition; } - void XM_CALLCONV PBREffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -680,24 +658,21 @@ void XM_CALLCONV PBREffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV PBREffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition; } - // Light settings void XM_CALLCONV PBREffect::SetAmbientLightColor(FXMVECTOR) { // Unsupported interface. } - void PBREffect::SetLightEnabled(int whichLight, bool value) { EffectLights::ValidateLightIndex(whichLight); @@ -707,7 +682,6 @@ void PBREffect::SetLightEnabled(int whichLight, bool value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV PBREffect::SetLightDirection(int whichLight, FXMVECTOR value) { EffectLights::ValidateLightIndex(whichLight); @@ -717,30 +691,26 @@ void XM_CALLCONV PBREffect::SetLightDirection(int whichLight, FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV PBREffect::SetLightDiffuseColor(int whichLight, FXMVECTOR value) { EffectLights::ValidateLightIndex(whichLight); - pImpl->lightColor[whichLight] = value; + pImpl->lightColor[whichLight] = value; pImpl->constants.lightDiffuseColor[whichLight] = value; pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV PBREffect::SetLightSpecularColor(int, FXMVECTOR) { // Unsupported interface. } - void PBREffect::EnableDefaultLighting() { EffectLights::EnableDefaultLighting(this); } - // PBR Settings void PBREffect::SetAlpha(float value) { @@ -750,7 +720,6 @@ void PBREffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void PBREffect::SetConstantAlbedo(FXMVECTOR value) { // Set xyz to new value, but preserve existing w (alpha). @@ -759,7 +728,6 @@ void PBREffect::SetConstantAlbedo(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void PBREffect::SetConstantMetallic(float value) { pImpl->constants.Metallic = value; @@ -767,7 +735,6 @@ void PBREffect::SetConstantMetallic(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void PBREffect::SetConstantRoughness(float value) { pImpl->constants.Roughness = value; @@ -775,84 +742,73 @@ void PBREffect::SetConstantRoughness(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void PBREffect::SetAlbedoTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { - pImpl->descriptors[Impl::RootParameterIndex::AlbedoTexture] = srvDescriptor; + pImpl->descriptors[Impl::RootParameterIndex::AlbedoTexture] = srvDescriptor; pImpl->descriptors[Impl::RootParameterIndex::SurfaceSampler] = samplerDescriptor; } - void PBREffect::SetNormalTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { pImpl->descriptors[Impl::RootParameterIndex::NormalTexture] = srvDescriptor; } - void PBREffect::SetRMATexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { pImpl->descriptors[Impl::RootParameterIndex::RMATexture] = srvDescriptor; } - void PBREffect::SetEmissiveTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { if (!pImpl->emissiveMap) { - DebugTrace("WARNING: Emissive texture set on PBREffect instance created without emissive shader (texture %llu)\n", srvDescriptor.ptr); + DebugTrace("WARNING: Emissive texture set on PBREffect instance created without emissive shader (texture %llu)\n", + srvDescriptor.ptr); } pImpl->descriptors[Impl::RootParameterIndex::EmissiveTexture] = srvDescriptor; } - -void PBREffect::SetSurfaceTextures( - D3D12_GPU_DESCRIPTOR_HANDLE albedo, - D3D12_GPU_DESCRIPTOR_HANDLE normal, - D3D12_GPU_DESCRIPTOR_HANDLE roughnessMetallicAmbientOcclusion, - D3D12_GPU_DESCRIPTOR_HANDLE sampler) +void PBREffect::SetSurfaceTextures(D3D12_GPU_DESCRIPTOR_HANDLE albedo, + D3D12_GPU_DESCRIPTOR_HANDLE normal, + D3D12_GPU_DESCRIPTOR_HANDLE roughnessMetallicAmbientOcclusion, + D3D12_GPU_DESCRIPTOR_HANDLE sampler) { - pImpl->descriptors[Impl::RootParameterIndex::AlbedoTexture] = albedo; - pImpl->descriptors[Impl::RootParameterIndex::NormalTexture] = normal; - pImpl->descriptors[Impl::RootParameterIndex::RMATexture] = roughnessMetallicAmbientOcclusion; + pImpl->descriptors[Impl::RootParameterIndex::AlbedoTexture] = albedo; + pImpl->descriptors[Impl::RootParameterIndex::NormalTexture] = normal; + pImpl->descriptors[Impl::RootParameterIndex::RMATexture] = roughnessMetallicAmbientOcclusion; pImpl->descriptors[Impl::RootParameterIndex::SurfaceSampler] = sampler; } - -void PBREffect::SetIBLTextures( - D3D12_GPU_DESCRIPTOR_HANDLE radiance, - int numRadianceMips, - D3D12_GPU_DESCRIPTOR_HANDLE irradiance, - D3D12_GPU_DESCRIPTOR_HANDLE sampler) +void PBREffect::SetIBLTextures(D3D12_GPU_DESCRIPTOR_HANDLE radiance, + int numRadianceMips, + D3D12_GPU_DESCRIPTOR_HANDLE irradiance, + D3D12_GPU_DESCRIPTOR_HANDLE sampler) { pImpl->descriptors[Impl::RootParameterIndex::RadianceTexture] = radiance; pImpl->descriptors[Impl::RootParameterIndex::RadianceSampler] = sampler; - pImpl->constants.numRadianceMipLevels = numRadianceMips; + pImpl->constants.numRadianceMipLevels = numRadianceMips; pImpl->descriptors[Impl::RootParameterIndex::IrradianceTexture] = irradiance; pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Additional settings. void PBREffect::SetRenderTargetSizeInPixels(int width, int height) { - pImpl->constants.targetWidth = static_cast(width); + pImpl->constants.targetWidth = static_cast(width); pImpl->constants.targetHeight = static_cast(height); pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - //-------------------------------------------------------------------------------------- // SkinnedPBREffect //-------------------------------------------------------------------------------------- -SkinnedPBREffect::~SkinnedPBREffect() -{} - +SkinnedPBREffect::~SkinnedPBREffect() {} // Animation settings. void SkinnedPBREffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) @@ -864,22 +820,21 @@ void SkinnedPBREffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value for (size_t i = 0; i < count; i++) { - #if DIRECTX_MATH_VERSION >= 313 +#if DIRECTX_MATH_VERSION >= 313 XMStoreFloat3x4A(reinterpret_cast(&boneConstant[i]), value[i]); - #else - // Xbox One XDK has an older version of DirectXMath +#else + // Xbox One XDK has an older version of DirectXMath XMMATRIX boneMatrix = XMMatrixTranspose(value[i]); boneConstant[i][0] = boneMatrix.r[0]; boneConstant[i][1] = boneMatrix.r[1]; boneConstant[i][2] = boneMatrix.r[2]; - #endif +#endif } pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferBones; } - void SkinnedPBREffect::ResetBoneTransforms() { auto boneConstant = pImpl->boneConstants.Bones; diff --git a/Src/PBREffectFactory.cpp b/Src/PBREffectFactory.cpp index 91438ecc..86c0ee70 100644 --- a/Src/PBREffectFactory.cpp +++ b/Src/PBREffectFactory.cpp @@ -16,20 +16,18 @@ #include - using namespace DirectX; using Microsoft::WRL::ComPtr; namespace { template - void SetPBRProperties( - _In_ T* effect, + void SetPBRProperties(_In_ T* effect, const EffectFactory::EffectInfo& info, - _In_ const DescriptorHeap* textures, - int textureDescriptorOffset, - _In_ const DescriptorHeap* samplers, - int samplerDescriptorOffset) + _In_ const DescriptorHeap* textures, + int textureDescriptorOffset, + _In_ const DescriptorHeap* samplers, + int samplerDescriptorOffset) { // We don't use EnableDefaultLighting generally for PBR as it uses Image-Based Lighting instead. @@ -39,12 +37,11 @@ namespace { // Textured PBR material const int albedoTextureIndex = info.diffuseTextureIndex + textureDescriptorOffset; - const int rmaTextureIndex = (info.specularTextureIndex != -1) ? info.specularTextureIndex + textureDescriptorOffset : -1; + const int rmaTextureIndex = (info.specularTextureIndex != -1) ? info.specularTextureIndex + textureDescriptorOffset : -1; const int normalTextureIndex = (info.normalTextureIndex != -1) ? info.normalTextureIndex + textureDescriptorOffset : -1; - const int samplerIndex = (info.samplerIndex != -1) ? info.samplerIndex + samplerDescriptorOffset : -1; + const int samplerIndex = (info.samplerIndex != -1) ? info.samplerIndex + samplerDescriptorOffset : -1; - effect->SetSurfaceTextures( - textures->GetGpuHandle(static_cast(albedoTextureIndex)), + effect->SetSurfaceTextures(textures->GetGpuHandle(static_cast(albedoTextureIndex)), textures->GetGpuHandle(static_cast(normalTextureIndex)), textures->GetGpuHandle(static_cast(rmaTextureIndex)), samplers->GetGpuHandle(static_cast(samplerIndex))); @@ -74,19 +71,20 @@ namespace // info.ambientColor, info.specularColor, and info.emissiveColor are unused by PBR. } } -} +} // namespace // Internal PBREffectFactory implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing PBREffectFactory instances. class PBREffectFactory::Impl { public: - Impl(_In_ ID3D12Device* device, _In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept(false) - : mSharing(true) - , mEnableInstancing(false) - , mTextureDescriptors(nullptr) - , mSamplerDescriptors(nullptr) - , mDevice(device) + Impl(_In_ ID3D12Device* device, _In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept( + false) + : mSharing(true), + mEnableInstancing(false), + mTextureDescriptors(nullptr), + mSamplerDescriptors(nullptr), + mDevice(device) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -97,19 +95,18 @@ class PBREffectFactory::Impl mSamplerDescriptors = std::make_unique(samplerDescriptors); } - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = delete; + Impl(Impl&&) = delete; Impl& operator=(Impl&&) = delete; - std::shared_ptr CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset, - int samplerDescriptorOffset); + std::shared_ptr CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset, + int samplerDescriptorOffset); void ReleaseCache(); @@ -122,22 +119,20 @@ class PBREffectFactory::Impl ComPtr mDevice; private: - using EffectCache = std::map< std::wstring, std::shared_ptr >; + using EffectCache = std::map>; - EffectCache mEffectCache; - EffectCache mEffectCacheSkinning; + EffectCache mEffectCache; + EffectCache mEffectCacheSkinning; std::mutex mutex; }; - -std::shared_ptr PBREffectFactory::Impl::CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayoutDesc, - int textureDescriptorOffset, - int samplerDescriptorOffset) +std::shared_ptr PBREffectFactory::Impl::CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayoutDesc, + int textureDescriptorOffset, + int samplerDescriptorOffset) { if (!mTextureDescriptors) { @@ -152,7 +147,7 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( // Modify base pipeline state EffectPipelineStateDescription derivedPSD = (info.alphaValue < 1.0f) ? alphaPipelineState : opaquePipelineState; - derivedPSD.inputLayout = inputLayoutDesc; + derivedPSD.inputLayout = inputLayoutDesc; // set effect flags for creation uint32_t effectflags = (info.diffuseTextureIndex != -1) ? EffectFlags::Texture : EffectFlags::None; @@ -176,7 +171,7 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCacheSkinning.find(cacheName); if (mSharing && it != mEffectCacheSkinning.end()) @@ -187,14 +182,17 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( auto effect = std::make_shared(mDevice.Get(), effectflags, derivedPSD); - SetPBRProperties(effect.get(), info, - mTextureDescriptors.get(), textureDescriptorOffset, - mSamplerDescriptors.get(), samplerDescriptorOffset); + SetPBRProperties(effect.get(), + info, + mTextureDescriptors.get(), + textureDescriptorOffset, + mSamplerDescriptors.get(), + samplerDescriptorOffset); if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCacheSkinning.insert(v); } @@ -212,7 +210,7 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( if (mSharing && !info.name.empty()) { const uint32_t hash = derivedPSD.ComputeHash(); - cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); + cacheName = std::to_wstring(effectflags) + info.name + std::to_wstring(hash); auto it = mEffectCache.find(cacheName); if (mSharing && it != mEffectCache.end()) @@ -223,14 +221,17 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( auto effect = std::make_shared(mDevice.Get(), effectflags, derivedPSD); - SetPBRProperties(effect.get(), info, - mTextureDescriptors.get(), textureDescriptorOffset, - mSamplerDescriptors.get(), samplerDescriptorOffset); + SetPBRProperties(effect.get(), + info, + mTextureDescriptors.get(), + textureDescriptorOffset, + mSamplerDescriptors.get(), + samplerDescriptorOffset); if (mSharing && !info.name.empty()) { std::lock_guard lock(mutex); - EffectCache::value_type v(cacheName, effect); + EffectCache::value_type v(cacheName, effect); mEffectCache.insert(v); } @@ -245,31 +246,33 @@ void PBREffectFactory::Impl::ReleaseCache() mEffectCacheSkinning.clear(); } - //-------------------------------------------------------------------------------------- // PBREffectFactory //-------------------------------------------------------------------------------------- -PBREffectFactory::PBREffectFactory(_In_ ID3D12Device* device) noexcept(false) : - pImpl(std::make_shared(device, nullptr, nullptr)) +PBREffectFactory::PBREffectFactory(_In_ ID3D12Device* device) noexcept(false) + : pImpl(std::make_shared(device, nullptr, nullptr)) {} -PBREffectFactory::PBREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept(false) +PBREffectFactory::PBREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept( + false) { if (!textureDescriptors) { - throw std::invalid_argument("Texture descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); + throw std::invalid_argument( + "Texture descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); } if (!samplerDescriptors) { - throw std::invalid_argument("Descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); + throw std::invalid_argument( + "Descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); } #if defined(_MSC_VER) || !defined(_WIN32) const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc().Type; const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc().Type; #else - D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2; + D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2; const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc(&tmpDesc1)->Type; const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc(&tmpDesc2)->Type; #endif @@ -294,29 +297,26 @@ PBREffectFactory::PBREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors pImpl = std::make_shared(device.Get(), textureDescriptors, samplerDescriptors); } -PBREffectFactory::PBREffectFactory(PBREffectFactory&&) noexcept = default; -PBREffectFactory& PBREffectFactory::operator= (PBREffectFactory&&) noexcept = default; -PBREffectFactory::~PBREffectFactory() = default; +PBREffectFactory::PBREffectFactory(PBREffectFactory&&) noexcept = default; +PBREffectFactory& PBREffectFactory::operator=(PBREffectFactory&&) noexcept = default; +PBREffectFactory::~PBREffectFactory() = default; - -std::shared_ptr PBREffectFactory::CreateEffect( - const EffectInfo& info, - const EffectPipelineStateDescription& opaquePipelineState, - const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, - int textureDescriptorOffset, - int samplerDescriptorOffset) +std::shared_ptr PBREffectFactory::CreateEffect(const EffectInfo& info, + const EffectPipelineStateDescription& opaquePipelineState, + const EffectPipelineStateDescription& alphaPipelineState, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, + int textureDescriptorOffset, + int samplerDescriptorOffset) { - return pImpl->CreateEffect(info, opaquePipelineState, alphaPipelineState, inputLayout, textureDescriptorOffset, samplerDescriptorOffset); + return pImpl + ->CreateEffect(info, opaquePipelineState, alphaPipelineState, inputLayout, textureDescriptorOffset, samplerDescriptorOffset); } - void PBREffectFactory::ReleaseCache() { pImpl->ReleaseCache(); } - // Properties. void PBREffectFactory::SetSharing(bool enabled) noexcept { diff --git a/Src/PlatformHelpers.h b/Src/PlatformHelpers.h index d1696ce3..6817415d 100644 --- a/Src/PlatformHelpers.h +++ b/Src/PlatformHelpers.h @@ -20,11 +20,9 @@ #include #ifndef MAKEFOURCC -#define MAKEFOURCC(ch0, ch1, ch2, ch3) \ - (static_cast(static_cast(ch0)) \ - | (static_cast(static_cast(ch1)) << 8) \ - | (static_cast(static_cast(ch2)) << 16) \ - | (static_cast(static_cast(ch3)) << 24)) +#define MAKEFOURCC(ch0, ch1, ch2, ch3) \ + (static_cast(static_cast(ch0)) | (static_cast(static_cast(ch1)) << 8) \ + | (static_cast(static_cast(ch2)) << 16) | (static_cast(static_cast(ch3)) << 24)) #endif /* defined(MAKEFOURCC) */ // See https://walbourn.github.io/modern-c++-bitmask-types/ @@ -42,22 +40,20 @@ namespace DirectX class com_exception : public std::exception { public: - explicit com_exception(HRESULT hr) : result(hr) + explicit com_exception(HRESULT hr) + : result(hr) { char str[64] = {}; sprintf_s(str, "Failure with HRESULT of %08X", static_cast(result)); message = str; } - const char* what() const noexcept override - { - return message.c_str(); - } + const char* what() const noexcept override { return message.c_str(); } HRESULT get_result() const noexcept { return result; } private: - HRESULT result; + HRESULT result; std::string message; }; @@ -70,11 +66,10 @@ namespace DirectX } } - // Helper for output debug tracing inline void DebugTrace(_In_z_ _Printf_format_string_ const char* format, ...) noexcept { - #ifdef _DEBUG +#ifdef _DEBUG va_list args; va_start(args, format); @@ -82,19 +77,37 @@ namespace DirectX vsprintf_s(buff, format, args); OutputDebugStringA(buff); va_end(args); - #else +#else UNREFERENCED_PARAMETER(format); - #endif +#endif } // Helper smart-pointers -#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) || (defined(_XBOX_ONE) && defined(_TITLE)) || !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) - struct virtual_deleter { void operator()(void* p) noexcept { if (p) VirtualFree(p, 0, MEM_RELEASE); } }; +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) || (defined(_XBOX_ONE) && defined(_TITLE)) || !defined(WINAPI_FAMILY) \ + || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) + struct virtual_deleter + { + void operator()(void* p) noexcept + { + if (p) + VirtualFree(p, 0, MEM_RELEASE); + } + }; #endif - struct handle_closer { void operator()(HANDLE h) noexcept { if (h) CloseHandle(h); } }; + struct handle_closer + { + void operator()(HANDLE h) noexcept + { + if (h) + CloseHandle(h); + } + }; using ScopedHandle = std::unique_ptr; - inline HANDLE safe_handle(HANDLE h) noexcept { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; } -} + inline HANDLE safe_handle(HANDLE h) noexcept + { + return (h == INVALID_HANDLE_VALUE) ? nullptr : h; + } +} // namespace DirectX diff --git a/Src/PrimitiveBatch.cpp b/Src/PrimitiveBatch.cpp index 5a140c9f..e8d97305 100644 --- a/Src/PrimitiveBatch.cpp +++ b/Src/PrimitiveBatch.cpp @@ -17,23 +17,27 @@ using namespace DirectX; using namespace DirectX::DX12::Private; using Microsoft::WRL::ComPtr; - // Internal PrimitiveBatch implementation class. class PrimitiveBatchBase::Impl { public: Impl(_In_ ID3D12Device* device, size_t maxIndices, size_t maxVertices, size_t vertexSize); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; void Begin(_In_ ID3D12GraphicsCommandList* cmdList); void End(); - void Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isIndexed, _In_opt_count_(indexCount) uint16_t const* indices, size_t indexCount, size_t vertexCount, _Outptr_ void** pMappedVertices); + void Draw(D3D_PRIMITIVE_TOPOLOGY topology, + bool isIndexed, + _In_opt_count_(indexCount) uint16_t const* indices, + size_t indexCount, + size_t vertexCount, + _Outptr_ void** pMappedVertices); private: void FlushBatch(); @@ -41,7 +45,7 @@ class PrimitiveBatchBase::Impl GraphicsResource mVertexSegment; GraphicsResource mIndexSegment; - ComPtr mDevice; + ComPtr mDevice; ComPtr mCommandList; size_t mMaxIndices; @@ -51,8 +55,8 @@ class PrimitiveBatchBase::Impl size_t mIndexPageSize; D3D_PRIMITIVE_TOPOLOGY mCurrentTopology; - bool mInBeginEndPair; - bool mCurrentlyIndexed; + bool mInBeginEndPair; + bool mCurrentlyIndexed; size_t mIndexCount; size_t mVertexCount; @@ -61,23 +65,22 @@ class PrimitiveBatchBase::Impl size_t mBaseVertex; }; - // Constructor. PrimitiveBatchBase::Impl::Impl(_In_ ID3D12Device* device, size_t maxIndices, size_t maxVertices, size_t vertexSize) : mDevice(device), - mCommandList(nullptr), - mMaxIndices(maxIndices), - mMaxVertices(maxVertices), - mVertexSize(vertexSize), - mVertexPageSize(maxVertices * vertexSize), - mIndexPageSize(maxIndices * sizeof(uint16_t)), - mCurrentTopology(D3D_PRIMITIVE_TOPOLOGY_UNDEFINED), - mInBeginEndPair(false), - mCurrentlyIndexed(false), - mIndexCount(0), - mVertexCount(0), - mBaseIndex(0), - mBaseVertex(0) + mCommandList(nullptr), + mMaxIndices(maxIndices), + mMaxVertices(maxVertices), + mVertexSize(vertexSize), + mVertexPageSize(maxVertices * vertexSize), + mIndexPageSize(maxIndices * sizeof(uint16_t)), + mCurrentTopology(D3D_PRIMITIVE_TOPOLOGY_UNDEFINED), + mInBeginEndPair(false), + mCurrentlyIndexed(false), + mIndexCount(0), + mVertexCount(0), + mBaseIndex(0), + mBaseVertex(0) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -95,7 +98,6 @@ PrimitiveBatchBase::Impl::Impl(_In_ ID3D12Device* device, size_t maxIndices, siz throw std::invalid_argument("VB too large for DirectX 12"); } - // Begins a batch of primitive drawing operations. void PrimitiveBatchBase::Impl::Begin(_In_ ID3D12GraphicsCommandList* cmdList) @@ -103,11 +105,10 @@ void PrimitiveBatchBase::Impl::Begin(_In_ ID3D12GraphicsCommandList* cmdList) if (mInBeginEndPair) throw std::logic_error("Cannot nest Begin calls"); - mCommandList = cmdList; + mCommandList = cmdList; mInBeginEndPair = true; } - // Ends a batch of primitive drawing operations. void PrimitiveBatchBase::Impl::End() { @@ -123,7 +124,6 @@ void PrimitiveBatchBase::Impl::End() mInBeginEndPair = false; } - // Can we combine adjacent primitives using this topology into a single draw call? static bool CanBatchPrimitives(D3D_PRIMITIVE_TOPOLOGY topology) noexcept { @@ -144,10 +144,13 @@ static bool CanBatchPrimitives(D3D_PRIMITIVE_TOPOLOGY topology) noexcept // but that's not always a perf win, so let's keep things simple. } - // Adds new geometry to the batch. -_Use_decl_annotations_ -void PrimitiveBatchBase::Impl::Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isIndexed, uint16_t const* indices, size_t indexCount, size_t vertexCount, void** pMappedVertices) +_Use_decl_annotations_ void PrimitiveBatchBase::Impl::Draw(D3D_PRIMITIVE_TOPOLOGY topology, + bool isIndexed, + uint16_t const* indices, + size_t indexCount, + size_t vertexCount, + void** pMappedVertices) { if (isIndexed && !indices) throw std::invalid_argument("Indices cannot be null"); @@ -164,13 +167,11 @@ void PrimitiveBatchBase::Impl::Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isInde assert(pMappedVertices != nullptr); // Can we merge this primitive in with an existing batch, or must we flush first? - const bool wrapIndexBuffer = (mIndexCount + indexCount > mMaxIndices); + const bool wrapIndexBuffer = (mIndexCount + indexCount > mMaxIndices); const bool wrapVertexBuffer = (mVertexCount + vertexCount > mMaxVertices); - if ((topology != mCurrentTopology) || - (isIndexed != mCurrentlyIndexed) || - !CanBatchPrimitives(topology) || - wrapIndexBuffer || wrapVertexBuffer) + if ((topology != mCurrentTopology) || (isIndexed != mCurrentlyIndexed) || !CanBatchPrimitives(topology) || wrapIndexBuffer + || wrapVertexBuffer) { FlushBatch(); } @@ -178,11 +179,11 @@ void PrimitiveBatchBase::Impl::Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isInde // If we are not already in a batch, lock the buffers. if (mCurrentTopology == D3D_PRIMITIVE_TOPOLOGY_UNDEFINED) { - mIndexCount = 0; - mVertexCount = 0; - mBaseIndex = 0; - mBaseVertex = 0; - mCurrentTopology = topology; + mIndexCount = 0; + mVertexCount = 0; + mBaseIndex = 0; + mBaseVertex = 0; + mCurrentTopology = topology; mCurrentlyIndexed = isIndexed; // Allocate a page for the primitive data @@ -213,7 +214,6 @@ void PrimitiveBatchBase::Impl::Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isInde mVertexCount += vertexCount; } - // Sends queued primitives to the graphics device. void PrimitiveBatchBase::Impl::FlushBatch() { @@ -226,8 +226,8 @@ void PrimitiveBatchBase::Impl::FlushBatch() // Set the vertex buffer view D3D12_VERTEX_BUFFER_VIEW vbv; vbv.BufferLocation = mVertexSegment.GpuAddress(); - vbv.SizeInBytes = static_cast(mVertexSize * (mVertexCount - mBaseVertex)); - vbv.StrideInBytes = static_cast(mVertexSize); + vbv.SizeInBytes = static_cast(mVertexSize * (mVertexCount - mBaseVertex)); + vbv.StrideInBytes = static_cast(mVertexSize); mCommandList->IASetVertexBuffers(0, 1, &vbv); if (mCurrentlyIndexed) @@ -235,8 +235,8 @@ void PrimitiveBatchBase::Impl::FlushBatch() // Set the index buffer view D3D12_INDEX_BUFFER_VIEW ibv; ibv.BufferLocation = mIndexSegment.GpuAddress(); - ibv.Format = DXGI_FORMAT_R16_UINT; - ibv.SizeInBytes = static_cast(mIndexCount - mBaseIndex) * sizeof(uint16_t); + ibv.Format = DXGI_FORMAT_R16_UINT; + ibv.SizeInBytes = static_cast(mIndexCount - mBaseIndex) * sizeof(uint16_t); mCommandList->IASetIndexBuffer(&ibv); // Draw indexed geometry. @@ -251,32 +251,31 @@ void PrimitiveBatchBase::Impl::FlushBatch() mCurrentTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; } - // Public constructor. PrimitiveBatchBase::PrimitiveBatchBase(_In_ ID3D12Device* device, size_t maxIndices, size_t maxVertices, size_t vertexSize) : pImpl(std::make_unique(device, maxIndices, maxVertices, vertexSize)) {} - -PrimitiveBatchBase::PrimitiveBatchBase(PrimitiveBatchBase&&) noexcept = default; -PrimitiveBatchBase& PrimitiveBatchBase::operator= (PrimitiveBatchBase&&) noexcept = default; -PrimitiveBatchBase::~PrimitiveBatchBase() = default; - +PrimitiveBatchBase::PrimitiveBatchBase(PrimitiveBatchBase&&) noexcept = default; +PrimitiveBatchBase& PrimitiveBatchBase::operator=(PrimitiveBatchBase&&) noexcept = default; +PrimitiveBatchBase::~PrimitiveBatchBase() = default; void PrimitiveBatchBase::Begin(_In_ ID3D12GraphicsCommandList* cmdList) { pImpl->Begin(cmdList); } - void PrimitiveBatchBase::End() { pImpl->End(); } - -_Use_decl_annotations_ -void PrimitiveBatchBase::Draw(D3D12_PRIMITIVE_TOPOLOGY topology, bool isIndexed, uint16_t const* indices, size_t indexCount, size_t vertexCount, void** pMappedVertices) +_Use_decl_annotations_ void PrimitiveBatchBase::Draw(D3D12_PRIMITIVE_TOPOLOGY topology, + bool isIndexed, + uint16_t const* indices, + size_t indexCount, + size_t vertexCount, + void** pMappedVertices) { pImpl->Draw(topology, isIndexed, indices, indexCount, vertexCount, pMappedVertices); } diff --git a/Src/ResourceUploadBatch.cpp b/Src/ResourceUploadBatch.cpp index 308b291f..26b4c28b 100644 --- a/Src/ResourceUploadBatch.cpp +++ b/Src/ResourceUploadBatch.cpp @@ -99,8 +99,7 @@ namespace } return false; - default: - return false; + default: return false; } } @@ -111,10 +110,8 @@ namespace case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: - return true; - default: - return false; + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return true; + default: return false; } } @@ -124,10 +121,8 @@ namespace { case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: - return true; - default: - return false; + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return true; + default: return false; } } @@ -137,64 +132,53 @@ namespace { case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_UINT: - case DXGI_FORMAT_R32G32B32A32_SINT: - return DXGI_FORMAT_R32G32B32A32_TYPELESS; + case DXGI_FORMAT_R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_TYPELESS; case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SNORM: - case DXGI_FORMAT_R16G16B16A16_SINT: - return DXGI_FORMAT_R16G16B16A16_TYPELESS; + case DXGI_FORMAT_R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_TYPELESS; case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_UINT: - case DXGI_FORMAT_R32G32_SINT: - return DXGI_FORMAT_R32G32_TYPELESS; + case DXGI_FORMAT_R32G32_SINT: return DXGI_FORMAT_R32G32_TYPELESS; case DXGI_FORMAT_R10G10B10A2_UNORM: - case DXGI_FORMAT_R10G10B10A2_UINT: - return DXGI_FORMAT_R10G10B10A2_TYPELESS; + case DXGI_FORMAT_R10G10B10A2_UINT: return DXGI_FORMAT_R10G10B10A2_TYPELESS; case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: - case DXGI_FORMAT_R8G8B8A8_SINT: - return DXGI_FORMAT_R8G8B8A8_TYPELESS; + case DXGI_FORMAT_R8G8B8A8_SINT: return DXGI_FORMAT_R8G8B8A8_TYPELESS; case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: - case DXGI_FORMAT_R16G16_SINT: - return DXGI_FORMAT_R16G16_TYPELESS; + case DXGI_FORMAT_R16G16_SINT: return DXGI_FORMAT_R16G16_TYPELESS; case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: - case DXGI_FORMAT_R32_SINT: - return DXGI_FORMAT_R32_TYPELESS; + case DXGI_FORMAT_R32_SINT: return DXGI_FORMAT_R32_TYPELESS; case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_UINT: case DXGI_FORMAT_R8G8_SNORM: - case DXGI_FORMAT_R8G8_SINT: - return DXGI_FORMAT_R8G8_TYPELESS; + case DXGI_FORMAT_R8G8_SINT: return DXGI_FORMAT_R8G8_TYPELESS; case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SNORM: - case DXGI_FORMAT_R16_SINT: - return DXGI_FORMAT_R16_TYPELESS; + case DXGI_FORMAT_R16_SINT: return DXGI_FORMAT_R16_TYPELESS; case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: case DXGI_FORMAT_R8_SNORM: - case DXGI_FORMAT_R8_SINT: - return DXGI_FORMAT_R8_TYPELESS; + case DXGI_FORMAT_R8_SINT: return DXGI_FORMAT_R8_TYPELESS; - default: - return format; + default: return format; } } @@ -209,50 +193,44 @@ namespace RootParameterCount }; - #pragma pack(push, 4) +#pragma pack(push, 4) struct ConstantData { XMFLOAT2 InvOutTexelSize; uint32_t SrcMipIndex; }; - #pragma pack(pop) +#pragma pack(pop) static constexpr uint32_t Num32BitConstants = static_cast(sizeof(ConstantData) / sizeof(uint32_t)); - static constexpr uint32_t ThreadGroupSize = 8; + static constexpr uint32_t ThreadGroupSize = 8; ComPtr rootSignature; ComPtr generateMipsPSO; - GenerateMipsResources( - _In_ ID3D12Device* device) + GenerateMipsResources(_In_ ID3D12Device* device) { - rootSignature = CreateGenMipsRootSignature(device); + rootSignature = CreateGenMipsRootSignature(device); generateMipsPSO = CreateGenMipsPipelineState(device, rootSignature.Get(), GenerateMips_main, sizeof(GenerateMips_main)); } - GenerateMipsResources(const GenerateMipsResources&) = delete; + GenerateMipsResources(const GenerateMipsResources&) = delete; GenerateMipsResources& operator=(const GenerateMipsResources&) = delete; - GenerateMipsResources(GenerateMipsResources&&) = default; + GenerateMipsResources(GenerateMipsResources&&) = default; GenerateMipsResources& operator=(GenerateMipsResources&&) = default; private: - static ComPtr CreateGenMipsRootSignature( - _In_ ID3D12Device* device) + static ComPtr CreateGenMipsRootSignature(_In_ ID3D12Device* device) { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif - | D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; - - const CD3DX12_STATIC_SAMPLER_DESC sampler( - 0, // register + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif + | D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; + + const CD3DX12_STATIC_SAMPLER_DESC sampler(0, // register D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -277,16 +255,15 @@ namespace return rootSignature; } - static ComPtr CreateGenMipsPipelineState( - _In_ ID3D12Device* device, - _In_ ID3D12RootSignature* rootSignature, - _In_reads_(bytecodeSize) const uint8_t* bytecode, - _In_ size_t bytecodeSize) + static ComPtr CreateGenMipsPipelineState(_In_ ID3D12Device* device, + _In_ ID3D12RootSignature* rootSignature, + _In_reads_(bytecodeSize) const uint8_t* bytecode, + _In_ size_t bytecodeSize) { D3D12_COMPUTE_PIPELINE_STATE_DESC desc = {}; - desc.CS.BytecodeLength = bytecodeSize; - desc.CS.pShaderBytecode = bytecode; - desc.pRootSignature = rootSignature; + desc.CS.BytecodeLength = bytecodeSize; + desc.CS.pShaderBytecode = bytecode; + desc.pRootSignature = rootSignature; ComPtr pso; ThrowIfFailed(device->CreateComputePipelineState(&desc, IID_GRAPHICS_PPV_ARGS(pso.GetAddressOf()))); @@ -301,32 +278,28 @@ namespace class ResourceUploadBatch::Impl { public: - Impl( - _In_ ID3D12Device* device) - : mDevice(device) - , mCommandType(D3D12_COMMAND_LIST_TYPE_DIRECT) - , mInBeginEndBlock(false) - , mTypedUAVLoadAdditionalFormats(false) - , mStandardSwizzle64KBSupported(false) + Impl(_In_ ID3D12Device* device) + : mDevice(device), + mCommandType(D3D12_COMMAND_LIST_TYPE_DIRECT), + mInBeginEndBlock(false), + mTypedUAVLoadAdditionalFormats(false), + mStandardSwizzle64KBSupported(false) { if (!device) throw std::invalid_argument("Direct3D device is null"); D3D12_FEATURE_DATA_D3D12_OPTIONS options = {}; - if (SUCCEEDED(device->CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS, - &options, - sizeof(options)))) + if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) { mTypedUAVLoadAdditionalFormats = options.TypedUAVLoadAdditionalFormats != 0; - mStandardSwizzle64KBSupported = options.StandardSwizzle64KBSupported != 0; + mStandardSwizzle64KBSupported = options.StandardSwizzle64KBSupported != 0; } } - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; // Call this before your multiple calls to Upload. @@ -339,8 +312,7 @@ class ResourceUploadBatch::Impl { case D3D12_COMMAND_LIST_TYPE_DIRECT: case D3D12_COMMAND_LIST_TYPE_COMPUTE: - case D3D12_COMMAND_LIST_TYPE_COPY: - break; + case D3D12_COMMAND_LIST_TYPE_COPY: break; default: DebugTrace("ResourceUploadBatch only supports Direct, Compute, and Copy command queues\n"); @@ -351,21 +323,21 @@ class ResourceUploadBatch::Impl SetDebugObjectName(mCmdAlloc.Get(), L"ResourceUploadBatch"); - ThrowIfFailed(mDevice->CreateCommandList(1, commandType, mCmdAlloc.Get(), nullptr, IID_GRAPHICS_PPV_ARGS(mList.ReleaseAndGetAddressOf()))); + ThrowIfFailed( + mDevice->CreateCommandList(1, commandType, mCmdAlloc.Get(), nullptr, IID_GRAPHICS_PPV_ARGS(mList.ReleaseAndGetAddressOf()))); SetDebugObjectName(mList.Get(), L"ResourceUploadBatch"); - mCommandType = commandType; + mCommandType = commandType; mInBeginEndBlock = true; } // Asynchronously uploads a resource. The memory in subRes is copied. // The resource must be in the COPY_DEST or COMMON state. - void Upload( - _In_ ID3D12Resource* resource, - uint32_t subresourceIndexStart, + void Upload(_In_ ID3D12Resource* resource, + uint32_t subresourceIndexStart, _In_reads_(numSubresources) const D3D12_SUBRESOURCE_DATA* subRes, - uint32_t numSubresources) + uint32_t numSubresources) { if (!mInBeginEndBlock) throw std::logic_error("Can't call Upload on a closed ResourceUploadBatch."); @@ -373,18 +345,14 @@ class ResourceUploadBatch::Impl if (!resource || !subRes || !numSubresources) throw std::invalid_argument("Resource/subresource are null"); - const UINT64 uploadSize = GetRequiredIntermediateSize( - resource, - subresourceIndexStart, - numSubresources); + const UINT64 uploadSize = GetRequiredIntermediateSize(resource, subresourceIndexStart, numSubresources); const CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_UPLOAD); - const auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(uploadSize); + const auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(uploadSize); // Create a temporary buffer ComPtr scratchResource = nullptr; - ThrowIfFailed(mDevice->CreateCommittedResource( - &heapProps, + ThrowIfFailed(mDevice->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &resDesc, D3D12_RESOURCE_STATE_GENERIC_READ, @@ -394,22 +362,25 @@ class ResourceUploadBatch::Impl SetDebugObjectName(scratchResource.Get(), L"ResourceUploadBatch Temporary"); // Submit resource copy to command list - UpdateSubresources(mList.Get(), resource, scratchResource.Get(), 0, subresourceIndexStart, numSubresources, - #if defined(_XBOX_ONE) && defined(_TITLE) - // Workaround for header constness issue + UpdateSubresources(mList.Get(), + resource, + scratchResource.Get(), + 0, + subresourceIndexStart, + numSubresources, +#if defined(_XBOX_ONE) && defined(_TITLE) + // Workaround for header constness issue const_cast(subRes) - #else +#else subRes - #endif +#endif ); // Remember this upload object for delayed release mTrackedObjects.push_back(scratchResource); } - void Upload( - _In_ ID3D12Resource* resource, - const SharedGraphicsResource& buffer) + void Upload(_In_ ID3D12Resource* resource, const SharedGraphicsResource& buffer) { if (!mInBeginEndBlock) throw std::logic_error("Can't call Upload on a closed ResourceUploadBatch."); @@ -440,12 +411,12 @@ class ResourceUploadBatch::Impl throw std::runtime_error("GenerateMips cannot operate on a copy queue"); } - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const auto desc = resource->GetDesc(); - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *resource->GetDesc(&tmpDesc); - #endif + const auto& desc = *resource->GetDesc(&tmpDesc); +#endif if (desc.MipLevels == 1) { @@ -490,12 +461,12 @@ class ResourceUploadBatch::Impl } else if (FormatIsBGR(desc.Format)) { - #if !defined(_GAMING_XBOX) && !(defined(_XBOX_ONE) && defined(_TITLE)) +#if !defined(_GAMING_XBOX) && !(defined(_XBOX_ONE) && defined(_TITLE)) if (!mStandardSwizzle64KBSupported) { throw std::runtime_error("GenerateMips needs StandardSwizzle64KBSupported device support for BGR"); } - #endif +#endif GenerateMips_TexturePathBGR(resource); } @@ -506,10 +477,7 @@ class ResourceUploadBatch::Impl } // Transition a resource once you're done with it - void Transition( - _In_ ID3D12Resource* resource, - _In_ D3D12_RESOURCE_STATES stateBefore, - _In_ D3D12_RESOURCE_STATES stateAfter) + void Transition(_In_ ID3D12Resource* resource, _In_ D3D12_RESOURCE_STATES stateBefore, _In_ D3D12_RESOURCE_STATES stateAfter) { if (!mInBeginEndBlock) throw std::logic_error("Can't call Upload on a closed ResourceUploadBatch."); @@ -522,8 +490,7 @@ class ResourceUploadBatch::Impl switch (stateAfter) { case D3D12_RESOURCE_STATE_COPY_DEST: - case D3D12_RESOURCE_STATE_COPY_SOURCE: - break; + case D3D12_RESOURCE_STATE_COPY_SOURCE: break; default: // Ignore other states for copy queues. @@ -539,8 +506,7 @@ class ResourceUploadBatch::Impl case D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE: case D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT: case D3D12_RESOURCE_STATE_COPY_DEST: - case D3D12_RESOURCE_STATE_COPY_SOURCE: - break; + case D3D12_RESOURCE_STATE_COPY_SOURCE: break; default: // Ignore other states for compute queues. @@ -554,8 +520,7 @@ class ResourceUploadBatch::Impl // Submits all the uploads to the driver. // No more uploads can happen after this call until Begin is called again. // This returns a handle to an event that can be waited on. - std::future End( - _In_ ID3D12CommandQueue* commandQueue) + std::future End(_In_ ID3D12CommandQueue* commandQueue) { if (!mInBeginEndBlock) throw std::logic_error("ResourceUploadBatch already closed."); @@ -582,16 +547,17 @@ class ResourceUploadBatch::Impl ThrowIfFailed(fence->SetEventOnCompletion(1ULL, gpuCompletedEvent)); // Create a packet of data that'll be passed to our waiting upload thread - auto uploadBatch = new UploadBatch(); + auto uploadBatch = new UploadBatch(); uploadBatch->CommandList = mList; - uploadBatch->Fence = fence; + uploadBatch->Fence = fence; uploadBatch->GpuCompleteEvent.reset(gpuCompletedEvent); std::swap(mTrackedObjects, uploadBatch->TrackedObjects); std::swap(mTrackedMemoryResources, uploadBatch->TrackedMemoryResources); // Kick off a thread that waits for the upload to complete on the GPU timeline. // Let the thread run autonomously, but provide a future the user can wait on. - std::future future = std::async(std::launch::async, [uploadBatch]() + std::future future = std::async(std::launch::async, + [uploadBatch]() { // Wait on the GPU-complete notification const DWORD wr = WaitForSingleObject(uploadBatch->GpuCompleteEvent.get(), INFINITE); @@ -599,7 +565,8 @@ class ResourceUploadBatch::Impl { if (wr == WAIT_FAILED) { - throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObject"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), + "WaitForSingleObject"); } else { @@ -613,8 +580,8 @@ class ResourceUploadBatch::Impl delete uploadBatch; }); - // Reset our state - mCommandType = D3D12_COMMAND_LIST_TYPE_DIRECT; + // Reset our state + mCommandType = D3D12_COMMAND_LIST_TYPE_DIRECT; mInBeginEndBlock = false; mList.Reset(); mCmdAlloc.Reset(); @@ -636,13 +603,13 @@ class ResourceUploadBatch::Impl if (FormatIsBGR(format)) { - #if defined(_GAMING_XBOX) || (defined(_XBOX_ONE) && defined(_TITLE)) - // We know the RGB and BGR memory layouts match for Xbox One +#if defined(_GAMING_XBOX) || (defined(_XBOX_ONE) && defined(_TITLE)) + // We know the RGB and BGR memory layouts match for Xbox One return true; - #else - // BGR path requires DXGI_FORMAT_R8G8B8A8_UNORM support for UAV load/store plus matching layouts +#else + // BGR path requires DXGI_FORMAT_R8G8B8A8_UNORM support for UAV load/store plus matching layouts return mTypedUAVLoadAdditionalFormats && mStandardSwizzle64KBSupported; - #endif +#endif } if (FormatIsSRGB(format)) @@ -656,22 +623,22 @@ class ResourceUploadBatch::Impl private: // Resource is UAV compatible - void GenerateMips_UnorderedAccessPath( - _In_ ID3D12Resource* resource) + void GenerateMips_UnorderedAccessPath(_In_ ID3D12Resource* resource) { - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const auto desc = resource->GetDesc(); - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *resource->GetDesc(&tmpDesc); - #endif + const auto& desc = *resource->GetDesc(&tmpDesc); +#endif assert(!FormatIsBGR(desc.Format) && !FormatIsSRGB(desc.Format)); const CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT); assert(mCommandType != D3D12_COMMAND_LIST_TYPE_COPY); - const D3D12_RESOURCE_STATES originalState = (mCommandType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + const D3D12_RESOURCE_STATES originalState = (mCommandType == D3D12_COMMAND_LIST_TYPE_COMPUTE) ? + D3D12_RESOURCE_STATE_COPY_DEST : + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; // Create a staging resource if we have to ComPtr staging; @@ -681,8 +648,7 @@ class ResourceUploadBatch::Impl stagingDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; stagingDesc.Format = ConvertSRVtoResourceFormat(desc.Format); - ThrowIfFailed(mDevice->CreateCommittedResource( - &defaultHeapProperties, + ThrowIfFailed(mDevice->CreateCommittedResource(&defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &stagingDesc, D3D12_RESOURCE_STATE_COPY_DEST, @@ -710,10 +676,10 @@ class ResourceUploadBatch::Impl // Create a descriptor heap that holds our resource descriptors ComPtr descriptorHeap; - D3D12_DESCRIPTOR_HEAP_DESC descriptorHeapDesc = {}; - descriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - descriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - descriptorHeapDesc.NumDescriptors = desc.MipLevels; + D3D12_DESCRIPTOR_HEAP_DESC descriptorHeapDesc = {}; + descriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + descriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + descriptorHeapDesc.NumDescriptors = desc.MipLevels; mDevice->CreateDescriptorHeap(&descriptorHeapDesc, IID_GRAPHICS_PPV_ARGS(descriptorHeap.GetAddressOf())); SetDebugObjectName(descriptorHeap.Get(), L"ResourceUploadBatch"); @@ -721,18 +687,18 @@ class ResourceUploadBatch::Impl const auto descriptorSize = static_cast(mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); // Create the top-level SRV - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) CD3DX12_CPU_DESCRIPTOR_HANDLE handleIt(descriptorHeap->GetCPUDescriptorHandleForHeapStart()); - #else +#else CD3DX12_CPU_DESCRIPTOR_HANDLE handleIt; std::ignore = descriptorHeap->GetCPUDescriptorHandleForHeapStart(&handleIt); - #endif +#endif D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; - srvDesc.Format = desc.Format; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Texture2D.MostDetailedMip = 0; - srvDesc.Texture2D.MipLevels = desc.MipLevels; + srvDesc.Format = desc.Format; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Texture2D.MostDetailedMip = 0; + srvDesc.Texture2D.MipLevels = desc.MipLevels; mDevice->CreateShaderResourceView(staging.Get(), &srvDesc, handleIt); @@ -740,9 +706,9 @@ class ResourceUploadBatch::Impl for (uint16_t mip = 1; mip < desc.MipLevels; ++mip) { D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; - uavDesc.Format = desc.Format; - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - uavDesc.Texture2D.MipSlice = mip; + uavDesc.Format = desc.Format; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + uavDesc.Texture2D.MipSlice = mip; handleIt.Offset(descriptorSize); mDevice->CreateUnorderedAccessView(staging.Get(), nullptr, &uavDesc, handleIt); @@ -750,25 +716,25 @@ class ResourceUploadBatch::Impl // Set up UAV barrier (used in loop) D3D12_RESOURCE_BARRIER barrierUAV = {}; - barrierUAV.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - barrierUAV.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrierUAV.UAV.pResource = staging.Get(); + barrierUAV.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrierUAV.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrierUAV.UAV.pResource = staging.Get(); // Barrier for transitioning the subresources to UAVs D3D12_RESOURCE_BARRIER srv2uavDesc = {}; - srv2uavDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - srv2uavDesc.Transition.pResource = staging.Get(); + srv2uavDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + srv2uavDesc.Transition.pResource = staging.Get(); srv2uavDesc.Transition.Subresource = 0; srv2uavDesc.Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - srv2uavDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + srv2uavDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; // Barrier for transitioning the subresources to SRVs D3D12_RESOURCE_BARRIER uav2srvDesc = {}; - uav2srvDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - uav2srvDesc.Transition.pResource = staging.Get(); + uav2srvDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + uav2srvDesc.Transition.pResource = staging.Get(); uav2srvDesc.Transition.Subresource = 0; uav2srvDesc.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - uav2srvDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + uav2srvDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; // based on format, select srgb or not ComPtr pso = mGenMipsResources->generateMipsPSO; @@ -778,23 +744,23 @@ class ResourceUploadBatch::Impl mList->SetPipelineState(pso.Get()); mList->SetDescriptorHeaps(1, descriptorHeap.GetAddressOf()); - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) D3D12_GPU_DESCRIPTOR_HANDLE handle(descriptorHeap->GetGPUDescriptorHandleForHeapStart()); - #else +#else D3D12_GPU_DESCRIPTOR_HANDLE handle; std::ignore = descriptorHeap->GetGPUDescriptorHandleForHeapStart(&handle); - #endif +#endif mList->SetComputeRootDescriptorTable(GenerateMipsResources::SourceTexture, handle); // Get the descriptor handle -- uavH will increment over each loop CD3DX12_GPU_DESCRIPTOR_HANDLE uavH(handle, descriptorSize); // offset by 1 descriptor // Process each mip - auto mipWidth = static_cast(desc.Width); + auto mipWidth = static_cast(desc.Width); uint32_t mipHeight = desc.Height; for (uint32_t mip = 1; mip < desc.MipLevels; ++mip) { - mipWidth = std::max(1, mipWidth >> 1); + mipWidth = std::max(1, mipWidth >> 1); mipHeight = std::max(1, mipHeight >> 1); // Transition the mip to a UAV @@ -806,17 +772,12 @@ class ResourceUploadBatch::Impl // Set constants GenerateMipsResources::ConstantData constants; - constants.SrcMipIndex = mip - 1; + constants.SrcMipIndex = mip - 1; constants.InvOutTexelSize = XMFLOAT2(1 / float(mipWidth), 1 / float(mipHeight)); - mList->SetComputeRoot32BitConstants( - GenerateMipsResources::Constants, - GenerateMipsResources::Num32BitConstants, - &constants, - 0); + mList->SetComputeRoot32BitConstants(GenerateMipsResources::Constants, GenerateMipsResources::Num32BitConstants, &constants, 0); // Process this mip - mList->Dispatch( - (mipWidth + GenerateMipsResources::ThreadGroupSize - 1) / GenerateMipsResources::ThreadGroupSize, + mList->Dispatch((mipWidth + GenerateMipsResources::ThreadGroupSize - 1) / GenerateMipsResources::ThreadGroupSize, (mipHeight + GenerateMipsResources::ThreadGroupSize - 1) / GenerateMipsResources::ThreadGroupSize, 1); @@ -837,13 +798,13 @@ class ResourceUploadBatch::Impl D3D12_RESOURCE_BARRIER barrier[2] = {}; barrier[0].Type = barrier[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier[0].Transition.Subresource = barrier[1].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier[0].Transition.pResource = staging.Get(); - barrier[0].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barrier[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier[0].Transition.pResource = staging.Get(); + barrier[0].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barrier[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - barrier[1].Transition.pResource = resource; + barrier[1].Transition.pResource = resource; barrier[1].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; - barrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + barrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; mList->ResourceBarrier(2, barrier); @@ -868,18 +829,17 @@ class ResourceUploadBatch::Impl } // Resource is not UAV compatible - void GenerateMips_TexturePath( - _In_ ID3D12Resource* resource) + void GenerateMips_TexturePath(_In_ ID3D12Resource* resource) { - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const auto resourceDesc = resource->GetDesc(); - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const auto& resourceDesc = *resource->GetDesc(&tmpDesc); - #endif + const auto& resourceDesc = *resource->GetDesc(&tmpDesc); +#endif assert(!FormatIsBGR(resourceDesc.Format) || FormatIsSRGB(resourceDesc.Format)); - auto copyDesc = resourceDesc; + auto copyDesc = resourceDesc; copyDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; copyDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; @@ -887,8 +847,7 @@ class ResourceUploadBatch::Impl // Create a resource with the same description, but without SRGB, and with UAV flags ComPtr resourceCopy; - ThrowIfFailed(mDevice->CreateCommittedResource( - &heapProperties, + ThrowIfFailed(mDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, ©Desc, D3D12_RESOURCE_STATE_COPY_DEST, @@ -898,8 +857,8 @@ class ResourceUploadBatch::Impl SetDebugObjectName(resourceCopy.Get(), L"GenerateMips Resource Copy"); assert(mCommandType != D3D12_COMMAND_LIST_TYPE_COPY); - const D3D12_RESOURCE_STATES originalState = mCommandType == D3D12_COMMAND_LIST_TYPE_COMPUTE - ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + const D3D12_RESOURCE_STATES originalState + = mCommandType == D3D12_COMMAND_LIST_TYPE_COMPUTE ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; // Copy the top mip of resource data TransitionResource(mList.Get(), resource, originalState, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -917,13 +876,13 @@ class ResourceUploadBatch::Impl D3D12_RESOURCE_BARRIER barrier[2] = {}; barrier[0].Type = barrier[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier[0].Transition.Subresource = barrier[1].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier[0].Transition.pResource = resourceCopy.Get(); - barrier[0].Transition.StateBefore = originalState; - barrier[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier[0].Transition.pResource = resourceCopy.Get(); + barrier[0].Transition.StateBefore = originalState; + barrier[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - barrier[1].Transition.pResource = resource; + barrier[1].Transition.pResource = resource; barrier[1].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; - barrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + barrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; mList->ResourceBarrier(2, barrier); @@ -938,34 +897,33 @@ class ResourceUploadBatch::Impl } // Resource is not UAV compatible (copy via alias to avoid validation failure) - void GenerateMips_TexturePathBGR( - _In_ ID3D12Resource* resource) + void GenerateMips_TexturePathBGR(_In_ ID3D12Resource* resource) { - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const auto resourceDesc = resource->GetDesc(); - #else +#else D3D12_RESOURCE_DESC tmpDesc; - const auto& resourceDesc = *resource->GetDesc(&tmpDesc); - #endif + const auto& resourceDesc = *resource->GetDesc(&tmpDesc); +#endif assert(FormatIsBGR(resourceDesc.Format)); // Create a resource with the same description with RGB and with UAV flags - auto copyDesc = resourceDesc; + auto copyDesc = resourceDesc; copyDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; copyDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - #if !defined(_GAMING_XBOX) && !(defined(_XBOX_ONE) && defined(_TITLE)) +#if !defined(_GAMING_XBOX) && !(defined(_XBOX_ONE) && defined(_TITLE)) copyDesc.Layout = D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE; - #endif +#endif D3D12_HEAP_DESC heapDesc = {}; - #if defined(_MSC_VER) || !defined(_WIN32) +#if defined(_MSC_VER) || !defined(_WIN32) const auto allocInfo = mDevice->GetResourceAllocationInfo(0, 1, ©Desc); - #else +#else D3D12_RESOURCE_ALLOCATION_INFO allocInfo; std::ignore = mDevice->GetResourceAllocationInfo(&allocInfo, 0, 1, ©Desc); - #endif - heapDesc.SizeInBytes = allocInfo.SizeInBytes; - heapDesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES; +#endif + heapDesc.SizeInBytes = allocInfo.SizeInBytes; + heapDesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES; heapDesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; ComPtr heap; @@ -974,8 +932,7 @@ class ResourceUploadBatch::Impl SetDebugObjectName(heap.Get(), L"ResourceUploadBatch"); ComPtr resourceCopy; - ThrowIfFailed(mDevice->CreatePlacedResource( - heap.Get(), + ThrowIfFailed(mDevice->CreatePlacedResource(heap.Get(), 0, ©Desc, D3D12_RESOURCE_STATE_COPY_DEST, @@ -985,14 +942,15 @@ class ResourceUploadBatch::Impl SetDebugObjectName(resourceCopy.Get(), L"GenerateMips Resource Copy"); // Create a BGRA alias - auto aliasDesc = resourceDesc; - aliasDesc.Format = (resourceDesc.Format == DXGI_FORMAT_B8G8R8X8_UNORM || resourceDesc.Format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) ? DXGI_FORMAT_B8G8R8X8_UNORM : DXGI_FORMAT_B8G8R8A8_UNORM; + auto aliasDesc = resourceDesc; + aliasDesc.Format = (resourceDesc.Format == DXGI_FORMAT_B8G8R8X8_UNORM || resourceDesc.Format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) ? + DXGI_FORMAT_B8G8R8X8_UNORM : + DXGI_FORMAT_B8G8R8A8_UNORM; aliasDesc.Layout = copyDesc.Layout; aliasDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; ComPtr aliasCopy; - ThrowIfFailed(mDevice->CreatePlacedResource( - heap.Get(), + ThrowIfFailed(mDevice->CreatePlacedResource(heap.Get(), 0, &aliasDesc, D3D12_RESOURCE_STATE_COPY_DEST, @@ -1002,19 +960,20 @@ class ResourceUploadBatch::Impl SetDebugObjectName(aliasCopy.Get(), L"GenerateMips BGR Alias Copy"); assert(mCommandType != D3D12_COMMAND_LIST_TYPE_COPY); - const D3D12_RESOURCE_STATES originalState = (mCommandType == D3D12_COMMAND_LIST_TYPE_COMPUTE) - ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + const D3D12_RESOURCE_STATES originalState = (mCommandType == D3D12_COMMAND_LIST_TYPE_COMPUTE) ? + D3D12_RESOURCE_STATE_COPY_DEST : + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; // Copy the top mip of the resource data BGR to RGB - D3D12_RESOURCE_BARRIER aliasBarrier[3] = {}; - aliasBarrier[0].Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + D3D12_RESOURCE_BARRIER aliasBarrier[3] = {}; + aliasBarrier[0].Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; aliasBarrier[0].Aliasing.pResourceAfter = aliasCopy.Get(); aliasBarrier[1].Type = aliasBarrier[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; aliasBarrier[1].Transition.Subresource = aliasBarrier[2].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - aliasBarrier[1].Transition.pResource = resource; - aliasBarrier[1].Transition.StateBefore = originalState; - aliasBarrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + aliasBarrier[1].Transition.pResource = resource; + aliasBarrier[1].Transition.StateBefore = originalState; + aliasBarrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; mList->ResourceBarrier(2, aliasBarrier); @@ -1024,26 +983,26 @@ class ResourceUploadBatch::Impl // Generate the mips aliasBarrier[0].Aliasing.pResourceBefore = aliasCopy.Get(); - aliasBarrier[0].Aliasing.pResourceAfter = resourceCopy.Get(); + aliasBarrier[0].Aliasing.pResourceAfter = resourceCopy.Get(); - aliasBarrier[1].Transition.pResource = resourceCopy.Get(); + aliasBarrier[1].Transition.pResource = resourceCopy.Get(); aliasBarrier[1].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; - aliasBarrier[1].Transition.StateAfter = originalState; + aliasBarrier[1].Transition.StateAfter = originalState; mList->ResourceBarrier(2, aliasBarrier); GenerateMips_UnorderedAccessPath(resourceCopy.Get()); // Direct copy back RGB to BGR aliasBarrier[0].Aliasing.pResourceBefore = resourceCopy.Get(); - aliasBarrier[0].Aliasing.pResourceAfter = aliasCopy.Get(); + aliasBarrier[0].Aliasing.pResourceAfter = aliasCopy.Get(); - aliasBarrier[1].Transition.pResource = aliasCopy.Get(); + aliasBarrier[1].Transition.pResource = aliasCopy.Get(); aliasBarrier[1].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; - aliasBarrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + aliasBarrier[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - aliasBarrier[2].Transition.pResource = resource; + aliasBarrier[2].Transition.pResource = resource; aliasBarrier[2].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; - aliasBarrier[2].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + aliasBarrier[2].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; mList->ResourceBarrier(3, aliasBarrier); @@ -1060,92 +1019,72 @@ class ResourceUploadBatch::Impl struct UploadBatch { - std::vector> TrackedObjects; - std::vector TrackedMemoryResources; - ComPtr CommandList; - ComPtr Fence; - ScopedHandle GpuCompleteEvent; + std::vector> TrackedObjects; + std::vector TrackedMemoryResources; + ComPtr CommandList; + ComPtr Fence; + ScopedHandle GpuCompleteEvent; UploadBatch() noexcept {} }; - ComPtr mDevice; - ComPtr mCmdAlloc; - ComPtr mList; - std::unique_ptr mGenMipsResources; + ComPtr mDevice; + ComPtr mCmdAlloc; + ComPtr mList; + std::unique_ptr mGenMipsResources; - std::vector> mTrackedObjects; - std::vector mTrackedMemoryResources; + std::vector> mTrackedObjects; + std::vector mTrackedMemoryResources; - D3D12_COMMAND_LIST_TYPE mCommandType; - bool mInBeginEndBlock; - bool mTypedUAVLoadAdditionalFormats; - bool mStandardSwizzle64KBSupported; + D3D12_COMMAND_LIST_TYPE mCommandType; + bool mInBeginEndBlock; + bool mTypedUAVLoadAdditionalFormats; + bool mStandardSwizzle64KBSupported; }; - - // Public constructor. ResourceUploadBatch::ResourceUploadBatch(_In_ ID3D12Device* device) noexcept(false) : pImpl(std::make_unique(device)) {} - -ResourceUploadBatch::ResourceUploadBatch(ResourceUploadBatch&&) noexcept = default; -ResourceUploadBatch& ResourceUploadBatch::operator= (ResourceUploadBatch&&) noexcept = default; -ResourceUploadBatch::~ResourceUploadBatch() = default; - +ResourceUploadBatch::ResourceUploadBatch(ResourceUploadBatch&&) noexcept = default; +ResourceUploadBatch& ResourceUploadBatch::operator=(ResourceUploadBatch&&) noexcept = default; +ResourceUploadBatch::~ResourceUploadBatch() = default; void ResourceUploadBatch::Begin(D3D12_COMMAND_LIST_TYPE commandType) { pImpl->Begin(commandType); } - -_Use_decl_annotations_ -void ResourceUploadBatch::Upload( - ID3D12Resource* resource, - uint32_t subresourceIndexStart, - const D3D12_SUBRESOURCE_DATA* subRes, - uint32_t numSubresources) +_Use_decl_annotations_ void ResourceUploadBatch::Upload(ID3D12Resource* resource, + uint32_t subresourceIndexStart, + const D3D12_SUBRESOURCE_DATA* subRes, + uint32_t numSubresources) { pImpl->Upload(resource, subresourceIndexStart, subRes, numSubresources); } - -_Use_decl_annotations_ -void ResourceUploadBatch::Upload( - ID3D12Resource* resource, - const SharedGraphicsResource& buffer -) +_Use_decl_annotations_ void ResourceUploadBatch::Upload(ID3D12Resource* resource, const SharedGraphicsResource& buffer) { pImpl->Upload(resource, buffer); } - - void ResourceUploadBatch::GenerateMips(_In_ ID3D12Resource* resource) { pImpl->GenerateMips(resource); } - -_Use_decl_annotations_ -void ResourceUploadBatch::Transition( - ID3D12Resource* resource, - D3D12_RESOURCE_STATES stateBefore, - D3D12_RESOURCE_STATES stateAfter) +_Use_decl_annotations_ void +ResourceUploadBatch::Transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES stateBefore, D3D12_RESOURCE_STATES stateAfter) { pImpl->Transition(resource, stateBefore, stateAfter); } - std::future ResourceUploadBatch::End(_In_ ID3D12CommandQueue* commandQueue) { return pImpl->End(commandQueue); } - bool ResourceUploadBatch::IsSupportedForGenerateMips(DXGI_FORMAT format) noexcept { return pImpl->IsSupportedForGenerateMips(format); diff --git a/Src/SDKMesh.h b/Src/SDKMesh.h index 9f3e766e..db7f7698 100644 --- a/Src/SDKMesh.h +++ b/Src/SDKMesh.h @@ -36,7 +36,6 @@ namespace DXUT // IB data // } - // .SDDKANIM files // SDKANIMATION_FILE_HEADER @@ -49,20 +48,20 @@ namespace DXUT // D3DDECLUSAGE_BLENDINDICES / D3DDECLTYPE_UBYTE4)? // (D3DDECLUSAGE_NORMAL / D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_SHORT4N, D3DDECLTYPE_UBYTE4N, or D3DDECLTYPE_DEC3N)? // (D3DDECLUSAGE_COLOR / D3DDECLTYPE_D3DCOLOR)? - // (D3DDECLUSAGE_TEXCOORD / D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT2 or D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT3 or D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT4 or D3DDECLTYPE_FLOAT16_4)* - // (D3DDECLUSAGE_TANGENT / same as D3DDECLUSAGE_NORMAL)? + // (D3DDECLUSAGE_TEXCOORD / D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT2 or D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT3 or + // D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT4 or D3DDECLTYPE_FLOAT16_4)* (D3DDECLUSAGE_TANGENT / same as D3DDECLUSAGE_NORMAL)? // (D3DDECLUSAGE_BINORMAL / same as D3DDECLUSAGE_NORMAL)? enum D3DDECLUSAGE { - D3DDECLUSAGE_POSITION = 0, - D3DDECLUSAGE_BLENDWEIGHT = 1, + D3DDECLUSAGE_POSITION = 0, + D3DDECLUSAGE_BLENDWEIGHT = 1, D3DDECLUSAGE_BLENDINDICES = 2, - D3DDECLUSAGE_NORMAL = 3, - D3DDECLUSAGE_TEXCOORD = 5, - D3DDECLUSAGE_TANGENT = 6, - D3DDECLUSAGE_BINORMAL = 7, - D3DDECLUSAGE_COLOR = 10, + D3DDECLUSAGE_NORMAL = 3, + D3DDECLUSAGE_TEXCOORD = 5, + D3DDECLUSAGE_TANGENT = 6, + D3DDECLUSAGE_BINORMAL = 7, + D3DDECLUSAGE_COLOR = 10, }; enum D3DDECLTYPE @@ -107,11 +106,11 @@ namespace DXUT // These are extensions for DXGI-based versions of Direct3D D3DDECLTYPE_DXGI_R10G10B10A2_UNORM = 32 + DXGI_FORMAT_R10G10B10A2_UNORM, - D3DDECLTYPE_DXGI_R11G11B10_FLOAT = 32 + DXGI_FORMAT_R11G11B10_FLOAT, - D3DDECLTYPE_DXGI_R8G8B8A8_SNORM = 32 + DXGI_FORMAT_R8G8B8A8_SNORM, + D3DDECLTYPE_DXGI_R11G11B10_FLOAT = 32 + DXGI_FORMAT_R11G11B10_FLOAT, + D3DDECLTYPE_DXGI_R8G8B8A8_SNORM = 32 + DXGI_FORMAT_R8G8B8A8_SNORM, }; -#pragma pack(push,4) +#pragma pack(push, 4) struct D3DVERTEXELEMENT9 { @@ -125,24 +124,24 @@ namespace DXUT #pragma pack(pop) -//-------------------------------------------------------------------------------------- -// Hard Defines for the various structures -//-------------------------------------------------------------------------------------- - constexpr uint32_t SDKMESH_FILE_VERSION = 101; + //-------------------------------------------------------------------------------------- + // Hard Defines for the various structures + //-------------------------------------------------------------------------------------- + constexpr uint32_t SDKMESH_FILE_VERSION = 101; constexpr uint32_t SDKMESH_FILE_VERSION_V2 = 200; - constexpr uint32_t MAX_VERTEX_ELEMENTS = 32; - constexpr uint32_t MAX_VERTEX_STREAMS = 16; - constexpr uint32_t MAX_FRAME_NAME = 100; - constexpr uint32_t MAX_MESH_NAME = 100; - constexpr uint32_t MAX_SUBSET_NAME = 100; - constexpr uint32_t MAX_MATERIAL_NAME = 100; - constexpr uint32_t MAX_TEXTURE_NAME = MAX_PATH; - constexpr uint32_t MAX_MATERIAL_PATH = MAX_PATH; - constexpr uint32_t INVALID_FRAME = uint32_t(-1); - constexpr uint32_t INVALID_MESH = uint32_t(-1); - constexpr uint32_t INVALID_MATERIAL = uint32_t(-1); - constexpr uint32_t INVALID_SUBSET = uint32_t(-1); + constexpr uint32_t MAX_VERTEX_ELEMENTS = 32; + constexpr uint32_t MAX_VERTEX_STREAMS = 16; + constexpr uint32_t MAX_FRAME_NAME = 100; + constexpr uint32_t MAX_MESH_NAME = 100; + constexpr uint32_t MAX_SUBSET_NAME = 100; + constexpr uint32_t MAX_MATERIAL_NAME = 100; + constexpr uint32_t MAX_TEXTURE_NAME = MAX_PATH; + constexpr uint32_t MAX_MATERIAL_PATH = MAX_PATH; + constexpr uint32_t INVALID_FRAME = uint32_t(-1); + constexpr uint32_t INVALID_MESH = uint32_t(-1); + constexpr uint32_t INVALID_MATERIAL = uint32_t(-1); + constexpr uint32_t INVALID_SUBSET = uint32_t(-1); constexpr uint32_t INVALID_ANIMATION_DATA = uint32_t(-1); //-------------------------------------------------------------------------------------- @@ -178,18 +177,18 @@ namespace DXUT //-------------------------------------------------------------------------------------- // Structures. //-------------------------------------------------------------------------------------- -#pragma pack(push,8) +#pragma pack(push, 8) struct SDKMESH_HEADER { - //Basic Info and sizes + // Basic Info and sizes uint32_t Version; uint8_t IsBigEndian; uint64_t HeaderSize; uint64_t NonBufferDataSize; uint64_t BufferDataSize; - //Stats + // Stats uint32_t NumVertexBuffers; uint32_t NumIndexBuffers; uint32_t NumMeshes; @@ -197,7 +196,7 @@ namespace DXUT uint32_t NumFrames; uint32_t NumMaterials; - //Offsets to Data + // Offsets to Data uint64_t VertexStreamHeadersOffset; uint64_t IndexStreamHeadersOffset; uint64_t MeshDataOffset; @@ -208,11 +207,11 @@ namespace DXUT struct SDKMESH_VERTEX_BUFFER_HEADER { - uint64_t NumVertices; - uint64_t SizeBytes; - uint64_t StrideBytes; + uint64_t NumVertices; + uint64_t SizeBytes; + uint64_t StrideBytes; D3DVERTEXELEMENT9 Decl[MAX_VERTEX_ELEMENTS]; - uint64_t DataOffset; + uint64_t DataOffset; }; struct SDKMESH_INDEX_BUFFER_HEADER @@ -225,12 +224,12 @@ namespace DXUT struct SDKMESH_MESH { - char Name[MAX_MESH_NAME]; - uint8_t NumVertexBuffers; + char Name[MAX_MESH_NAME]; + uint8_t NumVertexBuffers; uint32_t VertexBuffers[MAX_VERTEX_STREAMS]; uint32_t IndexBuffer; uint32_t NumSubsets; - uint32_t NumFrameInfluences; //aka bones + uint32_t NumFrameInfluences; // aka bones DirectX::XMFLOAT3 BoundingBoxCenter; DirectX::XMFLOAT3 BoundingBoxExtents; @@ -238,18 +237,18 @@ namespace DXUT union { uint64_t SubsetOffset; - INT* pSubsets; + INT* pSubsets; }; union { - uint64_t FrameInfluenceOffset; + uint64_t FrameInfluenceOffset; uint32_t* pFrameInfluences; }; }; struct SDKMESH_SUBSET { - char Name[MAX_SUBSET_NAME]; + char Name[MAX_SUBSET_NAME]; uint32_t MaterialID; uint32_t PrimitiveType; uint64_t IndexStart; @@ -260,32 +259,32 @@ namespace DXUT struct SDKMESH_FRAME { - char Name[MAX_FRAME_NAME]; - uint32_t Mesh; - uint32_t ParentFrame; - uint32_t ChildFrame; - uint32_t SiblingFrame; + char Name[MAX_FRAME_NAME]; + uint32_t Mesh; + uint32_t ParentFrame; + uint32_t ChildFrame; + uint32_t SiblingFrame; DirectX::XMFLOAT4X4 Matrix; - uint32_t AnimationDataIndex; //Used to index which set of keyframes transforms this frame + uint32_t AnimationDataIndex; // Used to index which set of keyframes transforms this frame }; struct SDKMESH_MATERIAL { - char Name[MAX_MATERIAL_NAME]; + char Name[MAX_MATERIAL_NAME]; // Use MaterialInstancePath - char MaterialInstancePath[MAX_MATERIAL_PATH]; + char MaterialInstancePath[MAX_MATERIAL_PATH]; // Or fall back to d3d8-type materials - char DiffuseTexture[MAX_TEXTURE_NAME]; - char NormalTexture[MAX_TEXTURE_NAME]; - char SpecularTexture[MAX_TEXTURE_NAME]; + char DiffuseTexture[MAX_TEXTURE_NAME]; + char NormalTexture[MAX_TEXTURE_NAME]; + char SpecularTexture[MAX_TEXTURE_NAME]; DirectX::XMFLOAT4 Diffuse; DirectX::XMFLOAT4 Ambient; DirectX::XMFLOAT4 Specular; DirectX::XMFLOAT4 Emissive; - float Power; + float Power; uint64_t Force64_1; uint64_t Force64_2; @@ -297,17 +296,17 @@ namespace DXUT struct SDKMESH_MATERIAL_V2 { - char Name[MAX_MATERIAL_NAME]; + char Name[MAX_MATERIAL_NAME]; // PBR materials - char RMATexture[MAX_TEXTURE_NAME]; - char AlbedoTexture[MAX_TEXTURE_NAME]; - char NormalTexture[MAX_TEXTURE_NAME]; - char EmissiveTexture[MAX_TEXTURE_NAME]; + char RMATexture[MAX_TEXTURE_NAME]; + char AlbedoTexture[MAX_TEXTURE_NAME]; + char NormalTexture[MAX_TEXTURE_NAME]; + char EmissiveTexture[MAX_TEXTURE_NAME]; - float Alpha; + float Alpha; - char Reserved[60]; + char Reserved[60]; uint64_t Force64_1; uint64_t Force64_2; @@ -338,16 +337,16 @@ namespace DXUT struct SDKANIMATION_FRAME_DATA { - char FrameName[MAX_FRAME_NAME]; + char FrameName[MAX_FRAME_NAME]; uint64_t DataOffset; }; #pragma pack(pop) -} // namespace +} // namespace DXUT static_assert(sizeof(DXUT::D3DVERTEXELEMENT9) == 8, "Direct3D9 Decl structure size incorrect"); -static_assert(sizeof(DXUT::SDKMESH_HEADER)== 104, "SDK Mesh structure size incorrect"); +static_assert(sizeof(DXUT::SDKMESH_HEADER) == 104, "SDK Mesh structure size incorrect"); static_assert(sizeof(DXUT::SDKMESH_VERTEX_BUFFER_HEADER) == 288, "SDK Mesh structure size incorrect"); static_assert(sizeof(DXUT::SDKMESH_INDEX_BUFFER_HEADER) == 32, "SDK Mesh structure size incorrect"); static_assert(sizeof(DXUT::SDKMESH_MESH) == 224, "SDK Mesh structure size incorrect"); diff --git a/Src/ScreenGrab.cpp b/Src/ScreenGrab.cpp index e4c5c61c..0f5e2bdf 100644 --- a/Src/ScreenGrab.cpp +++ b/Src/ScreenGrab.cpp @@ -37,13 +37,13 @@ namespace { //-------------------------------------------------------------------------------------- HRESULT CaptureTexture(_In_ ID3D12Device* device, - _In_ ID3D12CommandQueue* pCommandQ, - _In_ ID3D12Resource* pSource, - UINT64 srcPitch, - const D3D12_RESOURCE_DESC& desc, - _COM_Outptr_ ID3D12Resource** pStaging, - D3D12_RESOURCE_STATES beforeState, - D3D12_RESOURCE_STATES afterState) noexcept + _In_ ID3D12CommandQueue* pCommandQ, + _In_ ID3D12Resource* pSource, + UINT64 srcPitch, + const D3D12_RESOURCE_DESC& desc, + _COM_Outptr_ ID3D12Resource** pStaging, + D3D12_RESOURCE_STATES beforeState, + D3D12_RESOURCE_STATES afterState) noexcept { if (pStaging) { @@ -61,7 +61,9 @@ namespace if (desc.DepthOrArraySize > 1 || desc.MipLevels > 1) { - DebugTrace("WARNING: ScreenGrab does not support 2D arrays, cubemaps, or mipmaps; only the first surface is written. Consider using DirectXTex instead.\n"); + DebugTrace( + "WARNING: ScreenGrab does not support 2D arrays, cubemaps, or mipmaps; only the first surface is written. Consider using " + "DirectXTex instead.\n"); } if (srcPitch > UINT32_MAX) @@ -72,7 +74,7 @@ namespace return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); D3D12_HEAP_PROPERTIES sourceHeapProperties; - HRESULT hr = pSource->GetHeapProperties(&sourceHeapProperties, nullptr); + HRESULT hr = pSource->GetHeapProperties(&sourceHeapProperties, nullptr); if (SUCCEEDED(hr) && sourceHeapProperties.Type == D3D12_HEAP_TYPE_READBACK) { // Handle case where the source is already a staging texture we can use directly @@ -91,7 +93,11 @@ namespace // Spin up a new command list ComPtr commandList; - hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAlloc.Get(), nullptr, IID_GRAPHICS_PPV_ARGS(commandList.GetAddressOf())); + hr = device->CreateCommandList(0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + commandAlloc.Get(), + nullptr, + IID_GRAPHICS_PPV_ARGS(commandList.GetAddressOf())); if (FAILED(hr)) return hr; @@ -112,31 +118,30 @@ namespace // Readback resources must be buffers D3D12_RESOURCE_DESC bufferDesc = {}; - bufferDesc.DepthOrArraySize = 1; - bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; - bufferDesc.Format = DXGI_FORMAT_UNKNOWN; - bufferDesc.Height = 1; - bufferDesc.Width = srcPitch * desc.Height; - bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - bufferDesc.MipLevels = 1; - bufferDesc.SampleDesc.Count = 1; + bufferDesc.DepthOrArraySize = 1; + bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; + bufferDesc.Format = DXGI_FORMAT_UNKNOWN; + bufferDesc.Height = 1; + bufferDesc.Width = srcPitch * desc.Height; + bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + bufferDesc.MipLevels = 1; + bufferDesc.SampleDesc.Count = 1; ComPtr copySource(pSource); - D3D12_RESOURCE_STATES beforeStateSource = beforeState; + D3D12_RESOURCE_STATES beforeStateSource = beforeState; if (desc.SampleDesc.Count > 1) { TransitionResource(commandList.Get(), pSource, beforeState, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); // MSAA content must be resolved before being copied to a staging texture - auto descCopy = desc; - descCopy.SampleDesc.Count = 1; + auto descCopy = desc; + descCopy.SampleDesc.Count = 1; descCopy.SampleDesc.Quality = 0; - descCopy.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + descCopy.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; ComPtr pTemp; - hr = device->CreateCommittedResource( - &defaultHeapProperties, + hr = device->CreateCommittedResource(&defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &descCopy, D3D12_RESOURCE_STATE_RESOLVE_DEST, @@ -168,7 +173,7 @@ namespace } } - copySource = pTemp; + copySource = pTemp; beforeState = D3D12_RESOURCE_STATE_RESOLVE_DEST; } else @@ -177,8 +182,7 @@ namespace } // Create a staging texture - hr = device->CreateCommittedResource( - &readBackHeapProperties, + hr = device->CreateCommittedResource(&readBackHeapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_COPY_DEST, @@ -203,11 +207,11 @@ namespace // Get the copy target location D3D12_PLACED_SUBRESOURCE_FOOTPRINT bufferFootprint = {}; - bufferFootprint.Footprint.Width = static_cast(desc.Width); - bufferFootprint.Footprint.Height = desc.Height; - bufferFootprint.Footprint.Depth = 1; - bufferFootprint.Footprint.RowPitch = static_cast(srcPitch); - bufferFootprint.Footprint.Format = desc.Format; + bufferFootprint.Footprint.Width = static_cast(desc.Width); + bufferFootprint.Footprint.Height = desc.Height; + bufferFootprint.Footprint.Depth = 1; + bufferFootprint.Footprint.RowPitch = static_cast(srcPitch); + bufferFootprint.Footprint.Format = desc.Format; const CD3DX12_TEXTURE_COPY_LOCATION copyDest(*pStaging, bufferFootprint); const CD3DX12_TEXTURE_COPY_LOCATION copySrc(copySource.Get(), 0); @@ -246,15 +250,12 @@ namespace } } // anonymous namespace - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::SaveDDSTextureToFile( - ID3D12CommandQueue* pCommandQ, - ID3D12Resource* pSource, - const wchar_t* fileName, - D3D12_RESOURCE_STATES beforeState, - D3D12_RESOURCE_STATES afterState) noexcept +_Use_decl_annotations_ HRESULT DirectX::SaveDDSTextureToFile(ID3D12CommandQueue* pCommandQ, + ID3D12Resource* pSource, + const wchar_t* fileName, + D3D12_RESOURCE_STATES beforeState, + D3D12_RESOURCE_STATES afterState) noexcept { if (!fileName) return E_INVALIDARG; @@ -267,29 +268,22 @@ HRESULT DirectX::SaveDDSTextureToFile( const auto desc = pSource->GetDesc(); #else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *pSource->GetDesc(&tmpDesc); + const auto& desc = *pSource->GetDesc(&tmpDesc); #endif if (desc.Width > UINT32_MAX) return E_INVALIDARG; UINT64 totalResourceSize = 0; - UINT64 fpRowPitch = 0; - UINT fpRowCount = 0; + UINT64 fpRowPitch = 0; + UINT fpRowCount = 0; // Get the rowcount, pitch and size of the top mip - device->GetCopyableFootprints( - &desc, - 0, - 1, - 0, - nullptr, - &fpRowCount, - &fpRowPitch, - &totalResourceSize); + device->GetCopyableFootprints(&desc, 0, 1, 0, nullptr, &fpRowCount, &fpRowPitch, &totalResourceSize); #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) // Round up the srcPitch to multiples of 1024 - const UINT64 dstRowPitch = (fpRowPitch + static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u) & ~(static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u); + const UINT64 dstRowPitch = (fpRowPitch + static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u) + & ~(static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u); #else // Round up the srcPitch to multiples of 256 const UINT64 dstRowPitch = (fpRowPitch + 255) & ~0xFFu; @@ -304,10 +298,7 @@ HRESULT DirectX::SaveDDSTextureToFile( return hr; // Create file - ScopedHandle hFile(safe_handle(CreateFile2( - fileName, - GENERIC_WRITE, 0, CREATE_ALWAYS, - nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); if (!hFile) return HRESULT_FROM_WIN32(GetLastError()); @@ -318,53 +309,87 @@ HRESULT DirectX::SaveDDSTextureToFile( *reinterpret_cast(&fileHeader[0]) = DDS_MAGIC; - auto header = reinterpret_cast(&fileHeader[0] + sizeof(uint32_t)); - size_t headerSize = DDS_MIN_HEADER_SIZE; - header->size = sizeof(DDS_HEADER); - header->flags = DDS_HEADER_FLAGS_TEXTURE | DDS_HEADER_FLAGS_MIPMAP; - header->height = desc.Height; - header->width = static_cast(desc.Width); + auto header = reinterpret_cast(&fileHeader[0] + sizeof(uint32_t)); + size_t headerSize = DDS_MIN_HEADER_SIZE; + header->size = sizeof(DDS_HEADER); + header->flags = DDS_HEADER_FLAGS_TEXTURE | DDS_HEADER_FLAGS_MIPMAP; + header->height = desc.Height; + header->width = static_cast(desc.Width); header->mipMapCount = 1; - header->caps = DDS_SURFACE_FLAGS_TEXTURE; + header->caps = DDS_SURFACE_FLAGS_TEXTURE; // Try to use a legacy .DDS pixel format for better tools support, otherwise fallback to 'DX10' header extension DDS_HEADER_DXT10* extHeader = nullptr; switch (desc.Format) { - case DXGI_FORMAT_R8G8B8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R16G16_UNORM: memcpy(&header->ddspf, &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8_UNORM: memcpy(&header->ddspf, &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R16_UNORM: memcpy(&header->ddspf, &DDSPF_L16, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8_UNORM: memcpy(&header->ddspf, &DDSPF_L8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy(&header->ddspf, &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy(&header->ddspf, &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC1_UNORM: memcpy(&header->ddspf, &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC2_UNORM: memcpy(&header->ddspf, &DDSPF_DXT3, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC3_UNORM: memcpy(&header->ddspf, &DDSPF_DXT5, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC4_UNORM: memcpy(&header->ddspf, &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC4_SNORM: memcpy(&header->ddspf, &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC5_UNORM: memcpy(&header->ddspf, &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC5_SNORM: memcpy(&header->ddspf, &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B5G6R5_UNORM: memcpy(&header->ddspf, &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy(&header->ddspf, &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8_SNORM: memcpy(&header->ddspf, &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy(&header->ddspf, &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R16G16_SNORM: memcpy(&header->ddspf, &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy(&header->ddspf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_YUY2: memcpy(&header->ddspf, &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy(&header->ddspf, &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8B8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_UNORM: memcpy(&header->ddspf, &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_UNORM: memcpy(&header->ddspf, &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16_UNORM: memcpy(&header->ddspf, &DDSPF_L16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8_UNORM: memcpy(&header->ddspf, &DDSPF_L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy(&header->ddspf, &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy(&header->ddspf, &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC1_UNORM: memcpy(&header->ddspf, &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC2_UNORM: memcpy(&header->ddspf, &DDSPF_DXT3, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC3_UNORM: memcpy(&header->ddspf, &DDSPF_DXT5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC4_UNORM: memcpy(&header->ddspf, &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC4_SNORM: memcpy(&header->ddspf, &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC5_UNORM: memcpy(&header->ddspf, &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC5_SNORM: memcpy(&header->ddspf, &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G6R5_UNORM: memcpy(&header->ddspf, &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy(&header->ddspf, &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_SNORM: memcpy(&header->ddspf, &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy(&header->ddspf, &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_SNORM: memcpy(&header->ddspf, &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy(&header->ddspf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_YUY2: memcpy(&header->ddspf, &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B4G4R4A4_UNORM: + memcpy(&header->ddspf, &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); + break; // Legacy D3DX formats using D3DFMT enum value as FourCC - case DXGI_FORMAT_R32G32B32A32_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 116; break; // D3DFMT_A32B32G32R32F - case DXGI_FORMAT_R16G16B16A16_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 113; break; // D3DFMT_A16B16G16R16F - case DXGI_FORMAT_R16G16B16A16_UNORM: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 36; break; // D3DFMT_A16B16G16R16 - case DXGI_FORMAT_R16G16B16A16_SNORM: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 110; break; // D3DFMT_Q16W16V16U16 - case DXGI_FORMAT_R32G32_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 115; break; // D3DFMT_G32R32F - case DXGI_FORMAT_R16G16_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 112; break; // D3DFMT_G16R16F - case DXGI_FORMAT_R32_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 114; break; // D3DFMT_R32F - case DXGI_FORMAT_R16_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 111; break; // D3DFMT_R16F + case DXGI_FORMAT_R32G32B32A32_FLOAT: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 116; + break; // D3DFMT_A32B32G32R32F + case DXGI_FORMAT_R16G16B16A16_FLOAT: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 113; + break; // D3DFMT_A16B16G16R16F + case DXGI_FORMAT_R16G16B16A16_UNORM: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 36; + break; // D3DFMT_A16B16G16R16 + case DXGI_FORMAT_R16G16B16A16_SNORM: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 110; + break; // D3DFMT_Q16W16V16U16 + case DXGI_FORMAT_R32G32_FLOAT: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 115; + break; // D3DFMT_G32R32F + case DXGI_FORMAT_R16G16_FLOAT: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 112; + break; // D3DFMT_G16R16F + case DXGI_FORMAT_R32_FLOAT: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 114; + break; // D3DFMT_R32F + case DXGI_FORMAT_R16_FLOAT: + header->ddspf.size = sizeof(DDS_PIXELFORMAT); + header->ddspf.flags = DDS_FOURCC; + header->ddspf.fourCC = 111; + break; // D3DFMT_R16F case DXGI_FORMAT_AI44: case DXGI_FORMAT_IA44: @@ -377,10 +402,10 @@ HRESULT DirectX::SaveDDSTextureToFile( memcpy(&header->ddspf, &DDSPF_DX10, sizeof(DDS_PIXELFORMAT)); headerSize += sizeof(DDS_HEADER_DXT10); - extHeader = reinterpret_cast(fileHeader + DDS_MIN_HEADER_SIZE); - extHeader->dxgiFormat = desc.Format; + extHeader = reinterpret_cast(fileHeader + DDS_MIN_HEADER_SIZE); + extHeader->dxgiFormat = desc.Format; extHeader->resourceDimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - extHeader->arraySize = 1; + extHeader->arraySize = 1; break; } @@ -415,10 +440,10 @@ HRESULT DirectX::SaveDDSTextureToFile( if (imageSize > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); - void* pMappedMemory = nullptr; - D3D12_RANGE readRange = { 0, static_cast(imageSize) }; - D3D12_RANGE writeRange = { 0, 0 }; - hr = pStaging->Map(0, &readRange, &pMappedMemory); + void* pMappedMemory = nullptr; + D3D12_RANGE readRange = { 0, static_cast(imageSize) }; + D3D12_RANGE writeRange = { 0, 0 }; + hr = pStaging->Map(0, &readRange, &pMappedMemory); if (FAILED(hr)) return hr; @@ -469,20 +494,18 @@ namespace DirectX { extern IWICImagingFactory2* GetWIC() noexcept; } - } -} - -_Use_decl_annotations_ -HRESULT DirectX::SaveWICTextureToFile( - ID3D12CommandQueue* pCommandQ, - ID3D12Resource* pSource, - REFGUID guidContainerFormat, - const wchar_t* fileName, - D3D12_RESOURCE_STATES beforeState, - D3D12_RESOURCE_STATES afterState, - const GUID* targetFormat, - std::function setCustomProps, - bool forceSRGB) + } // namespace DX12 +} // namespace DirectX + +_Use_decl_annotations_ HRESULT DirectX::SaveWICTextureToFile(ID3D12CommandQueue* pCommandQ, + ID3D12Resource* pSource, + REFGUID guidContainerFormat, + const wchar_t* fileName, + D3D12_RESOURCE_STATES beforeState, + D3D12_RESOURCE_STATES afterState, + const GUID* targetFormat, + std::function setCustomProps, + bool forceSRGB) { using namespace DirectX::DX12::ToolKitInternal; @@ -497,29 +520,22 @@ HRESULT DirectX::SaveWICTextureToFile( const auto desc = pSource->GetDesc(); #else D3D12_RESOURCE_DESC tmpDesc; - const auto& desc = *pSource->GetDesc(&tmpDesc); + const auto& desc = *pSource->GetDesc(&tmpDesc); #endif if (desc.Width > UINT32_MAX) return E_INVALIDARG; UINT64 totalResourceSize = 0; - UINT64 fpRowPitch = 0; - UINT fpRowCount = 0; + UINT64 fpRowPitch = 0; + UINT fpRowCount = 0; // Get the rowcount, pitch and size of the top mip - device->GetCopyableFootprints( - &desc, - 0, - 1, - 0, - nullptr, - &fpRowCount, - &fpRowPitch, - &totalResourceSize); + device->GetCopyableFootprints(&desc, 0, 1, 0, nullptr, &fpRowCount, &fpRowPitch, &totalResourceSize); #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) // Round up the srcPitch to multiples of 1024 - UINT64 dstRowPitch = (fpRowPitch + static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u) & ~(static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u); + UINT64 dstRowPitch = (fpRowPitch + static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u) + & ~(static_cast(D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT) - 1u); #else // Round up the srcPitch to multiples of 256 (D3D12_TEXTURE_DATA_PITCH_ALIGNMENT) const UINT64 dstRowPitch = (fpRowPitch + 255) & ~0xFFu; @@ -535,51 +551,46 @@ HRESULT DirectX::SaveWICTextureToFile( // Determine source format's WIC equivalent WICPixelFormatGUID pfGuid = {}; - bool sRGB = forceSRGB; + bool sRGB = forceSRGB; switch (desc.Format) { - case DXGI_FORMAT_R32G32B32A32_FLOAT: pfGuid = GUID_WICPixelFormat128bppRGBAFloat; break; - case DXGI_FORMAT_R16G16B16A16_FLOAT: pfGuid = GUID_WICPixelFormat64bppRGBAHalf; break; - case DXGI_FORMAT_R16G16B16A16_UNORM: pfGuid = GUID_WICPixelFormat64bppRGBA; break; - case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102XR; break; - case DXGI_FORMAT_R10G10B10A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102; break; - case DXGI_FORMAT_B5G5R5A1_UNORM: pfGuid = GUID_WICPixelFormat16bppBGRA5551; break; - case DXGI_FORMAT_B5G6R5_UNORM: pfGuid = GUID_WICPixelFormat16bppBGR565; break; - case DXGI_FORMAT_R32_FLOAT: pfGuid = GUID_WICPixelFormat32bppGrayFloat; break; - case DXGI_FORMAT_R16_FLOAT: pfGuid = GUID_WICPixelFormat16bppGrayHalf; break; - case DXGI_FORMAT_R16_UNORM: pfGuid = GUID_WICPixelFormat16bppGray; break; - case DXGI_FORMAT_R8_UNORM: pfGuid = GUID_WICPixelFormat8bppGray; break; - case DXGI_FORMAT_A8_UNORM: pfGuid = GUID_WICPixelFormat8bppAlpha; break; - - case DXGI_FORMAT_R8G8B8A8_UNORM: - pfGuid = GUID_WICPixelFormat32bppRGBA; - break; + case DXGI_FORMAT_R32G32B32A32_FLOAT: pfGuid = GUID_WICPixelFormat128bppRGBAFloat; break; + case DXGI_FORMAT_R16G16B16A16_FLOAT: pfGuid = GUID_WICPixelFormat64bppRGBAHalf; break; + case DXGI_FORMAT_R16G16B16A16_UNORM: pfGuid = GUID_WICPixelFormat64bppRGBA; break; + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102XR; break; + case DXGI_FORMAT_R10G10B10A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102; break; + case DXGI_FORMAT_B5G5R5A1_UNORM: pfGuid = GUID_WICPixelFormat16bppBGRA5551; break; + case DXGI_FORMAT_B5G6R5_UNORM: pfGuid = GUID_WICPixelFormat16bppBGR565; break; + case DXGI_FORMAT_R32_FLOAT: pfGuid = GUID_WICPixelFormat32bppGrayFloat; break; + case DXGI_FORMAT_R16_FLOAT: pfGuid = GUID_WICPixelFormat16bppGrayHalf; break; + case DXGI_FORMAT_R16_UNORM: pfGuid = GUID_WICPixelFormat16bppGray; break; + case DXGI_FORMAT_R8_UNORM: pfGuid = GUID_WICPixelFormat8bppGray; break; + case DXGI_FORMAT_A8_UNORM: pfGuid = GUID_WICPixelFormat8bppAlpha; break; + + case DXGI_FORMAT_R8G8B8A8_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA; break; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: pfGuid = GUID_WICPixelFormat32bppRGBA; - sRGB = true; + sRGB = true; break; - case DXGI_FORMAT_B8G8R8A8_UNORM: - pfGuid = GUID_WICPixelFormat32bppBGRA; - break; + case DXGI_FORMAT_B8G8R8A8_UNORM: pfGuid = GUID_WICPixelFormat32bppBGRA; break; case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: pfGuid = GUID_WICPixelFormat32bppBGRA; - sRGB = true; + sRGB = true; break; - case DXGI_FORMAT_B8G8R8X8_UNORM: - pfGuid = GUID_WICPixelFormat32bppBGR; - break; + case DXGI_FORMAT_B8G8R8X8_UNORM: pfGuid = GUID_WICPixelFormat32bppBGR; break; case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: pfGuid = GUID_WICPixelFormat32bppBGR; - sRGB = true; + sRGB = true; break; default: - DebugTrace("ERROR: ScreenGrab does not support all DXGI formats (%u). Consider using DirectXTex.\n", static_cast(desc.Format)); + DebugTrace("ERROR: ScreenGrab does not support all DXGI formats (%u). Consider using DirectXTex.\n", + static_cast(desc.Format)); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } @@ -608,7 +619,7 @@ HRESULT DirectX::SaveWICTextureToFile( return hr; ComPtr frame; - ComPtr props; + ComPtr props; hr = encoder->CreateNewFrame(frame.GetAddressOf(), props.GetAddressOf()); if (FAILED(hr)) return hr; @@ -620,9 +631,9 @@ HRESULT DirectX::SaveWICTextureToFile( option.pstrName = const_cast(L"EnableV5Header32bppBGRA"); VARIANT varValue; - varValue.vt = VT_BOOL; + varValue.vt = VT_BOOL; varValue.boolVal = VARIANT_TRUE; - std::ignore = props->Write(1, &option, &varValue); + std::ignore = props->Write(1, &option, &varValue); } if (setCustomProps) @@ -666,13 +677,9 @@ HRESULT DirectX::SaveWICTextureToFile( case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R8_UNORM: - case DXGI_FORMAT_A8_UNORM: - targetGuid = GUID_WICPixelFormat8bppGray; - break; + case DXGI_FORMAT_A8_UNORM: targetGuid = GUID_WICPixelFormat8bppGray; break; - default: - targetGuid = GUID_WICPixelFormat24bppBGR; - break; + default: targetGuid = GUID_WICPixelFormat24bppBGR; break; } } @@ -693,7 +700,7 @@ HRESULT DirectX::SaveWICTextureToFile( PROPVARIANT value; PropVariantInit(&value); - value.vt = VT_LPSTR; + value.vt = VT_LPSTR; value.pszVal = const_cast("DirectXTK"); if (memcmp(&guidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID)) == 0) @@ -704,22 +711,22 @@ HRESULT DirectX::SaveWICTextureToFile( // Set sRGB chunk if (sRGB) { - value.vt = VT_UI1; - value.bVal = 0; + value.vt = VT_UI1; + value.bVal = 0; std::ignore = metawriter->SetMetadataByName(L"/sRGB/RenderingIntent", &value); } else { // add gAMA chunk with gamma 1.0 - value.vt = VT_UI4; + value.vt = VT_UI4; value.uintVal = 100000; // gama value * 100,000 -- i.e. gamma 1.0 - std::ignore = metawriter->SetMetadataByName(L"/gAMA/ImageGamma", &value); + std::ignore = metawriter->SetMetadataByName(L"/gAMA/ImageGamma", &value); // remove sRGB chunk which is added by default. std::ignore = metawriter->RemoveMetadataByName(L"/sRGB/RenderingIntent"); } } - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) else if (memcmp(&guidContainerFormat, &GUID_ContainerFormatJpeg, sizeof(GUID)) == 0) { // Set Software name @@ -728,7 +735,7 @@ HRESULT DirectX::SaveWICTextureToFile( if (sRGB) { // Set EXIF Colorspace of sRGB - value.vt = VT_UI2; + value.vt = VT_UI2; value.uiVal = 1; std::ignore = metawriter->SetMetadataByName(L"/app1/ifd/exif/{ushort=40961}", &value); } @@ -741,12 +748,12 @@ HRESULT DirectX::SaveWICTextureToFile( if (sRGB) { // Set EXIF Colorspace of sRGB - value.vt = VT_UI2; + value.vt = VT_UI2; value.uiVal = 1; std::ignore = metawriter->SetMetadataByName(L"/ifd/exif/{ushort=40961}", &value); } } - #else +#else else { // Set Software name @@ -755,22 +762,22 @@ HRESULT DirectX::SaveWICTextureToFile( if (sRGB) { // Set EXIF Colorspace of sRGB - value.vt = VT_UI2; + value.vt = VT_UI2; value.uiVal = 1; std::ignore = metawriter->SetMetadataByName(L"System.Image.ColorSpace", &value); } } - #endif +#endif } const UINT64 imageSize = dstRowPitch * UINT64(desc.Height); if (imageSize > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); - void* pMappedMemory = nullptr; - D3D12_RANGE readRange = { 0, static_cast(imageSize) }; - D3D12_RANGE writeRange = { 0, 0 }; - hr = pStaging->Map(0, &readRange, &pMappedMemory); + void* pMappedMemory = nullptr; + D3D12_RANGE readRange = { 0, static_cast(imageSize) }; + D3D12_RANGE writeRange = { 0, 0 }; + hr = pStaging->Map(0, &readRange, &pMappedMemory); if (FAILED(hr)) return hr; @@ -778,10 +785,13 @@ HRESULT DirectX::SaveWICTextureToFile( { // Conversion required to write ComPtr source; - hr = pWIC->CreateBitmapFromMemory(static_cast(desc.Width), desc.Height, + hr = pWIC->CreateBitmapFromMemory(static_cast(desc.Width), + desc.Height, pfGuid, - static_cast(dstRowPitch), static_cast(imageSize), - static_cast(pMappedMemory), source.GetAddressOf()); + static_cast(dstRowPitch), + static_cast(imageSize), + static_cast(pMappedMemory), + source.GetAddressOf()); if (FAILED(hr)) { pStaging->Unmap(0, &writeRange); @@ -797,7 +807,7 @@ HRESULT DirectX::SaveWICTextureToFile( } BOOL canConvert = FALSE; - hr = FC->CanConvert(pfGuid, targetGuid, &canConvert); + hr = FC->CanConvert(pfGuid, targetGuid, &canConvert); if (FAILED(hr) || !canConvert) { pStaging->Unmap(0, &writeRange); @@ -812,13 +822,14 @@ HRESULT DirectX::SaveWICTextureToFile( } WICRect rect = { 0, 0, static_cast(desc.Width), static_cast(desc.Height) }; - hr = frame->WriteSource(FC.Get(), &rect); + hr = frame->WriteSource(FC.Get(), &rect); } else { // No conversion required hr = frame->WritePixels(desc.Height, - static_cast(dstRowPitch), static_cast(imageSize), + static_cast(dstRowPitch), + static_cast(imageSize), static_cast(pMappedMemory)); } @@ -840,7 +851,6 @@ HRESULT DirectX::SaveWICTextureToFile( return S_OK; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients @@ -848,33 +858,35 @@ HRESULT DirectX::SaveWICTextureToFile( namespace DirectX { - HRESULT __cdecl SaveDDSTextureToFile( - _In_ ID3D12CommandQueue* pCommandQueue, - _In_ ID3D12Resource* pSource, - _In_z_ const __wchar_t* fileName, - D3D12_RESOURCE_STATES beforeState, - D3D12_RESOURCE_STATES afterState) noexcept + HRESULT __cdecl SaveDDSTextureToFile(_In_ ID3D12CommandQueue* pCommandQueue, + _In_ ID3D12Resource* pSource, + _In_z_ const __wchar_t* fileName, + D3D12_RESOURCE_STATES beforeState, + D3D12_RESOURCE_STATES afterState) noexcept { - return SaveDDSTextureToFile(pCommandQueue, pSource, - reinterpret_cast(fileName), - beforeState, afterState); + return SaveDDSTextureToFile(pCommandQueue, pSource, reinterpret_cast(fileName), beforeState, afterState); } - HRESULT __cdecl SaveWICTextureToFile( - _In_ ID3D12CommandQueue* pCommandQ, - _In_ ID3D12Resource* pSource, - REFGUID guidContainerFormat, - _In_z_ const __wchar_t* fileName, - D3D12_RESOURCE_STATES beforeState, - D3D12_RESOURCE_STATES afterState, - _In_opt_ const GUID* targetFormat, + HRESULT __cdecl SaveWICTextureToFile(_In_ ID3D12CommandQueue* pCommandQ, + _In_ ID3D12Resource* pSource, + REFGUID guidContainerFormat, + _In_z_ const __wchar_t* fileName, + D3D12_RESOURCE_STATES beforeState, + D3D12_RESOURCE_STATES afterState, + _In_opt_ const GUID* targetFormat, _In_ std::function setCustomProps, - bool forceSRGB) + bool forceSRGB) { - return SaveWICTextureToFile(pCommandQ, pSource, guidContainerFormat, + return SaveWICTextureToFile(pCommandQ, + pSource, + guidContainerFormat, reinterpret_cast(fileName), - beforeState, afterState, targetFormat, setCustomProps, forceSRGB); + beforeState, + afterState, + targetFormat, + setCustomProps, + forceSRGB); } -} +} // namespace DirectX #endif // !_NATIVE_WCHAR_T_DEFINED diff --git a/Src/SharedResourcePool.h b/Src/SharedResourcePool.h index 8d9b27e6..c30c4d4a 100644 --- a/Src/SharedResourcePool.h +++ b/Src/SharedResourcePool.h @@ -15,7 +15,6 @@ #include "PlatformHelpers.h" - namespace DirectX { // Pool manager ensures that only a single TData instance is created for each unique TKey. @@ -30,8 +29,8 @@ namespace DirectX : mResourceMap(std::make_shared()) {} - SharedResourcePool(SharedResourcePool const&) = delete; - SharedResourcePool& operator= (SharedResourcePool const&) = delete; + SharedResourcePool(SharedResourcePool const&) = delete; + SharedResourcePool& operator=(SharedResourcePool const&) = delete; // Allocates or looks up the shared TData instance for the specified key. std::shared_ptr DemandCreate(TKey key, TConstructorArgs... args) @@ -60,7 +59,6 @@ namespace DirectX return std::move(newValue); } - private: // Keep track of all allocated TData instances. struct ResourceMap : public std::map> @@ -70,22 +68,21 @@ namespace DirectX std::shared_ptr mResourceMap; - // Wrap TData with our own subclass, so we can hook the destructor // to remove instances from our pool before they are freed. struct WrappedData : public TData { WrappedData(TKey key, std::shared_ptr const& resourceMap, TConstructorArgs... args) : TData(key, args...), - mKey(key), - mResourceMap(resourceMap) + mKey(key), + mResourceMap(resourceMap) {} - WrappedData(WrappedData&&) = default; - WrappedData& operator= (WrappedData&&) = default; + WrappedData(WrappedData&&) = default; + WrappedData& operator=(WrappedData&&) = default; - WrappedData(WrappedData const&) = delete; - WrappedData& operator= (WrappedData const&) = delete; + WrappedData(WrappedData const&) = delete; + WrappedData& operator=(WrappedData const&) = delete; ~WrappedData() { @@ -102,8 +99,8 @@ namespace DirectX } } - TKey mKey; + TKey mKey; std::shared_ptr mResourceMap; }; }; -} +} // namespace DirectX diff --git a/Src/SimpleMath.cpp b/Src/SimpleMath.cpp index 2f9321e6..6331c2cf 100644 --- a/Src/SimpleMath.cpp +++ b/Src/SimpleMath.cpp @@ -21,41 +21,35 @@ namespace DirectX { namespace SimpleMath { - const Vector2 Vector2::Zero = { 0.f, 0.f }; - const Vector2 Vector2::One = { 1.f, 1.f }; + const Vector2 Vector2::Zero = { 0.f, 0.f }; + const Vector2 Vector2::One = { 1.f, 1.f }; const Vector2 Vector2::UnitX = { 1.f, 0.f }; const Vector2 Vector2::UnitY = { 0.f, 1.f }; - const Vector3 Vector3::Zero = { 0.f, 0.f, 0.f }; - const Vector3 Vector3::One = { 1.f, 1.f, 1.f }; - const Vector3 Vector3::UnitX = { 1.f, 0.f, 0.f }; - const Vector3 Vector3::UnitY = { 0.f, 1.f, 0.f }; - const Vector3 Vector3::UnitZ = { 0.f, 0.f, 1.f }; - const Vector3 Vector3::Up = { 0.f, 1.f, 0.f }; - const Vector3 Vector3::Down = { 0.f, -1.f, 0.f }; - const Vector3 Vector3::Right = { 1.f, 0.f, 0.f }; - const Vector3 Vector3::Left = { -1.f, 0.f, 0.f }; - const Vector3 Vector3::Forward = { 0.f, 0.f, -1.f }; + const Vector3 Vector3::Zero = { 0.f, 0.f, 0.f }; + const Vector3 Vector3::One = { 1.f, 1.f, 1.f }; + const Vector3 Vector3::UnitX = { 1.f, 0.f, 0.f }; + const Vector3 Vector3::UnitY = { 0.f, 1.f, 0.f }; + const Vector3 Vector3::UnitZ = { 0.f, 0.f, 1.f }; + const Vector3 Vector3::Up = { 0.f, 1.f, 0.f }; + const Vector3 Vector3::Down = { 0.f, -1.f, 0.f }; + const Vector3 Vector3::Right = { 1.f, 0.f, 0.f }; + const Vector3 Vector3::Left = { -1.f, 0.f, 0.f }; + const Vector3 Vector3::Forward = { 0.f, 0.f, -1.f }; const Vector3 Vector3::Backward = { 0.f, 0.f, 1.f }; - const Vector4 Vector4::Zero = { 0.f, 0.f, 0.f, 0.f }; - const Vector4 Vector4::One = { 1.f, 1.f, 1.f, 1.f }; + const Vector4 Vector4::Zero = { 0.f, 0.f, 0.f, 0.f }; + const Vector4 Vector4::One = { 1.f, 1.f, 1.f, 1.f }; const Vector4 Vector4::UnitX = { 1.f, 0.f, 0.f, 0.f }; const Vector4 Vector4::UnitY = { 0.f, 1.f, 0.f, 0.f }; const Vector4 Vector4::UnitZ = { 0.f, 0.f, 1.f, 0.f }; const Vector4 Vector4::UnitW = { 0.f, 0.f, 0.f, 1.f }; - const Matrix Matrix::Identity = - { - 1.f, 0.f, 0.f, 0.f, - 0.f, 1.f, 0.f, 0.f, - 0.f, 0.f, 1.f, 0.f, - 0.f, 0.f, 0.f, 1.f - }; + const Matrix Matrix::Identity = { 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f }; const Quaternion Quaternion::Identity = { 0.f, 0.f, 0.f, 1.f }; - } -} + } // namespace SimpleMath +} // namespace DirectX using namespace DirectX; using namespace DirectX::SimpleMath; @@ -73,13 +67,13 @@ void Quaternion::RotateTowards(const Quaternion& target, float maxAngle, Quatern // We can use the conjugate here instead of inverse assuming q1 & q2 are normalized. const XMVECTOR R = XMQuaternionMultiply(XMQuaternionConjugate(T), target); - const float rs = XMVectorGetW(R); - const XMVECTOR L = XMVector3Length(R); - const float angle = 2.f * atan2f(XMVectorGetX(L), rs); + const float rs = XMVectorGetW(R); + const XMVECTOR L = XMVector3Length(R); + const float angle = 2.f * atan2f(XMVectorGetX(L), rs); if (angle > maxAngle) { const XMVECTOR delta = XMQuaternionRotationAxis(R, maxAngle); - const XMVECTOR Q = XMQuaternionMultiply(delta, T); + const XMVECTOR Q = XMQuaternionMultiply(delta, T); XMStoreFloat4(&result, Q); } else @@ -146,7 +140,6 @@ void Quaternion::LookRotation(const Vector3& forward, const Vector3& up, Quatern XMStoreFloat4(&result, XMQuaternionMultiply(q2, q1)); } - /**************************************************************************** * * Viewport @@ -174,7 +167,11 @@ static_assert(offsetof(DirectX::SimpleMath::Viewport, maxDepth) == offsetof(D3D1 #endif #if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) -RECT Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight) noexcept +RECT Viewport::ComputeDisplayArea(DXGI_SCALING scaling, + UINT backBufferWidth, + UINT backBufferHeight, + int outputWidth, + int outputHeight) noexcept { RECT rct = {}; @@ -182,9 +179,9 @@ RECT Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UI { case DXGI_SCALING_STRETCH: // Output fills the entire window area - rct.top = 0; - rct.left = 0; - rct.right = outputWidth; + rct.top = 0; + rct.left = 0; + rct.right = outputWidth; rct.bottom = outputHeight; break; @@ -196,27 +193,27 @@ RECT Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UI const float aspectRatio = float(backBufferWidth) / float(backBufferHeight); // Horizontal fill - float scaledWidth = float(outputWidth); + float scaledWidth = float(outputWidth); float scaledHeight = float(outputWidth) / aspectRatio; if (scaledHeight >= float(outputHeight)) { // Do vertical fill - scaledWidth = float(outputHeight) * aspectRatio; + scaledWidth = float(outputHeight) * aspectRatio; scaledHeight = float(outputHeight); } const float offsetX = (float(outputWidth) - scaledWidth) * 0.5f; const float offsetY = (float(outputHeight) - scaledHeight) * 0.5f; - rct.left = static_cast(offsetX); - rct.top = static_cast(offsetY); - rct.right = static_cast(offsetX + scaledWidth); + rct.left = static_cast(offsetX); + rct.top = static_cast(offsetY); + rct.right = static_cast(offsetX + scaledWidth); rct.bottom = static_cast(offsetY + scaledHeight); // Clip to display window - rct.left = std::max(0, rct.left); - rct.top = std::max(0, rct.top); - rct.right = std::min(outputWidth, rct.right); + rct.left = std::max(0, rct.left); + rct.top = std::max(0, rct.top); + rct.right = std::min(outputWidth, rct.right); rct.bottom = std::min(outputHeight, rct.bottom); } break; @@ -224,9 +221,9 @@ RECT Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UI case DXGI_SCALING_NONE: default: // Output is displayed in the upper left corner of the window area - rct.top = 0; - rct.left = 0; - rct.right = std::min(static_cast(backBufferWidth), outputWidth); + rct.top = 0; + rct.left = 0; + rct.right = std::min(static_cast(backBufferWidth), outputWidth); rct.bottom = std::min(static_cast(backBufferHeight), outputHeight); break; } @@ -241,9 +238,9 @@ RECT Viewport::ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight) const float safeh = (float(backBufferHeight) + 19.f) / 20.f; RECT rct; - rct.left = static_cast(safew); - rct.top = static_cast(safeh); - rct.right = static_cast(float(backBufferWidth) - safew + 0.5f); + rct.left = static_cast(safew); + rct.top = static_cast(safeh); + rct.right = static_cast(float(backBufferWidth) - safew + 0.5f); rct.bottom = static_cast(float(backBufferHeight) - safeh + 0.5f); return rct; diff --git a/Src/SkinnedEffect.cpp b/Src/SkinnedEffect.cpp index e8d3db4d..d29e28b6 100644 --- a/Src/SkinnedEffect.cpp +++ b/Src/SkinnedEffect.cpp @@ -39,18 +39,17 @@ namespace static_assert((sizeof(SkinnedEffectConstants) % 16) == 0, "CB size not padded correctly"); - // Traits type describes our characteristics to the EffectBase template. struct SkinnedEffectTraits { using ConstantBufferType = SkinnedEffectConstants; - static constexpr int VertexShaderCount = 4; - static constexpr int PixelShaderCount = 3; + static constexpr int VertexShaderCount = 4; + static constexpr int PixelShaderCount = 3; static constexpr int ShaderPermutationCount = 8; - static constexpr int RootSignatureCount = 1; + static constexpr int RootSignatureCount = 1; }; -} +} // namespace // Internal SkinnedEffect implementation class. class SkinnedEffect::Impl : public EffectBase @@ -58,10 +57,10 @@ class SkinnedEffect::Impl : public EffectBase public: Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; enum RootParameterIndex @@ -82,7 +81,6 @@ class SkinnedEffect::Impl : public EffectBase void Apply(_In_ ID3D12GraphicsCommandList* commandList); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -124,82 +122,82 @@ namespace #include "SkinnedEffect_PSSkinnedVertexLightingNoFog.inc" #include "SkinnedEffect_PSSkinnedPixelLighting.inc" #endif -} - +} // namespace template<> -const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = -{ - { SkinnedEffect_VSSkinnedVertexLightingFourBones, sizeof(SkinnedEffect_VSSkinnedVertexLightingFourBones) }, - { SkinnedEffect_VSSkinnedPixelLightingFourBones, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBones) }, +const D3D12_SHADER_BYTECODE EffectBase::VertexShaderBytecode[] = { + { SkinnedEffect_VSSkinnedVertexLightingFourBones, sizeof(SkinnedEffect_VSSkinnedVertexLightingFourBones) }, + { SkinnedEffect_VSSkinnedPixelLightingFourBones, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBones) }, { SkinnedEffect_VSSkinnedVertexLightingFourBonesBn, sizeof(SkinnedEffect_VSSkinnedVertexLightingFourBonesBn) }, - { SkinnedEffect_VSSkinnedPixelLightingFourBonesBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBonesBn) }, + { SkinnedEffect_VSSkinnedPixelLightingFourBonesBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBonesBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // vertex lighting, four bones - 0, // vertex lighting, four bones, no fog +const int EffectBase::VertexShaderIndices[] = { + 0, // vertex lighting, four bones + 0, // vertex lighting, four bones, no fog - 1, // pixel lighting, four bones - 1, // pixel lighting, four bones, no fog + 1, // pixel lighting, four bones + 1, // pixel lighting, four bones, no fog - 2, // vertex lighting (biased vertex normals), four bones - 2, // vertex lighting (biased vertex normals), four bones, no fog + 2, // vertex lighting (biased vertex normals), four bones + 2, // vertex lighting (biased vertex normals), four bones, no fog - 3, // pixel lighting (biased vertex normals), four bones - 3, // pixel lighting (biased vertex normals), four bones, no fog + 3, // pixel lighting (biased vertex normals), four bones + 3, // pixel lighting (biased vertex normals), four bones, no fog }; - template<> -const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = -{ - { SkinnedEffect_PSSkinnedVertexLighting, sizeof(SkinnedEffect_PSSkinnedVertexLighting) }, +const D3D12_SHADER_BYTECODE EffectBase::PixelShaderBytecode[] = { + { SkinnedEffect_PSSkinnedVertexLighting, sizeof(SkinnedEffect_PSSkinnedVertexLighting) }, { SkinnedEffect_PSSkinnedVertexLightingNoFog, sizeof(SkinnedEffect_PSSkinnedVertexLightingNoFog) }, - { SkinnedEffect_PSSkinnedPixelLighting, sizeof(SkinnedEffect_PSSkinnedPixelLighting) }, + { SkinnedEffect_PSSkinnedPixelLighting, sizeof(SkinnedEffect_PSSkinnedPixelLighting) }, }; - template<> -const int EffectBase::PixelShaderIndices[] = -{ - 0, // vertex lighting, four bones - 1, // vertex lighting, four bones, no fog +const int EffectBase::PixelShaderIndices[] = { + 0, // vertex lighting, four bones + 1, // vertex lighting, four bones, no fog - 2, // pixel lighting, four bones - 2, // pixel lighting, four bones, no fog + 2, // pixel lighting, four bones + 2, // pixel lighting, four bones, no fog - 0, // vertex lighting (biased vertex normals), four bones - 1, // vertex lighting (biased vertex normals), four bones, no fog + 0, // vertex lighting (biased vertex normals), four bones + 1, // vertex lighting (biased vertex normals), four bones, no fog - 2, // pixel lighting (biased vertex normals), four bones - 2, // pixel lighting (biased vertex normals), four bones, no fog + 2, // pixel lighting (biased vertex normals), four bones + 2, // pixel lighting (biased vertex normals), four bones, no fog }; #pragma endregion // Global pool of per-device SkinnedEffect resources. template<> -SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - +SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool + = {}; // Constructor. -SkinnedEffect::Impl::Impl( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) +SkinnedEffect::Impl::Impl(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription) : EffectBase(device), - texture{}, - sampler{} -{ - static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == SkinnedEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == SkinnedEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); - - lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); + texture{}, + sampler{} +{ + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) + == SkinnedEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) + == SkinnedEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) + == SkinnedEffectTraits::PixelShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) + == SkinnedEffectTraits::ShaderPermutationCount, + "array/max mismatch"); + + lights.InitializeConstants(constants.specularColorAndPower, + constants.lightDirection, + constants.lightDiffuseColor, + constants.lightSpecularColor); for (int i = 0; i < MaxBones; i++) { @@ -210,15 +208,12 @@ SkinnedEffect::Impl::Impl( // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; const CD3DX12_DESCRIPTOR_RANGE textureSrvDescriptorRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); @@ -226,7 +221,9 @@ SkinnedEffect::Impl::Impl( CD3DX12_ROOT_PARAMETER rootParameters[RootParameterIndex::RootParameterCount] = {}; rootParameters[RootParameterIndex::TextureSRV].InitAsDescriptorTable(1, &textureSrvDescriptorRange, D3D12_SHADER_VISIBILITY_PIXEL); - rootParameters[RootParameterIndex::TextureSampler].InitAsDescriptorTable(1, &textureSamplerDescriptorRange, D3D12_SHADER_VISIBILITY_PIXEL); + rootParameters[RootParameterIndex::TextureSampler].InitAsDescriptorTable(1, + &textureSamplerDescriptorRange, + D3D12_SHADER_VISIBILITY_PIXEL); rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc = {}; @@ -262,8 +259,7 @@ SkinnedEffect::Impl::Impl( assert(pi >= 0 && pi < SkinnedEffectTraits::PixelShaderCount); _Analysis_assume_(pi >= 0 && pi < SkinnedEffectTraits::PixelShaderCount); - pipelineDescription.CreatePipelineState( - device, + pipelineDescription.CreatePipelineState(device, mRootSignature, EffectBase::VertexShaderBytecode[vi], EffectBase::PixelShaderBytecode[pi], @@ -272,7 +268,6 @@ SkinnedEffect::Impl::Impl( SetDebugObjectName(mPipelineState.Get(), L"SkinnedEffect"); } - int SkinnedEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const noexcept { int permutation = 0; @@ -298,14 +293,20 @@ int SkinnedEffect::Impl::GetPipelineStatePermutation(uint32_t effectFlags) const return permutation; } - // Sets our state onto the D3D device. void SkinnedEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) { // Compute derived parameter values. matrices.SetConstants(dirtyFlags, constants.worldViewProj); fog.SetConstants(dirtyFlags, matrices.worldView, constants.fogVector); - lights.SetConstants(dirtyFlags, matrices, constants.world, constants.worldInverseTranspose, constants.eyePosition, constants.diffuseColor, constants.emissiveColor, true); + lights.SetConstants(dirtyFlags, + matrices, + constants.world, + constants.worldInverseTranspose, + constants.eyePosition, + constants.diffuseColor, + constants.emissiveColor, + true); UpdateConstants(); @@ -319,7 +320,8 @@ void SkinnedEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) throw std::runtime_error("SkinnedEffect"); } - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heaps. commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSampler, sampler); @@ -330,20 +332,14 @@ void SkinnedEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) commandList->SetPipelineState(EffectBase::mPipelineState.Get()); } - // Public constructor. -SkinnedEffect::SkinnedEffect( - _In_ ID3D12Device* device, - uint32_t effectFlags, - const EffectPipelineStateDescription& pipelineDescription) +SkinnedEffect::SkinnedEffect(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription) : pImpl(std::make_unique(device, effectFlags, pipelineDescription)) {} - -SkinnedEffect::SkinnedEffect(SkinnedEffect&&) noexcept = default; -SkinnedEffect& SkinnedEffect::operator= (SkinnedEffect&&) noexcept = default; -SkinnedEffect::~SkinnedEffect() = default; - +SkinnedEffect::SkinnedEffect(SkinnedEffect&&) noexcept = default; +SkinnedEffect& SkinnedEffect::operator=(SkinnedEffect&&) noexcept = default; +SkinnedEffect::~SkinnedEffect() = default; // IEffect methods. void SkinnedEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) @@ -351,7 +347,6 @@ void SkinnedEffect::Apply(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Apply(commandList); } - // Camera settings. void XM_CALLCONV SkinnedEffect::SetWorld(FXMMATRIX value) { @@ -360,7 +355,6 @@ void XM_CALLCONV SkinnedEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::FogVector; } - void XM_CALLCONV SkinnedEffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -368,7 +362,6 @@ void XM_CALLCONV SkinnedEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; } - void XM_CALLCONV SkinnedEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -376,17 +369,16 @@ void XM_CALLCONV SkinnedEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV SkinnedEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->matrices.world = world; - pImpl->matrices.view = view; + pImpl->matrices.world = world; + pImpl->matrices.view = view; pImpl->matrices.projection = projection; - pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition | EffectDirtyFlags::FogVector; + pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition + | EffectDirtyFlags::FogVector; } - // Material settings. void XM_CALLCONV SkinnedEffect::SetDiffuseColor(FXMVECTOR value) { @@ -395,7 +387,6 @@ void XM_CALLCONV SkinnedEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV SkinnedEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -403,7 +394,6 @@ void XM_CALLCONV SkinnedEffect::SetEmissiveColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV SkinnedEffect::SetSpecularColor(FXMVECTOR value) { // Set xyz to new value, but preserve existing w (specular power). @@ -412,7 +402,6 @@ void XM_CALLCONV SkinnedEffect::SetSpecularColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void SkinnedEffect::SetSpecularPower(float value) { // Set w to new value, but preserve existing xyz (specular color). @@ -421,7 +410,6 @@ void SkinnedEffect::SetSpecularPower(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void SkinnedEffect::DisableSpecular() { // Set specular color to black, power to 1 @@ -432,7 +420,6 @@ void SkinnedEffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void SkinnedEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -440,16 +427,14 @@ void SkinnedEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV SkinnedEffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->lights.diffuseColor = value; - pImpl->lights.alpha = XMVectorGetW(value); + pImpl->lights.alpha = XMVectorGetW(value); pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - // Light settings. void XM_CALLCONV SkinnedEffect::SetAmbientLightColor(FXMVECTOR value) { @@ -458,13 +443,12 @@ void XM_CALLCONV SkinnedEffect::SetAmbientLightColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void SkinnedEffect::SetLightEnabled(int whichLight, bool value) { - pImpl->dirtyFlags |= pImpl->lights.SetLightEnabled(whichLight, value, pImpl->constants.lightDiffuseColor, pImpl->constants.lightSpecularColor); + pImpl->dirtyFlags + |= pImpl->lights.SetLightEnabled(whichLight, value, pImpl->constants.lightDiffuseColor, pImpl->constants.lightSpecularColor); } - void XM_CALLCONV SkinnedEffect::SetLightDirection(int whichLight, FXMVECTOR value) { EffectLights::ValidateLightIndex(whichLight); @@ -474,25 +458,21 @@ void XM_CALLCONV SkinnedEffect::SetLightDirection(int whichLight, FXMVECTOR valu pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV SkinnedEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR value) { pImpl->dirtyFlags |= pImpl->lights.SetLightDiffuseColor(whichLight, value, pImpl->constants.lightDiffuseColor); } - void XM_CALLCONV SkinnedEffect::SetLightSpecularColor(int whichLight, FXMVECTOR value) { pImpl->dirtyFlags |= pImpl->lights.SetLightSpecularColor(whichLight, value, pImpl->constants.lightSpecularColor); } - void SkinnedEffect::EnableDefaultLighting() { EffectLights::EnableDefaultLighting(this); } - // Fog settings. void SkinnedEffect::SetFogStart(float value) { @@ -501,7 +481,6 @@ void SkinnedEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void SkinnedEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -509,7 +488,6 @@ void SkinnedEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV SkinnedEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -517,7 +495,6 @@ void XM_CALLCONV SkinnedEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void SkinnedEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor) { @@ -525,7 +502,6 @@ void SkinnedEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_ pImpl->sampler = samplerDescriptor; } - // Animation settings. void SkinnedEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { @@ -536,22 +512,21 @@ void SkinnedEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, s for (size_t i = 0; i < count; i++) { - #if DIRECTX_MATH_VERSION >= 313 +#if DIRECTX_MATH_VERSION >= 313 XMStoreFloat3x4A(reinterpret_cast(&boneConstant[i]), value[i]); - #else - // Xbox One XDK has an older version of DirectXMath +#else + // Xbox One XDK has an older version of DirectXMath XMMATRIX boneMatrix = XMMatrixTranspose(value[i]); boneConstant[i][0] = boneMatrix.r[0]; boneConstant[i][1] = boneMatrix.r[1]; boneConstant[i][2] = boneMatrix.r[2]; - #endif +#endif } pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void SkinnedEffect::ResetBoneTransforms() { auto boneConstant = pImpl->constants.bones; diff --git a/Src/SpriteBatch.cpp b/Src/SpriteBatch.cpp index bcb63d4b..ef2af9fa 100644 --- a/Src/SpriteBatch.cpp +++ b/Src/SpriteBatch.cpp @@ -47,11 +47,11 @@ namespace #include "SpriteEffect_SpritePixelShaderHeap.inc" #endif - inline bool operator != (D3D12_GPU_DESCRIPTOR_HANDLE a, D3D12_GPU_DESCRIPTOR_HANDLE b) noexcept + inline bool operator!=(D3D12_GPU_DESCRIPTOR_HANDLE a, D3D12_GPU_DESCRIPTOR_HANDLE b) noexcept { return a.ptr != b.ptr; } - inline bool operator < (D3D12_GPU_DESCRIPTOR_HANDLE a, D3D12_GPU_DESCRIPTOR_HANDLE b) noexcept + inline bool operator<(D3D12_GPU_DESCRIPTOR_HANDLE a, D3D12_GPU_DESCRIPTOR_HANDLE b) noexcept { return a.ptr < b.ptr; } @@ -68,51 +68,49 @@ namespace return v; } -} +} // namespace // Internal SpriteBatch implementation class. XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew { public: - Impl(_In_ ID3D12Device* device, - ResourceUploadBatch& upload, + Impl(_In_ ID3D12Device * device, + ResourceUploadBatch & upload, const SpriteBatchPipelineStateDescription& psoDesc, - _In_opt_ const D3D12_VIEWPORT* viewport); + _In_opt_ const D3D12_VIEWPORT* viewport); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; - void XM_CALLCONV Begin( - _In_ ID3D12GraphicsCommandList* commandList, - SpriteSortMode sortMode = SpriteSortMode_Deferred, - FXMMATRIX transformMatrix = MatrixIdentity); - void End(); - - void XM_CALLCONV Draw( - D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - FXMVECTOR destination, - _In_opt_ RECT const* sourceRectangle, - FXMVECTOR color, - FXMVECTOR originRotationDepth, - unsigned int flags); + void XM_CALLCONV Begin(_In_ ID3D12GraphicsCommandList * commandList, + SpriteSortMode sortMode = SpriteSortMode_Deferred, + FXMMATRIX transformMatrix = MatrixIdentity); + void End(); + + void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 const& textureSize, + FXMVECTOR destination, + _In_opt_ RECT const* sourceRectangle, + FXMVECTOR color, + FXMVECTOR originRotationDepth, + unsigned int flags); // Info about a single sprite that is waiting to be drawn. XM_ALIGNED_STRUCT(16) SpriteInfo : public AlignedNew { - XMFLOAT4A source; - XMFLOAT4A destination; - XMFLOAT4A color; - XMFLOAT4A originRotationDepth; + XMFLOAT4A source; + XMFLOAT4A destination; + XMFLOAT4A color; + XMFLOAT4A originRotationDepth; D3D12_GPU_DESCRIPTOR_HANDLE texture; - XMVECTOR textureSize; - unsigned int flags; + XMVECTOR textureSize; + unsigned int flags; // Combine values from the public SpriteEffects enum with these internal-only flags. - static constexpr unsigned int SourceInTexels = 4; + static constexpr unsigned int SourceInTexels = 4; static constexpr unsigned int DestSizeInPixels = 8; static_assert((SpriteEffects_FlipBoth & (SourceInTexels | DestSizeInPixels)) == 0, "Flag bits must not overlap"); @@ -120,9 +118,9 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew DXGI_MODE_ROTATION mRotation; - bool mSetViewport; - D3D12_VIEWPORT mViewPort; - D3D12_GPU_DESCRIPTOR_HANDLE mSampler; + bool mSetViewport; + D3D12_VIEWPORT mViewPort; + D3D12_GPU_DESCRIPTOR_HANDLE mSampler; std::function mCustomCallback; XMMATRIX GetViewportTransform(_In_ DXGI_MODE_ROTATION rotation); @@ -135,41 +133,38 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew void SortSprites(); void GrowSortedSprites(); - void RenderBatch( - D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMVECTOR textureSize, + void RenderBatch(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMVECTOR textureSize, _In_reads_(count) SpriteInfo const* const* sprites, - size_t count); + size_t count); - static void XM_CALLCONV RenderSprite(_In_ SpriteInfo const* sprite, + static void XM_CALLCONV RenderSprite(_In_ SpriteInfo const* sprite, _Out_writes_(VerticesPerSprite) VertexPositionColorTexture* vertices, - FXMVECTOR textureSize, - FXMVECTOR inverseTextureSize) noexcept; + FXMVECTOR textureSize, + FXMVECTOR inverseTextureSize) noexcept; // Constants. - static constexpr size_t MaxBatchSize = 2048; - static constexpr size_t MinBatchSize = 128; - static constexpr size_t InitialQueueSize = 64; + static constexpr size_t MaxBatchSize = 2048; + static constexpr size_t MinBatchSize = 128; + static constexpr size_t InitialQueueSize = 64; static constexpr size_t VerticesPerSprite = 4; - static constexpr size_t IndicesPerSprite = 6; + static constexpr size_t IndicesPerSprite = 6; // // The following functions and members are used to create the default pipeline state objects. // - static const D3D12_SHADER_BYTECODE s_DefaultVertexShaderByteCodeStatic; - static const D3D12_SHADER_BYTECODE s_DefaultPixelShaderByteCodeStatic; - static const D3D12_SHADER_BYTECODE s_DefaultVertexShaderByteCodeHeap; - static const D3D12_SHADER_BYTECODE s_DefaultPixelShaderByteCodeHeap; + static const D3D12_SHADER_BYTECODE s_DefaultVertexShaderByteCodeStatic; + static const D3D12_SHADER_BYTECODE s_DefaultPixelShaderByteCodeStatic; + static const D3D12_SHADER_BYTECODE s_DefaultVertexShaderByteCodeHeap; + static const D3D12_SHADER_BYTECODE s_DefaultPixelShaderByteCodeHeap; static const D3D12_INPUT_LAYOUT_DESC s_DefaultInputLayoutDesc; - // Queue of sprites waiting to be drawn. std::unique_ptr mSpriteQueue; size_t mSpriteQueueCount; size_t mSpriteQueueArraySize; - // To avoid needlessly copying around bulky SpriteInfo structures, we leave that // actual data alone and just sort this array of pointers instead. But we want contiguous // memory for cache efficiency, so these pointers are just shortcuts into the single @@ -182,16 +177,16 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew // Mode settings from the last Begin call. bool mInBeginEndPair; - SpriteSortMode mSortMode; - ComPtr mPSO; - ComPtr mRootSignature; - XMMATRIX mTransformMatrix; + SpriteSortMode mSortMode; + ComPtr mPSO; + ComPtr mRootSignature; + XMMATRIX mTransformMatrix; ComPtr mCommandList; // Batched data GraphicsResource mVertexSegment; - size_t mVertexPageSize; - size_t mSpriteCount; + size_t mVertexPageSize; + size_t mSpriteCount; GraphicsResource mConstantBuffer; enum RootParameterIndex @@ -207,11 +202,11 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew { DeviceResources(_In_ ID3D12Device* device, ResourceUploadBatch& upload); - ComPtr indexBuffer; - D3D12_INDEX_BUFFER_VIEW indexBufferView; + ComPtr indexBuffer; + D3D12_INDEX_BUFFER_VIEW indexBufferView; ComPtr rootSignatureStatic; ComPtr rootSignatureHeap; - ID3D12Device* mDevice; + ID3D12Device* mDevice; private: void CreateIndexBuffer(_In_ ID3D12Device* device, ResourceUploadBatch& upload); @@ -221,89 +216,82 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew }; // Per-device data. - std::shared_ptr mDeviceResources; + std::shared_ptr mDeviceResources; static SharedResourcePool deviceResourcesPool; }; - // Global pools of per-device and per-context SpriteBatch resources. SharedResourcePool SpriteBatch::Impl::deviceResourcesPool; - // Constants. const XMMATRIX SpriteBatch::MatrixIdentity = XMMatrixIdentity(); const XMFLOAT2 SpriteBatch::Float2Zero(0, 0); -const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultVertexShaderByteCodeStatic = { SpriteEffect_SpriteVertexShader, sizeof(SpriteEffect_SpriteVertexShader) }; -const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultPixelShaderByteCodeStatic = { SpriteEffect_SpritePixelShader, sizeof(SpriteEffect_SpritePixelShader) }; +const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultVertexShaderByteCodeStatic + = { SpriteEffect_SpriteVertexShader, sizeof(SpriteEffect_SpriteVertexShader) }; +const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultPixelShaderByteCodeStatic + = { SpriteEffect_SpritePixelShader, sizeof(SpriteEffect_SpritePixelShader) }; -const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultVertexShaderByteCodeHeap = { SpriteEffect_SpriteVertexShaderHeap, sizeof(SpriteEffect_SpriteVertexShaderHeap) }; -const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultPixelShaderByteCodeHeap = { SpriteEffect_SpritePixelShaderHeap, sizeof(SpriteEffect_SpritePixelShaderHeap) }; +const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultVertexShaderByteCodeHeap + = { SpriteEffect_SpriteVertexShaderHeap, sizeof(SpriteEffect_SpriteVertexShaderHeap) }; +const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultPixelShaderByteCodeHeap + = { SpriteEffect_SpritePixelShaderHeap, sizeof(SpriteEffect_SpritePixelShaderHeap) }; const D3D12_INPUT_LAYOUT_DESC SpriteBatch::Impl::s_DefaultInputLayoutDesc = VertexPositionColorTexture::InputLayout; // Matches CommonStates::AlphaBlend -const D3D12_BLEND_DESC SpriteBatchPipelineStateDescription::s_DefaultBlendDesc = -{ - FALSE, // AlphaToCoverageEnable - FALSE, // IndependentBlendEnable - { { - TRUE, // BlendEnable - FALSE, // LogicOpEnable - D3D12_BLEND_ONE, // SrcBlend - D3D12_BLEND_INV_SRC_ALPHA, // DestBlend - D3D12_BLEND_OP_ADD, // BlendOp - D3D12_BLEND_ONE, // SrcBlendAlpha - D3D12_BLEND_INV_SRC_ALPHA, // DestBlendAlpha - D3D12_BLEND_OP_ADD, // BlendOpAlpha +const D3D12_BLEND_DESC SpriteBatchPipelineStateDescription::s_DefaultBlendDesc = { FALSE, // AlphaToCoverageEnable + FALSE, // IndependentBlendEnable + { { TRUE, // BlendEnable + FALSE, // LogicOpEnable + D3D12_BLEND_ONE, // SrcBlend + D3D12_BLEND_INV_SRC_ALPHA, // DestBlend + D3D12_BLEND_OP_ADD, // BlendOp + D3D12_BLEND_ONE, // SrcBlendAlpha + D3D12_BLEND_INV_SRC_ALPHA, // DestBlendAlpha + D3D12_BLEND_OP_ADD, // BlendOpAlpha D3D12_LOGIC_OP_NOOP, - D3D12_COLOR_WRITE_ENABLE_ALL - } } -}; + D3D12_COLOR_WRITE_ENABLE_ALL } } }; // Same to CommonStates::CullCounterClockwise -const D3D12_RASTERIZER_DESC SpriteBatchPipelineStateDescription::s_DefaultRasterizerDesc = -{ - D3D12_FILL_MODE_SOLID, +const D3D12_RASTERIZER_DESC SpriteBatchPipelineStateDescription::s_DefaultRasterizerDesc = { D3D12_FILL_MODE_SOLID, D3D12_CULL_MODE_BACK, FALSE, // FrontCounterClockwise D3D12_DEFAULT_DEPTH_BIAS, D3D12_DEFAULT_DEPTH_BIAS_CLAMP, D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS, - TRUE, // DepthClipEnable - TRUE, // MultisampleEnable + TRUE, // DepthClipEnable + TRUE, // MultisampleEnable FALSE, // AntialiasedLineEnable - 0, // ForcedSampleCount - D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF -}; + 0, // ForcedSampleCount + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF }; // Same as CommonStates::DepthNone -const D3D12_DEPTH_STENCIL_DESC SpriteBatchPipelineStateDescription::s_DefaultDepthStencilDesc = -{ - FALSE, // DepthEnable +const D3D12_DEPTH_STENCIL_DESC SpriteBatchPipelineStateDescription::s_DefaultDepthStencilDesc = { + FALSE, // DepthEnable D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_LESS_EQUAL, // DepthFunc - FALSE, // StencilEnable + FALSE, // StencilEnable D3D12_DEFAULT_STENCIL_READ_MASK, D3D12_DEFAULT_STENCIL_WRITE_MASK, { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc - }, // FrontFace + }, // FrontFace { - D3D12_STENCIL_OP_KEEP, // StencilFailOp - D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp - D3D12_STENCIL_OP_KEEP, // StencilPassOp + D3D12_STENCIL_OP_KEEP, // StencilFailOp + D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp + D3D12_STENCIL_OP_KEEP, // StencilPassOp D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc } // BackFace }; // Per-device constructor. -SpriteBatch::Impl::DeviceResources::DeviceResources(_In_ ID3D12Device* device, ResourceUploadBatch& upload) : - indexBufferView{}, - mDevice(device) +SpriteBatch::Impl::DeviceResources::DeviceResources(_In_ ID3D12Device* device, ResourceUploadBatch& upload) + : indexBufferView{}, + mDevice(device) { CreateIndexBuffer(device, upload); CreateRootSignatures(device); @@ -315,11 +303,10 @@ void SpriteBatch::Impl::DeviceResources::CreateIndexBuffer(_In_ ID3D12Device* de static_assert((MaxBatchSize * VerticesPerSprite) < USHRT_MAX, "MaxBatchSize too large for 16-bit indices"); const CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_DEFAULT); - const auto bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(short) * MaxBatchSize * IndicesPerSprite); + const auto bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(short) * MaxBatchSize * IndicesPerSprite); // Create the constant buffer. - ThrowIfFailed(device->CreateCommittedResource( - &heapProps, + ThrowIfFailed(device->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &bufferDesc, c_initialCopyTargetState, @@ -331,9 +318,9 @@ void SpriteBatch::Impl::DeviceResources::CreateIndexBuffer(_In_ ID3D12Device* de auto indexValues = CreateIndexValues(); D3D12_SUBRESOURCE_DATA indexDataDesc = {}; - indexDataDesc.pData = indexValues.data(); - indexDataDesc.RowPitch = static_cast(bufferDesc.Width); - indexDataDesc.SlicePitch = indexDataDesc.RowPitch; + indexDataDesc.pData = indexValues.data(); + indexDataDesc.RowPitch = static_cast(bufferDesc.Width); + indexDataDesc.SlicePitch = indexDataDesc.RowPitch; // Upload the resource upload.Upload(indexBuffer.Get(), 0, &indexDataDesc, 1); @@ -342,29 +329,25 @@ void SpriteBatch::Impl::DeviceResources::CreateIndexBuffer(_In_ ID3D12Device* de // Create the index buffer view indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress(); - indexBufferView.Format = DXGI_FORMAT_R16_UINT; - indexBufferView.SizeInBytes = static_cast(bufferDesc.Width); + indexBufferView.Format = DXGI_FORMAT_R16_UINT; + indexBufferView.SizeInBytes = static_cast(bufferDesc.Width); } void SpriteBatch::Impl::DeviceResources::CreateRootSignatures(_In_ ID3D12Device* device) { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; const CD3DX12_DESCRIPTOR_RANGE textureSRV(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); { // Same as CommonStates::StaticLinearClamp - const CD3DX12_STATIC_SAMPLER_DESC sampler( - 0, // register + const CD3DX12_STATIC_SAMPLER_DESC sampler(0, // register D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -430,60 +413,60 @@ std::vector SpriteBatch::Impl::DeviceResources::CreateIndexValues() } // Per-SpriteBatch constructor. -_Use_decl_annotations_ -SpriteBatch::Impl::Impl(ID3D12Device* device, - ResourceUploadBatch& upload, - const SpriteBatchPipelineStateDescription& psoDesc, - const D3D12_VIEWPORT* viewport) +_Use_decl_annotations_ SpriteBatch::Impl::Impl(ID3D12Device* device, + ResourceUploadBatch& upload, + const SpriteBatchPipelineStateDescription& psoDesc, + const D3D12_VIEWPORT* viewport) : mRotation(DXGI_MODE_ROTATION_IDENTITY), - mSetViewport(false), - mViewPort{}, - mSampler{}, - mSpriteQueueCount(0), - mSpriteQueueArraySize(0), - mCustomCBV(false), - mInBeginEndPair(false), - mSortMode(SpriteSortMode_Deferred), - mTransformMatrix(MatrixIdentity), - mVertexSegment{}, - mVertexPageSize(sizeof(VertexPositionColorTexture) * MaxBatchSize * VerticesPerSprite), - mSpriteCount(0), - mDeviceResources{} + mSetViewport(false), + mViewPort{}, + mSampler{}, + mSpriteQueueCount(0), + mSpriteQueueArraySize(0), + mCustomCBV(false), + mInBeginEndPair(false), + mSortMode(SpriteSortMode_Deferred), + mTransformMatrix(MatrixIdentity), + mVertexSegment{}, + mVertexPageSize(sizeof(VertexPositionColorTexture) * MaxBatchSize * VerticesPerSprite), + mSpriteCount(0), + mDeviceResources{} { if (!device) throw std::invalid_argument("Direct3D device is null"); if (viewport != nullptr) { - mViewPort = *viewport; + mViewPort = *viewport; mSetViewport = true; } mDeviceResources = deviceResourcesPool.DemandCreate(device, upload); D3D12_GRAPHICS_PIPELINE_STATE_DESC d3dDesc = {}; - d3dDesc.InputLayout = s_DefaultInputLayoutDesc; - d3dDesc.BlendState = psoDesc.blendDesc; - d3dDesc.DepthStencilState = psoDesc.depthStencilDesc; - d3dDesc.RasterizerState = psoDesc.rasterizerDesc; - d3dDesc.DSVFormat = psoDesc.renderTargetState.dsvFormat; - d3dDesc.NodeMask = psoDesc.renderTargetState.nodeMask; - d3dDesc.NumRenderTargets = psoDesc.renderTargetState.numRenderTargets; + d3dDesc.InputLayout = s_DefaultInputLayoutDesc; + d3dDesc.BlendState = psoDesc.blendDesc; + d3dDesc.DepthStencilState = psoDesc.depthStencilDesc; + d3dDesc.RasterizerState = psoDesc.rasterizerDesc; + d3dDesc.DSVFormat = psoDesc.renderTargetState.dsvFormat; + d3dDesc.NodeMask = psoDesc.renderTargetState.nodeMask; + d3dDesc.NumRenderTargets = psoDesc.renderTargetState.numRenderTargets; memcpy(d3dDesc.RTVFormats, psoDesc.renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); - d3dDesc.SampleDesc = psoDesc.renderTargetState.sampleDesc; - d3dDesc.SampleMask = psoDesc.renderTargetState.sampleMask; - d3dDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; + d3dDesc.SampleDesc = psoDesc.renderTargetState.sampleDesc; + d3dDesc.SampleMask = psoDesc.renderTargetState.sampleMask; + d3dDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; d3dDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; // Three choices: (1) static sampler, (2) heap sampler, or (3) custom signature & shaders if (psoDesc.customRootSignature) { mRootSignature = psoDesc.customRootSignature; - mCustomCBV = psoDesc.customCBV; + mCustomCBV = psoDesc.customCBV; } else { - mRootSignature = (psoDesc.samplerDescriptor.ptr) ? mDeviceResources->rootSignatureHeap.Get() : mDeviceResources->rootSignatureStatic.Get(); + mRootSignature + = (psoDesc.samplerDescriptor.ptr) ? mDeviceResources->rootSignatureHeap.Get() : mDeviceResources->rootSignatureStatic.Get(); } d3dDesc.pRootSignature = mRootSignature.Get(); @@ -510,19 +493,15 @@ SpriteBatch::Impl::Impl(ID3D12Device* device, mSampler = psoDesc.samplerDescriptor; } - ThrowIfFailed(device->CreateGraphicsPipelineState( - &d3dDesc, - IID_GRAPHICS_PPV_ARGS(mPSO.GetAddressOf()))); + ThrowIfFailed(device->CreateGraphicsPipelineState(&d3dDesc, IID_GRAPHICS_PPV_ARGS(mPSO.GetAddressOf()))); SetDebugObjectName(mPSO.Get(), L"SpriteBatch"); } // Begins a batch of sprite drawing operations. -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Impl::Begin( - ID3D12GraphicsCommandList* commandList, - SpriteSortMode sortMode, - FXMMATRIX transformMatrix) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Impl::Begin(ID3D12GraphicsCommandList* commandList, + SpriteSortMode sortMode, + FXMMATRIX transformMatrix) { if (mInBeginEndPair) { @@ -530,10 +509,10 @@ void XM_CALLCONV SpriteBatch::Impl::Begin( throw std::logic_error("SpriteBatch::Begin"); } - mSortMode = sortMode; + mSortMode = sortMode; mTransformMatrix = transformMatrix; - mCommandList = commandList; - mSpriteCount = 0; + mCommandList = commandList; + mSpriteCount = 0; if (sortMode == SpriteSortMode_Immediate) { @@ -566,19 +545,17 @@ void SpriteBatch::Impl::End() mCustomCallback = nullptr; mInBeginEndPair = false; - mCommandList = nullptr; + mCommandList = nullptr; } - // Adds a single sprite to the queue. -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Impl::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - FXMVECTOR destination, - RECT const* sourceRectangle, - FXMVECTOR color, - FXMVECTOR originRotationDepth, - unsigned int flags) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Impl::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 const& textureSize, + FXMVECTOR destination, + RECT const* sourceRectangle, + FXMVECTOR color, + FXMVECTOR originRotationDepth, + unsigned int flags) { if (!mInBeginEndPair) { @@ -617,7 +594,7 @@ void XM_CALLCONV SpriteBatch::Impl::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, else { // No explicit source region, so use the entire texture. - static const XMVECTORF32 wholeTexture = { { {0, 0, 1, 1} } }; + static const XMVECTORF32 wholeTexture = { { { 0, 0, 1, 1 } } }; XMStoreFloat4A(&sprite->source, wholeTexture); } @@ -630,9 +607,9 @@ void XM_CALLCONV SpriteBatch::Impl::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMStoreFloat4A(&sprite->color, color); XMStoreFloat4A(&sprite->originRotationDepth, originRotationDepth); - sprite->texture = texture; + sprite->texture = texture; sprite->textureSize = textureSizeV; - sprite->flags = flags; + sprite->flags = flags; if (mSortMode == SpriteSortMode_Immediate) { @@ -646,7 +623,6 @@ void XM_CALLCONV SpriteBatch::Impl::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, } } - // Dynamically expands the array used to store pending sprite information. void SpriteBatch::Impl::GrowSpriteQueue() { @@ -663,14 +639,13 @@ void SpriteBatch::Impl::GrowSpriteQueue() } // Replace the previous array with the new one. - mSpriteQueue = std::move(newArray); + mSpriteQueue = std::move(newArray); mSpriteQueueArraySize = newSize; // Clear any dangling SpriteInfo pointers left over from previous rendering. mSortedSprites.clear(); } - // Sets up D3D device state ready for drawing sprites. void SpriteBatch::Impl::PrepareForRendering() { @@ -689,9 +664,8 @@ void SpriteBatch::Impl::PrepareForRendering() if (!mCustomCBV) { // Set the transform matrix. - const XMMATRIX transformMatrix = (mRotation == DXGI_MODE_ROTATION_UNSPECIFIED) - ? mTransformMatrix - : (mTransformMatrix * GetViewportTransform(mRotation)); + const XMMATRIX transformMatrix + = (mRotation == DXGI_MODE_ROTATION_UNSPECIFIED) ? mTransformMatrix : (mTransformMatrix * GetViewportTransform(mRotation)); mConstantBuffer = GraphicsMemory::Get(mDeviceResources->mDevice).AllocateConstant(transformMatrix); commandList->SetGraphicsRootConstantBufferView(RootParameterIndex::ConstantBuffer, mConstantBuffer.GpuAddress()); @@ -704,7 +678,6 @@ void SpriteBatch::Impl::PrepareForRendering() } } - // Sends queued sprites to the graphics device. void SpriteBatch::Impl::FlushBatch() { @@ -714,9 +687,9 @@ void SpriteBatch::Impl::FlushBatch() SortSprites(); // Walk through the sorted sprite list, looking for adjacent entries that share a texture. - D3D12_GPU_DESCRIPTOR_HANDLE batchTexture = {}; - XMVECTOR batchTextureSize = {}; - size_t batchStart = 0; + D3D12_GPU_DESCRIPTOR_HANDLE batchTexture = {}; + XMVECTOR batchTextureSize = {}; + size_t batchStart = 0; for (size_t pos = 0; pos < mSpriteQueueCount; pos++) { @@ -732,9 +705,9 @@ void SpriteBatch::Impl::FlushBatch() RenderBatch(batchTexture, batchTextureSize, &mSortedSprites[batchStart], pos - batchStart); } - batchTexture = texture; + batchTexture = texture; batchTextureSize = textureSize; - batchStart = pos; + batchStart = pos; } } @@ -753,7 +726,6 @@ void SpriteBatch::Impl::FlushBatch() } } - // Sorts the array of queued sprites. void SpriteBatch::Impl::SortSprites() { @@ -795,12 +767,10 @@ void SpriteBatch::Impl::SortSprites() }); break; - default: - break; + default: break; } } - // Populates the mSortedSprites vector with pointers to individual elements of the mSpriteQueue array. void SpriteBatch::Impl::GrowSortedSprites() { @@ -814,15 +784,15 @@ void SpriteBatch::Impl::GrowSortedSprites() } } - // Submits a batch of sprites to the GPU. -_Use_decl_annotations_ -void SpriteBatch::Impl::RenderBatch(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMVECTOR textureSize, SpriteInfo const* const* sprites, size_t count) +_Use_decl_annotations_ void +SpriteBatch::Impl::RenderBatch(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMVECTOR textureSize, SpriteInfo const* const* sprites, size_t count) { auto commandList = mCommandList.Get(); // Draw using the specified texture. - // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heap(s) + // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor + // heap(s) commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); if (mSampler.ptr) @@ -877,10 +847,10 @@ void SpriteBatch::Impl::RenderBatch(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMVECTO // Set the vertex buffer view D3D12_VERTEX_BUFFER_VIEW vbv; - constexpr size_t spriteVertexTotalSize = sizeof(VertexPositionColorTexture) * VerticesPerSprite; + constexpr size_t spriteVertexTotalSize = sizeof(VertexPositionColorTexture) * VerticesPerSprite; vbv.BufferLocation = mVertexSegment.GpuAddress() + (UINT64(mSpriteCount) * UINT64(spriteVertexTotalSize)); - vbv.StrideInBytes = sizeof(VertexPositionColorTexture); - vbv.SizeInBytes = static_cast(batchSize * spriteVertexTotalSize); + vbv.StrideInBytes = sizeof(VertexPositionColorTexture); + vbv.SizeInBytes = static_cast(batchSize * spriteVertexTotalSize); commandList->IASetVertexBuffers(0, 1, &vbv); // Ok lads, the time has come for us draw ourselves some sprites! @@ -896,26 +866,27 @@ void SpriteBatch::Impl::RenderBatch(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMVECTO } } - // Generates vertex data for drawing a single sprite. -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, VertexPositionColorTexture* vertices, FXMVECTOR textureSize, FXMVECTOR inverseTextureSize) noexcept +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, + VertexPositionColorTexture* vertices, + FXMVECTOR textureSize, + FXMVECTOR inverseTextureSize) noexcept { // Load sprite parameters into SIMD registers. - XMVECTOR source = XMLoadFloat4A(&sprite->source); - const XMVECTOR destination = XMLoadFloat4A(&sprite->destination); - const XMVECTOR color = XMLoadFloat4A(&sprite->color); + XMVECTOR source = XMLoadFloat4A(&sprite->source); + const XMVECTOR destination = XMLoadFloat4A(&sprite->destination); + const XMVECTOR color = XMLoadFloat4A(&sprite->color); const XMVECTOR originRotationDepth = XMLoadFloat4A(&sprite->originRotationDepth); - const float rotation = sprite->originRotationDepth.z; - const unsigned int flags = sprite->flags; + const float rotation = sprite->originRotationDepth.z; + const unsigned int flags = sprite->flags; // Extract the source and destination sizes into separate vectors. - XMVECTOR sourceSize = XMVectorSwizzle<2, 3, 2, 3>(source); + XMVECTOR sourceSize = XMVectorSwizzle<2, 3, 2, 3>(source); XMVECTOR destinationSize = XMVectorSwizzle<2, 3, 2, 3>(destination); // Scale the origin offset by source size, taking care to avoid overflow if the source region is zero. - const XMVECTOR isZeroMask = XMVectorEqual(sourceSize, XMVectorZero()); + const XMVECTOR isZeroMask = XMVectorEqual(sourceSize, XMVectorZero()); const XMVECTOR nonZeroSourceSize = XMVectorSelect(sourceSize, g_XMEpsilon, isZeroMask); XMVECTOR origin = XMVectorDivide(originRotationDepth, nonZeroSourceSize); @@ -923,7 +894,7 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, Verte // Convert the source region from texels to mod-1 texture coordinate format. if (flags & SpriteInfo::SourceInTexels) { - source = XMVectorMultiply(source, inverseTextureSize); + source = XMVectorMultiply(source, inverseTextureSize); sourceSize = XMVectorMultiply(sourceSize, inverseTextureSize); } else @@ -960,8 +931,7 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, Verte } // The four corner vertices are computed by transforming these unit-square positions. - static XMVECTORF32 cornerOffsets[VerticesPerSprite] = - { + static XMVECTORF32 cornerOffsets[VerticesPerSprite] = { { { { 0, 0, 0, 0 } } }, { { { 1, 0, 0, 0 } } }, { { { 0, 1, 0, 0 } } }, @@ -975,8 +945,8 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, Verte // position = cornerOffsets[i] // texcoord = cornerOffsets[i ^ SpriteEffects] - static_assert(SpriteEffects_FlipHorizontally == 1 && - SpriteEffects_FlipVertically == 2, "If you change these enum values, the mirroring implementation must be updated to match"); + static_assert(SpriteEffects_FlipHorizontally == 1 && SpriteEffects_FlipVertically == 2, + "If you change these enum values, the mirroring implementation must be updated to match"); const unsigned int mirrorBits = flags & 3u; @@ -1002,13 +972,13 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, Verte XMStoreFloat4(&vertices[i].color, color); // Compute and write the texture coordinate. - const XMVECTOR textureCoordinate = XMVectorMultiplyAdd(cornerOffsets[static_cast(i) ^ mirrorBits], sourceSize, source); + const XMVECTOR textureCoordinate + = XMVectorMultiplyAdd(cornerOffsets[static_cast(i) ^ mirrorBits], sourceSize, source); XMStoreFloat2(&vertices[i].textureCoordinate, textureCoordinate); } } - // Generates a viewport transform matrix for rendering sprites using x-right y-down screen pixel coordinates. XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ DXGI_MODE_ROTATION rotation) { @@ -1024,78 +994,41 @@ XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ DXGI_MODE_ROTATION rotatio switch (rotation) { - case DXGI_MODE_ROTATION_ROTATE90: - return XMMATRIX - ( - 0, -yScale, 0, 0, - -xScale, 0, 0, 0, - 0, 0, 1, 0, - 1, 1, 0, 1 - ); - - case DXGI_MODE_ROTATION_ROTATE270: - return XMMATRIX - ( - 0, yScale, 0, 0, - xScale, 0, 0, 0, - 0, 0, 1, 0, - -1, -1, 0, 1 - ); - - case DXGI_MODE_ROTATION_ROTATE180: - return XMMATRIX - ( - -xScale, 0, 0, 0, - 0, yScale, 0, 0, - 0, 0, 1, 0, - 1, -1, 0, 1 - ); - - default: - return XMMATRIX - ( - xScale, 0, 0, 0, - 0, -yScale, 0, 0, - 0, 0, 1, 0, - -1, 1, 0, 1 - ); + case DXGI_MODE_ROTATION_ROTATE90: return XMMATRIX(0, -yScale, 0, 0, -xScale, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1); + + case DXGI_MODE_ROTATION_ROTATE270: return XMMATRIX(0, yScale, 0, 0, xScale, 0, 0, 0, 0, 0, 1, 0, -1, -1, 0, 1); + + case DXGI_MODE_ROTATION_ROTATE180: return XMMATRIX(-xScale, 0, 0, 0, 0, yScale, 0, 0, 0, 0, 1, 0, 1, -1, 0, 1); + + default: return XMMATRIX(xScale, 0, 0, 0, 0, -yScale, 0, 0, 0, 0, 1, 0, -1, 1, 0, 1); } } - // Public constructor. -_Use_decl_annotations_ -SpriteBatch::SpriteBatch(ID3D12Device* device, - ResourceUploadBatch& upload, - const SpriteBatchPipelineStateDescription& psoDesc, - const D3D12_VIEWPORT* viewport) +_Use_decl_annotations_ SpriteBatch::SpriteBatch(ID3D12Device* device, + ResourceUploadBatch& upload, + const SpriteBatchPipelineStateDescription& psoDesc, + const D3D12_VIEWPORT* viewport) : pImpl(std::make_unique(device, upload, psoDesc, viewport)) {} - -SpriteBatch::SpriteBatch(SpriteBatch&&) noexcept = default; -SpriteBatch& SpriteBatch::operator= (SpriteBatch&&) noexcept = default; -SpriteBatch::~SpriteBatch() = default; - +SpriteBatch::SpriteBatch(SpriteBatch&&) noexcept = default; +SpriteBatch& SpriteBatch::operator=(SpriteBatch&&) noexcept = default; +SpriteBatch::~SpriteBatch() = default; // Begin using static sampler -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Begin( - ID3D12GraphicsCommandList* commandList, - SpriteSortMode sortMode, - FXMMATRIX transformMatrix) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Begin(ID3D12GraphicsCommandList* commandList, + SpriteSortMode sortMode, + FXMMATRIX transformMatrix) { pImpl->Begin(commandList, sortMode, transformMatrix); } - // Begin with heap-based sampler -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Begin( - ID3D12GraphicsCommandList* commandList, - D3D12_GPU_DESCRIPTOR_HANDLE sampler, - SpriteSortMode sortMode, - FXMMATRIX transformMatrix) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Begin(ID3D12GraphicsCommandList* commandList, + D3D12_GPU_DESCRIPTOR_HANDLE sampler, + SpriteSortMode sortMode, + FXMMATRIX transformMatrix) { if (!sampler.ptr) throw std::invalid_argument("Invalid heap-based sampler for Begin"); @@ -1111,29 +1044,23 @@ void XM_CALLCONV SpriteBatch::Begin( pImpl->Begin(commandList, sortMode, transformMatrix); } - // Begin using static sampler and custom lambda -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Begin( - ID3D12GraphicsCommandList* commandList, - std::function setCustomCallback, - SpriteSortMode sortMode, - FXMMATRIX transformMatrix) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Begin(ID3D12GraphicsCommandList* commandList, + std::function setCustomCallback, + SpriteSortMode sortMode, + FXMMATRIX transformMatrix) { pImpl->mCustomCallback = setCustomCallback; pImpl->Begin(commandList, sortMode, transformMatrix); } - // Begin with heap-based sampler and custom lambda -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Begin( - ID3D12GraphicsCommandList* commandList, - D3D12_GPU_DESCRIPTOR_HANDLE sampler, - std::function setCustomCallback, - SpriteSortMode sortMode, - FXMMATRIX transformMatrix) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Begin(ID3D12GraphicsCommandList* commandList, + D3D12_GPU_DESCRIPTOR_HANDLE sampler, + std::function setCustomCallback, + SpriteSortMode sortMode, + FXMMATRIX transformMatrix) { if (!sampler.ptr) throw std::invalid_argument("Invalid heap-based sampler for Begin"); @@ -1144,41 +1071,37 @@ void XM_CALLCONV SpriteBatch::Begin( throw std::runtime_error("SpriteBatch::Begin"); } - pImpl->mSampler = sampler; + pImpl->mSampler = sampler; pImpl->mCustomCallback = setCustomCallback; pImpl->Begin(commandList, sortMode, transformMatrix); } - void SpriteBatch::End() { pImpl->End(); } - void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - XMFLOAT2 const& position, - FXMVECTOR color) + XMUINT2 const& textureSize, + XMFLOAT2 const& position, + FXMVECTOR color) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(XMLoadFloat2(&position), g_XMOne); // x, y, 1, 1 pImpl->Draw(texture, textureSize, destination, nullptr, color, g_XMZero, 0); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - XMFLOAT2 const& position, - RECT const* sourceRectangle, - FXMVECTOR color, - float rotation, - XMFLOAT2 const& origin, - float scale, - SpriteEffects effects, - float layerDepth) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 const& textureSize, + XMFLOAT2 const& position, + RECT const* sourceRectangle, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + float scale, + SpriteEffects effects, + float layerDepth) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 4>(XMLoadFloat2(&position), XMLoadFloat(&scale)); // x, y, scale, scale @@ -1187,18 +1110,16 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - XMFLOAT2 const& position, - RECT const* sourceRectangle, - FXMVECTOR color, - float rotation, - XMFLOAT2 const& origin, - XMFLOAT2 const& scale, - SpriteEffects effects, - float layerDepth) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 const& textureSize, + XMFLOAT2 const& position, + RECT const* sourceRectangle, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects, + float layerDepth) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(XMLoadFloat2(&position), XMLoadFloat2(&scale)); // x, y, scale.x, scale.y @@ -1207,7 +1128,6 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 const& textureSize, FXMVECTOR position, FXMVECTOR color) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(position, g_XMOne); // x, y, 1, 1 @@ -1215,101 +1135,93 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 pImpl->Draw(texture, textureSize, destination, nullptr, color, g_XMZero, 0); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - FXMVECTOR position, - RECT const* sourceRectangle, - FXMVECTOR color, - float rotation, - FXMVECTOR origin, - float scale, - SpriteEffects effects, - float layerDepth) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 const& textureSize, + FXMVECTOR position, + RECT const* sourceRectangle, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + float scale, + SpriteEffects effects, + float layerDepth) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 4>(position, XMLoadFloat(&scale)); // x, y, scale, scale - const XMVECTOR rotationDepth = XMVectorMergeXY( - XMVectorReplicate(rotation), - XMVectorReplicate(layerDepth)); + const XMVECTOR rotationDepth = XMVectorMergeXY(XMVectorReplicate(rotation), XMVectorReplicate(layerDepth)); const XMVECTOR originRotationDepth = XMVectorPermute<0, 1, 4, 5>(origin, rotationDepth); pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - FXMVECTOR position, - RECT const* sourceRectangle, - FXMVECTOR color, - float rotation, - FXMVECTOR origin, - GXMVECTOR scale, - SpriteEffects effects, - float layerDepth) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 const& textureSize, + FXMVECTOR position, + RECT const* sourceRectangle, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects, + float layerDepth) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(position, scale); // x, y, scale.x, scale.y - const XMVECTOR rotationDepth = XMVectorMergeXY( - XMVectorReplicate(rotation), - XMVectorReplicate(layerDepth)); + const XMVECTOR rotationDepth = XMVectorMergeXY(XMVectorReplicate(rotation), XMVectorReplicate(layerDepth)); const XMVECTOR originRotationDepth = XMVectorPermute<0, 1, 4, 5>(origin, rotationDepth); pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - RECT const& destinationRectangle, - FXMVECTOR color) + XMUINT2 const& textureSize, + RECT const& destinationRectangle, + FXMVECTOR color) { const XMVECTOR destination = LoadRect(&destinationRectangle); // x, y, w, h pImpl->Draw(texture, textureSize, destination, nullptr, color, g_XMZero, Impl::SpriteInfo::DestSizeInPixels); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 const& textureSize, - RECT const& destinationRectangle, - RECT const* sourceRectangle, - FXMVECTOR color, - float rotation, - XMFLOAT2 const& origin, - SpriteEffects effects, - float layerDepth) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 const& textureSize, + RECT const& destinationRectangle, + RECT const* sourceRectangle, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + SpriteEffects effects, + float layerDepth) { const XMVECTOR destination = LoadRect(&destinationRectangle); // x, y, w, h const XMVECTOR originRotationDepth = XMVectorSet(origin.x, origin.y, rotation, layerDepth); - pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast(effects) | Impl::SpriteInfo::DestSizeInPixels); + pImpl->Draw(texture, + textureSize, + destination, + sourceRectangle, + color, + originRotationDepth, + static_cast(effects) | Impl::SpriteInfo::DestSizeInPixels); } - void SpriteBatch::SetRotation(DXGI_MODE_ROTATION mode) { pImpl->mRotation = mode; } - DXGI_MODE_ROTATION SpriteBatch::GetRotation() const noexcept { return pImpl->mRotation; } - void SpriteBatch::SetViewport(const D3D12_VIEWPORT& viewPort) { pImpl->mSetViewport = true; - pImpl->mViewPort = viewPort; + pImpl->mViewPort = viewPort; } void SpriteBatch::GetViewportTransform(XMMATRIX& transformMatrix) const diff --git a/Src/SpriteFont.cpp b/Src/SpriteFont.cpp index 7c01fe21..db5a5156 100644 --- a/Src/SpriteFont.cpp +++ b/Src/SpriteFont.cpp @@ -22,27 +22,26 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - // Internal SpriteFont implementation class. class SpriteFont::Impl { public: - Impl(_In_ ID3D12Device* device, - ResourceUploadBatch& upload, - _In_ BinaryReader* reader, + Impl(_In_ ID3D12Device* device, + ResourceUploadBatch& upload, + _In_ BinaryReader* reader, D3D12_CPU_DESCRIPTOR_HANDLE cpuDesc, D3D12_GPU_DESCRIPTOR_HANDLE gpuDesc, - bool forceSRGB) noexcept(false); - Impl(D3D12_GPU_DESCRIPTOR_HANDLE texture, - XMUINT2 textureSize, + bool forceSRGB) noexcept(false); + Impl(D3D12_GPU_DESCRIPTOR_HANDLE texture, + XMUINT2 textureSize, _In_reads_(glyphCount) Glyph const* glyphs, - size_t glyphCount, - float lineSpacing) noexcept(false); + size_t glyphCount, + float lineSpacing) noexcept(false); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; Glyph const* FindGlyph(wchar_t character) const; @@ -52,72 +51,69 @@ class SpriteFont::Impl template void ForEachGlyph(_In_z_ wchar_t const* text, TAction action, bool ignoreWhitespace) const; - const wchar_t* ConvertUTF8(_In_z_ const char *text) noexcept(false); + const wchar_t* ConvertUTF8(_In_z_ const char* text) noexcept(false); // Fields. - ComPtr textureResource; + ComPtr textureResource; D3D12_GPU_DESCRIPTOR_HANDLE texture; - XMUINT2 textureSize; - std::vector glyphs; - std::vector glyphsIndex; - Glyph const* defaultGlyph; - float lineSpacing; - bool pixelAlignment; + XMUINT2 textureSize; + std::vector glyphs; + std::vector glyphsIndex; + Glyph const* defaultGlyph; + float lineSpacing; + bool pixelAlignment; private: void CreateTextureResource(_In_ ID3D12Device* device, - ResourceUploadBatch& upload, - uint32_t width, uint32_t height, - DXGI_FORMAT format, - uint32_t stride, uint32_t rows, - _In_reads_(stride * rows) const uint8_t* data) noexcept(false); - - size_t utfBufferSize; + ResourceUploadBatch& upload, + uint32_t width, + uint32_t height, + DXGI_FORMAT format, + uint32_t stride, + uint32_t rows, + _In_reads_(stride* rows) const uint8_t* data) noexcept(false); + + size_t utfBufferSize; std::unique_ptr utfBuffer; }; - // Constants. const XMFLOAT2 SpriteFont::Float2Zero(0, 0); static const char spriteFontMagic[] = "DXTKfont"; - // Comparison operators make our sorted glyph vector work with std::binary_search and lower_bound. namespace DirectX { - static inline bool operator< (SpriteFont::Glyph const& left, SpriteFont::Glyph const& right) noexcept + static inline bool operator<(SpriteFont::Glyph const& left, SpriteFont::Glyph const& right) noexcept { return left.Character < right.Character; } - static inline bool operator< (wchar_t left, SpriteFont::Glyph const& right) noexcept + static inline bool operator<(wchar_t left, SpriteFont::Glyph const& right) noexcept { return left < right.Character; } - static inline bool operator< (SpriteFont::Glyph const& left, wchar_t right) noexcept + static inline bool operator<(SpriteFont::Glyph const& left, wchar_t right) noexcept { return left.Character < right; } -} - +} // namespace DirectX // Reads a SpriteFont from the binary format created by the MakeSpriteFont utility. -_Use_decl_annotations_ -SpriteFont::Impl::Impl( - ID3D12Device* device, - ResourceUploadBatch& upload, - BinaryReader* reader, - D3D12_CPU_DESCRIPTOR_HANDLE cpuDesc, - D3D12_GPU_DESCRIPTOR_HANDLE gpuDesc, - bool forceSRGB) noexcept(false) : - texture{}, - textureSize{}, - defaultGlyph(nullptr), - lineSpacing(0), - pixelAlignment(false), - utfBufferSize(0) +_Use_decl_annotations_ SpriteFont::Impl::Impl(ID3D12Device* device, + ResourceUploadBatch& upload, + BinaryReader* reader, + D3D12_CPU_DESCRIPTOR_HANDLE cpuDesc, + D3D12_GPU_DESCRIPTOR_HANDLE gpuDesc, + bool forceSRGB) noexcept(false) + : texture{}, + textureSize{}, + defaultGlyph(nullptr), + lineSpacing(0), + pixelAlignment(false), + utfBufferSize(0) { if (!device || !reader) throw std::invalid_argument("Direct3D device is null"); @@ -134,7 +130,7 @@ SpriteFont::Impl::Impl( // Read the glyph data. auto glyphCount = reader->Read(); - auto glyphData = reader->ReadArray(glyphCount); + auto glyphData = reader->ReadArray(glyphCount); glyphs.assign(glyphData, glyphData + glyphCount); glyphsIndex.reserve(glyphs.size()); @@ -150,19 +146,14 @@ SpriteFont::Impl::Impl( SetDefaultCharacter(static_cast(reader->Read())); // Read the texture data. - auto textureWidth = reader->Read(); + auto textureWidth = reader->Read(); auto textureHeight = reader->Read(); auto textureFormat = reader->Read(); auto textureStride = reader->Read(); - auto textureRows = reader->Read(); - - if (!textureWidth - || !textureHeight - || !textureStride - || !textureRows - || (textureWidth > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) - || (textureHeight > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) - || LoaderHelpers::BitsPerPixel(textureFormat) == 0) + auto textureRows = reader->Read(); + + if (!textureWidth || !textureHeight || !textureStride || !textureRows || (textureWidth > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) + || (textureHeight > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) || LoaderHelpers::BitsPerPixel(textureFormat) == 0) { DebugTrace("ERROR: SpriteFont provided with an invalid .spritefont file\n"); throw std::runtime_error("Invalid .spritefont file"); @@ -183,40 +174,29 @@ SpriteFont::Impl::Impl( } // Create the D3D texture. - CreateTextureResource( - device, - upload, - textureWidth, textureHeight, - textureFormat, - textureStride, textureRows, - textureData); + CreateTextureResource(device, upload, textureWidth, textureHeight, textureFormat, textureStride, textureRows, textureData); // Create the shader resource view - CreateShaderResourceView( - device, textureResource.Get(), - cpuDesc, false); + CreateShaderResourceView(device, textureResource.Get(), cpuDesc, false); // Save off the GPU descriptor pointer and size. - texture = gpuDesc; + texture = gpuDesc; textureSize = XMUINT2(textureWidth, textureHeight); } - // Constructs a SpriteFont from arbitrary user specified glyph data. -_Use_decl_annotations_ -SpriteFont::Impl::Impl( - D3D12_GPU_DESCRIPTOR_HANDLE itexture, - XMUINT2 itextureSize, - Glyph const* iglyphs, - size_t glyphCount, - float ilineSpacing) noexcept(false) : - texture(itexture), - textureSize(itextureSize), - glyphs(iglyphs, iglyphs + glyphCount), - defaultGlyph(nullptr), - lineSpacing(ilineSpacing), - pixelAlignment(false), - utfBufferSize(0) +_Use_decl_annotations_ SpriteFont::Impl::Impl(D3D12_GPU_DESCRIPTOR_HANDLE itexture, + XMUINT2 itextureSize, + Glyph const* iglyphs, + size_t glyphCount, + float ilineSpacing) noexcept(false) + : texture(itexture), + textureSize(itextureSize), + glyphs(iglyphs, iglyphs + glyphCount), + defaultGlyph(nullptr), + lineSpacing(ilineSpacing), + pixelAlignment(false), + utfBufferSize(0) { if (!itexture.ptr) { @@ -236,7 +216,6 @@ SpriteFont::Impl::Impl( } } - // Looks up the requested glyph, falling back to the default character if it is not in the font. SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const { @@ -244,15 +223,18 @@ SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const // we implement a binary search inline to ensure sufficient Debug build performance to be useful // for text-heavy applications. - size_t lower = 0; - size_t higher = glyphs.size() - 1; - size_t index = higher / 2; - const size_t size = glyphs.size(); + size_t lower = 0; + size_t higher = glyphs.size() - 1; + size_t index = higher / 2; + const size_t size = glyphs.size(); while (index < size) { const auto curChar = glyphsIndex[index]; - if (curChar == character) { return &glyphs[index]; } + if (curChar == character) + { + return &glyphs[index]; + } if (curChar < character) { lower = index + 1; @@ -261,7 +243,10 @@ SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const { higher = index - 1; } - if (higher < lower) { break; } + if (higher < lower) + { + break; + } else if (higher - lower <= 4) { for (index = lower; index <= higher; index++) @@ -280,11 +265,12 @@ SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const return defaultGlyph; } - DebugTrace("ERROR: SpriteFont encountered a character not in the font (%u, %C), and no default glyph was provided\n", character, character); + DebugTrace("ERROR: SpriteFont encountered a character not in the font (%u, %C), and no default glyph was provided\n", + character, + character); throw std::runtime_error("Character not in font"); } - // Sets the missing-character fallback glyph. void SpriteFont::Impl::SetDefaultCharacter(wchar_t character) { @@ -296,7 +282,6 @@ void SpriteFont::Impl::SetDefaultCharacter(wchar_t character) } } - // The core glyph layout algorithm, shared between DrawString and MeasureString. template void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action, bool ignoreWhitespace) const @@ -331,9 +316,7 @@ void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action, const float advance = float(glyph->Subrect.right) - float(glyph->Subrect.left) + glyph->XAdvance; - if (!ignoreWhitespace - || !iswspace(character) - || ((glyph->Subrect.right - glyph->Subrect.left) > 1) + if (!ignoreWhitespace || !iswspace(character) || ((glyph->Subrect.right - glyph->Subrect.left) > 1) || ((glyph->Subrect.bottom - glyph->Subrect.top) > 1)) { action(glyph, x, y, advance); @@ -345,15 +328,14 @@ void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action, } } - -_Use_decl_annotations_ -void SpriteFont::Impl::CreateTextureResource( - ID3D12Device* device, - ResourceUploadBatch& upload, - uint32_t width, uint32_t height, - DXGI_FORMAT format, - uint32_t stride, uint32_t rows, - const uint8_t* data) noexcept(false) +_Use_decl_annotations_ void SpriteFont::Impl::CreateTextureResource(ID3D12Device* device, + ResourceUploadBatch& upload, + uint32_t width, + uint32_t height, + DXGI_FORMAT format, + uint32_t stride, + uint32_t rows, + const uint8_t* data) noexcept(false) { const uint64_t sliceBytes = uint64_t(stride) * uint64_t(rows); if (sliceBytes > UINT32_MAX) @@ -363,18 +345,17 @@ void SpriteFont::Impl::CreateTextureResource( } D3D12_RESOURCE_DESC desc = {}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = width; - desc.Height = height; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = format; - desc.SampleDesc.Count = 1; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; const CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT); - ThrowIfFailed(device->CreateCommittedResource( - &defaultHeapProperties, + ThrowIfFailed(device->CreateCommittedResource(&defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, @@ -385,20 +366,12 @@ void SpriteFont::Impl::CreateTextureResource( D3D12_SUBRESOURCE_DATA initData = { data, static_cast(stride), static_cast(sliceBytes) }; - upload.Upload( - textureResource.Get(), - 0, - &initData, - 1); + upload.Upload(textureResource.Get(), 0, &initData, 1); - upload.Transition( - textureResource.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + upload.Transition(textureResource.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); } - -const wchar_t* SpriteFont::Impl::ConvertUTF8(_In_z_ const char *text) noexcept(false) +const wchar_t* SpriteFont::Impl::ConvertUTF8(_In_z_ const char* text) noexcept(false) { if (!utfBuffer) { @@ -410,7 +383,7 @@ const wchar_t* SpriteFont::Impl::ConvertUTF8(_In_z_ const char *text) noexcept(f if (!result && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { // Compute required buffer size - result = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0); + result = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0); utfBufferSize = AlignUp(static_cast(result), 1024u); utfBuffer.reset(new wchar_t[utfBufferSize]); @@ -427,74 +400,122 @@ const wchar_t* SpriteFont::Impl::ConvertUTF8(_In_z_ const char *text) noexcept(f return utfBuffer.get(); } - // Construct from a binary file created by the MakeSpriteFont utility. -_Use_decl_annotations_ -SpriteFont::SpriteFont(ID3D12Device* device, ResourceUploadBatch& upload, wchar_t const* fileName, D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorDest, bool forceSRGB) +_Use_decl_annotations_ SpriteFont::SpriteFont(ID3D12Device* device, + ResourceUploadBatch& upload, + wchar_t const* fileName, + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, + D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorDest, + bool forceSRGB) { BinaryReader reader(fileName); pImpl = std::make_unique(device, upload, &reader, cpuDescriptorDest, gpuDescriptorDest, forceSRGB); } - // Construct from a binary blob created by the MakeSpriteFont utility and already loaded into memory. -_Use_decl_annotations_ -SpriteFont::SpriteFont(ID3D12Device* device, ResourceUploadBatch& upload, uint8_t const* dataBlob, size_t dataSize, D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorDest, bool forceSRGB) +_Use_decl_annotations_ SpriteFont::SpriteFont(ID3D12Device* device, + ResourceUploadBatch& upload, + uint8_t const* dataBlob, + size_t dataSize, + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, + D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorDest, + bool forceSRGB) { BinaryReader reader(dataBlob, dataSize); pImpl = std::make_unique(device, upload, &reader, cpuDescriptorDest, gpuDescriptorDest, forceSRGB); } - // Construct from arbitrary user specified glyph data (for those not using the MakeSpriteFont utility). _Use_decl_annotations_ SpriteFont::SpriteFont(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 textureSize, Glyph const* glyphs, size_t glyphCount, float lineSpacing) : pImpl(std::make_unique(texture, textureSize, glyphs, glyphCount, lineSpacing)) {} - -SpriteFont::SpriteFont(SpriteFont&&) noexcept = default; -SpriteFont& SpriteFont::operator= (SpriteFont&&) noexcept = default; -SpriteFont::~SpriteFont() = default; +SpriteFont::SpriteFont(SpriteFont&&) noexcept = default; +SpriteFont& SpriteFont::operator=(SpriteFont&&) noexcept = default; +SpriteFont::~SpriteFont() = default; // Wide-character / UTF-16LE -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, float scale, SpriteEffects effects, float layerDepth) const -{ - DrawString(spriteBatch, text, XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMVectorReplicate(scale), effects, layerDepth); -} - - -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects, float layerDepth) const -{ - DrawString(spriteBatch, text, XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMLoadFloat2(&scale), effects, layerDepth); -} - - -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, float scale, SpriteEffects effects, float layerDepth) const +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + float scale, + SpriteEffects effects, + float layerDepth) const +{ + DrawString(spriteBatch, + text, + XMLoadFloat2(&position), + color, + rotation, + XMLoadFloat2(&origin), + XMVectorReplicate(scale), + effects, + layerDepth); +} + +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects, + float layerDepth) const +{ + DrawString(spriteBatch, + text, + XMLoadFloat2(&position), + color, + rotation, + XMLoadFloat2(&origin), + XMLoadFloat2(&scale), + effects, + layerDepth); +} + +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + float scale, + SpriteEffects effects, + float layerDepth) const { DrawString(spriteBatch, text, position, color, rotation, origin, XMVectorReplicate(scale), effects, layerDepth); } - -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects, float layerDepth) const +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects, + float layerDepth) const { - static_assert(SpriteEffects_FlipHorizontally == 1 && - SpriteEffects_FlipVertically == 2, "If you change these enum values, the following tables must be updated to match"); + static_assert(SpriteEffects_FlipHorizontally == 1 && SpriteEffects_FlipVertically == 2, + "If you change these enum values, the following tables must be updated to match"); -// Lookup table indicates which way to move along each axis per SpriteEffects enum value. - static XMVECTORF32 axisDirectionTable[4] = - { + // Lookup table indicates which way to move along each axis per SpriteEffects enum value. + static XMVECTORF32 axisDirectionTable[4] = { { { { -1, -1, 0, 0 } } }, - { { { 1, -1, 0, 0 } } }, - { { { -1, 1, 0, 0 } } }, - { { { 1, 1, 0, 0 } } }, + { { { 1, -1, 0, 0 } } }, + { { { -1, 1, 0, 0 } } }, + { { { 1, 1, 0, 0 } } }, }; // Lookup table indicates which axes are mirrored for each SpriteEffects enum value. - static XMVECTORF32 axisIsMirroredTable[4] = - { + static XMVECTORF32 axisIsMirroredTable[4] = { { { { 0, 0, 0, 0 } } }, { { { 1, 0, 0, 0 } } }, { { { 0, 1, 0, 0 } } }, @@ -506,14 +527,13 @@ void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wc // If the text is mirrored, offset the start position accordingly. if (effects) { - baseOffset = XMVectorNegativeMultiplySubtract( - MeasureString(text), - axisIsMirroredTable[effects & 3], - baseOffset); + baseOffset = XMVectorNegativeMultiplySubtract(MeasureString(text), axisIsMirroredTable[effects & 3], baseOffset); } // Draw each character in turn. - pImpl->ForEachGlyph(text, [&](Glyph const* glyph, float x, float y, float advance) + pImpl->ForEachGlyph( + text, + [&](Glyph const* glyph, float x, float y, float advance) { UNREFERENCED_PARAMETER(advance); @@ -535,44 +555,45 @@ void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wc offset = XMVectorRound(offset); } - spriteBatch->Draw(pImpl->texture, pImpl->textureSize, position, &glyph->Subrect, color, rotation, offset, scale, effects, layerDepth); - }, true); + spriteBatch + ->Draw(pImpl->texture, pImpl->textureSize, position, &glyph->Subrect, color, rotation, offset, scale, effects, layerDepth); + }, + true); } - XMVECTOR XM_CALLCONV SpriteFont::MeasureString(_In_z_ wchar_t const* text, bool ignoreWhitespace) const { XMVECTOR result = XMVectorZero(); - pImpl->ForEachGlyph(text, [&](Glyph const* glyph, float x, float y, float advance) + pImpl->ForEachGlyph( + text, + [&](Glyph const* glyph, float x, float y, float advance) { UNREFERENCED_PARAMETER(advance); const auto w = static_cast(glyph->Subrect.right - glyph->Subrect.left); - auto h = static_cast(glyph->Subrect.bottom - glyph->Subrect.top) + glyph->YOffset; + auto h = static_cast(glyph->Subrect.bottom - glyph->Subrect.top) + glyph->YOffset; - h = iswspace(wchar_t(glyph->Character)) ? - pImpl->lineSpacing : - std::max(h, pImpl->lineSpacing); + h = iswspace(wchar_t(glyph->Character)) ? pImpl->lineSpacing : std::max(h, pImpl->lineSpacing); result = XMVectorMax(result, XMVectorSet(x + w, y + h, 0, 0)); - }, ignoreWhitespace); + }, + ignoreWhitespace); return result; } - RECT SpriteFont::MeasureDrawBounds(_In_z_ wchar_t const* text, XMFLOAT2 const& position, bool ignoreWhitespace) const { RECT result = { LONG_MAX, LONG_MAX, 0, 0 }; - pImpl->ForEachGlyph(text, [&](Glyph const* glyph, float x, float y, float advance) noexcept + pImpl->ForEachGlyph( + text, + [&](Glyph const* glyph, float x, float y, float advance) noexcept { const auto isWhitespace = iswspace(wchar_t(glyph->Character)); - const auto w = static_cast(glyph->Subrect.right - glyph->Subrect.left); - const auto h = isWhitespace ? - pImpl->lineSpacing : - static_cast(glyph->Subrect.bottom - glyph->Subrect.top); + const auto w = static_cast(glyph->Subrect.right - glyph->Subrect.left); + const auto h = isWhitespace ? pImpl->lineSpacing : static_cast(glyph->Subrect.bottom - glyph->Subrect.top); const float minX = position.x + x; const float minY = position.y + y + (isWhitespace ? 0.0f : glyph->YOffset); @@ -591,18 +612,18 @@ RECT SpriteFont::MeasureDrawBounds(_In_z_ wchar_t const* text, XMFLOAT2 const& p if (float(result.bottom) < maxY) result.bottom = long(maxY); - }, ignoreWhitespace); + }, + ignoreWhitespace); if (result.left == LONG_MAX) { result.left = 0; - result.top = 0; + result.top = 0; } return result; } - RECT XM_CALLCONV SpriteFont::MeasureDrawBounds(_In_z_ wchar_t const* text, FXMVECTOR position, bool ignoreWhitespace) const { XMFLOAT2 pos; @@ -611,44 +632,85 @@ RECT XM_CALLCONV SpriteFont::MeasureDrawBounds(_In_z_ wchar_t const* text, FXMVE return MeasureDrawBounds(text, pos, ignoreWhitespace); } - // UTF-8 -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, float scale, SpriteEffects effects, float layerDepth) const -{ - DrawString(spriteBatch, pImpl->ConvertUTF8(text), XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMVectorReplicate(scale), effects, layerDepth); -} - - -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects, float layerDepth) const -{ - DrawString(spriteBatch, pImpl->ConvertUTF8(text), XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMLoadFloat2(&scale), effects, layerDepth); -} - - -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, float scale, SpriteEffects effects, float layerDepth) const +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + float scale, + SpriteEffects effects, + float layerDepth) const +{ + DrawString(spriteBatch, + pImpl->ConvertUTF8(text), + XMLoadFloat2(&position), + color, + rotation, + XMLoadFloat2(&origin), + XMVectorReplicate(scale), + effects, + layerDepth); +} + +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects, + float layerDepth) const +{ + DrawString(spriteBatch, + pImpl->ConvertUTF8(text), + XMLoadFloat2(&position), + color, + rotation, + XMLoadFloat2(&origin), + XMLoadFloat2(&scale), + effects, + layerDepth); +} + +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + float scale, + SpriteEffects effects, + float layerDepth) const { DrawString(spriteBatch, pImpl->ConvertUTF8(text), position, color, rotation, origin, XMVectorReplicate(scale), effects, layerDepth); } - -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects, float layerDepth) const +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ char const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects, + float layerDepth) const { DrawString(spriteBatch, pImpl->ConvertUTF8(text), position, color, rotation, origin, scale, effects, layerDepth); } - XMVECTOR XM_CALLCONV SpriteFont::MeasureString(_In_z_ char const* text, bool ignoreWhitespace) const { return MeasureString(pImpl->ConvertUTF8(text), ignoreWhitespace); } - RECT SpriteFont::MeasureDrawBounds(_In_z_ char const* text, XMFLOAT2 const& position, bool ignoreWhitespace) const { return MeasureDrawBounds(pImpl->ConvertUTF8(text), position, ignoreWhitespace); } - RECT XM_CALLCONV SpriteFont::MeasureDrawBounds(_In_z_ char const* text, FXMVECTOR position, bool ignoreWhitespace) const { XMFLOAT2 pos; @@ -657,98 +719,140 @@ RECT XM_CALLCONV SpriteFont::MeasureDrawBounds(_In_z_ char const* text, FXMVECTO return MeasureDrawBounds(pImpl->ConvertUTF8(text), pos, ignoreWhitespace); } - // Spacing properties float SpriteFont::GetLineSpacing() const noexcept { return pImpl->lineSpacing; } - void SpriteFont::SetLineSpacing(float spacing) noexcept { pImpl->lineSpacing = spacing; } - void SpriteFont::SetPixelAlignment(bool enable) noexcept { pImpl->pixelAlignment = enable; } - // Font properties wchar_t SpriteFont::GetDefaultCharacter() const noexcept { return static_cast(pImpl->defaultGlyph ? pImpl->defaultGlyph->Character : 0); } - void SpriteFont::SetDefaultCharacter(wchar_t character) { pImpl->SetDefaultCharacter(character); } - bool SpriteFont::ContainsCharacter(wchar_t character) const { return std::binary_search(pImpl->glyphs.begin(), pImpl->glyphs.end(), character); } - // Custom layout/rendering SpriteFont::Glyph const* SpriteFont::FindGlyph(wchar_t character) const { return pImpl->FindGlyph(character); } - D3D12_GPU_DESCRIPTOR_HANDLE SpriteFont::GetSpriteSheet() const noexcept { return pImpl->texture; } - XMUINT2 SpriteFont::GetSpriteSheetSize() const noexcept { return pImpl->textureSize; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -SpriteFont::SpriteFont( - ID3D12Device* device, - ResourceUploadBatch& upload, - _In_z_ __wchar_t const* fileName, - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, - D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, - bool forceSRGB) : - SpriteFont( - device, upload, - reinterpret_cast(fileName), - cpuDescriptorDest, gpuDescriptor, forceSRGB) +SpriteFont::SpriteFont(ID3D12Device* device, + ResourceUploadBatch& upload, + _In_z_ __wchar_t const* fileName, + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, + D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor, + bool forceSRGB) + : SpriteFont(device, upload, reinterpret_cast(fileName), cpuDescriptorDest, gpuDescriptor, forceSRGB) {} -void SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, float scale, SpriteEffects effects, float layerDepth) const -{ - DrawString(spriteBatch, reinterpret_cast(text), XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMVectorReplicate(scale), effects, layerDepth); -} - -void SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects, float layerDepth) const -{ - DrawString(spriteBatch, reinterpret_cast(text), XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMLoadFloat2(&scale), effects, layerDepth); -} - -void SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, float scale, SpriteEffects effects, float layerDepth) const -{ - DrawString(spriteBatch, reinterpret_cast(text), position, color, rotation, origin, XMVectorReplicate(scale), effects, layerDepth); -} - -void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects, float layerDepth) const +void SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + float scale, + SpriteEffects effects, + float layerDepth) const +{ + DrawString(spriteBatch, + reinterpret_cast(text), + XMLoadFloat2(&position), + color, + rotation, + XMLoadFloat2(&origin), + XMVectorReplicate(scale), + effects, + layerDepth); +} + +void SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + XMFLOAT2 const& position, + FXMVECTOR color, + float rotation, + XMFLOAT2 const& origin, + XMFLOAT2 const& scale, + SpriteEffects effects, + float layerDepth) const +{ + DrawString(spriteBatch, + reinterpret_cast(text), + XMLoadFloat2(&position), + color, + rotation, + XMLoadFloat2(&origin), + XMLoadFloat2(&scale), + effects, + layerDepth); +} + +void SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + float scale, + SpriteEffects effects, + float layerDepth) const +{ + DrawString(spriteBatch, + reinterpret_cast(text), + position, + color, + rotation, + origin, + XMVectorReplicate(scale), + effects, + layerDepth); +} + +void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, + _In_z_ __wchar_t const* text, + FXMVECTOR position, + FXMVECTOR color, + float rotation, + FXMVECTOR origin, + GXMVECTOR scale, + SpriteEffects effects, + float layerDepth) const { DrawString(spriteBatch, reinterpret_cast(text), position, color, rotation, origin, scale, effects, layerDepth); } diff --git a/Src/ToneMapPostProcess.cpp b/Src/ToneMapPostProcess.cpp index 7ba4333a..3dff241c 100644 --- a/Src/ToneMapPostProcess.cpp +++ b/Src/ToneMapPostProcess.cpp @@ -26,13 +26,13 @@ using Microsoft::WRL::ComPtr; namespace { constexpr int Dirty_ConstantBuffer = 0x01; - constexpr int Dirty_Parameters = 0x02; + constexpr int Dirty_Parameters = 0x02; #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) - constexpr int PixelShaderCount = 15; + constexpr int PixelShaderCount = 15; constexpr int ShaderPermutationCount = 24; #else - constexpr int PixelShaderCount = 9; + constexpr int PixelShaderCount = 9; constexpr int ShaderPermutationCount = 12; #endif @@ -48,29 +48,53 @@ namespace static_assert((sizeof(ToneMapConstants) % 16) == 0, "CB size not padded correctly"); // HDTV to UHDTV (Rec.709 color primaries into Rec.2020) - constexpr float c_from709to2020[12] = - { - 0.6274040f, 0.3292820f, 0.0433136f, 0.f, - 0.0690970f, 0.9195400f, 0.0113612f, 0.f, - 0.0163916f, 0.0880132f, 0.8955950f, 0.f, + constexpr float c_from709to2020[12] = { + 0.6274040f, + 0.3292820f, + 0.0433136f, + 0.f, + 0.0690970f, + 0.9195400f, + 0.0113612f, + 0.f, + 0.0163916f, + 0.0880132f, + 0.8955950f, + 0.f, }; // DCI-P3-D65 https://en.wikipedia.org/wiki/DCI-P3 to UHDTV (DCI-P3-D65 color primaries into Rec.2020) - constexpr float c_fromP3D65to2020[12] = - { - 0.753845f, 0.198593f, 0.047562f, 0.f, - 0.0457456f, 0.941777f, 0.0124772f, 0.f, - -0.00121055f, 0.0176041f, 0.983607f, 0.f, + constexpr float c_fromP3D65to2020[12] = { + 0.753845f, + 0.198593f, + 0.047562f, + 0.f, + 0.0457456f, + 0.941777f, + 0.0124772f, + 0.f, + -0.00121055f, + 0.0176041f, + 0.983607f, + 0.f, }; // HDTV to DCI-P3-D65 (a.k.a. Display P3 or P3D65) - constexpr float c_from709toP3D65[12] = - { - 0.822461969f, 0.1775380f, 0.f, 0.f, - 0.033194199f, 0.9668058f, 0.f, 0.f, - 0.017082631f, 0.0723974f, 0.9105199f, 0.f, + constexpr float c_from709toP3D65[12] = { + 0.822461969f, + 0.1775380f, + 0.f, + 0.f, + 0.033194199f, + 0.9668058f, + 0.f, + 0.f, + 0.017082631f, + 0.0723974f, + 0.9105199f, + 0.f, }; -} +} // namespace #pragma region Shaders // Include the precompiled shader code. @@ -143,57 +167,54 @@ namespace #include "ToneMap_PSACESFilmic_SRGB.inc" #include "ToneMap_PSHDR10.inc" #endif -} +} // namespace namespace { - const D3D12_SHADER_BYTECODE vertexShader = - { ToneMap_VSQuad, sizeof(ToneMap_VSQuad) }; - - const D3D12_SHADER_BYTECODE pixelShaders[] = - { - { ToneMap_PSCopy, sizeof(ToneMap_PSCopy) }, - { ToneMap_PSSaturate, sizeof(ToneMap_PSSaturate) }, - { ToneMap_PSReinhard, sizeof(ToneMap_PSReinhard) }, - { ToneMap_PSACESFilmic, sizeof(ToneMap_PSACESFilmic) }, - { ToneMap_PS_SRGB, sizeof(ToneMap_PS_SRGB) }, - { ToneMap_PSSaturate_SRGB, sizeof(ToneMap_PSSaturate_SRGB) }, - { ToneMap_PSReinhard_SRGB, sizeof(ToneMap_PSReinhard_SRGB) }, - { ToneMap_PSACESFilmic_SRGB, sizeof(ToneMap_PSACESFilmic_SRGB) }, - { ToneMap_PSHDR10, sizeof(ToneMap_PSHDR10) }, + const D3D12_SHADER_BYTECODE vertexShader = { ToneMap_VSQuad, sizeof(ToneMap_VSQuad) }; + + const D3D12_SHADER_BYTECODE pixelShaders[] = { + { ToneMap_PSCopy, sizeof(ToneMap_PSCopy) }, + { ToneMap_PSSaturate, sizeof(ToneMap_PSSaturate) }, + { ToneMap_PSReinhard, sizeof(ToneMap_PSReinhard) }, + { ToneMap_PSACESFilmic, sizeof(ToneMap_PSACESFilmic) }, + { ToneMap_PS_SRGB, sizeof(ToneMap_PS_SRGB) }, + { ToneMap_PSSaturate_SRGB, sizeof(ToneMap_PSSaturate_SRGB) }, + { ToneMap_PSReinhard_SRGB, sizeof(ToneMap_PSReinhard_SRGB) }, + { ToneMap_PSACESFilmic_SRGB, sizeof(ToneMap_PSACESFilmic_SRGB) }, + { ToneMap_PSHDR10, sizeof(ToneMap_PSHDR10) }, #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) // Shaders that generate both HDR10 and GameDVR SDR signals via Multiple Render Targets. - { ToneMap_PSHDR10_Saturate, sizeof(ToneMap_PSHDR10_Saturate) }, - { ToneMap_PSHDR10_Reinhard, sizeof(ToneMap_PSHDR10_Reinhard) }, - { ToneMap_PSHDR10_ACESFilmic, sizeof(ToneMap_PSHDR10_ACESFilmic) }, - { ToneMap_PSHDR10_Saturate_SRGB, sizeof(ToneMap_PSHDR10_Saturate_SRGB) }, - { ToneMap_PSHDR10_Reinhard_SRGB, sizeof(ToneMap_PSHDR10_Reinhard_SRGB) }, - { ToneMap_PSHDR10_ACESFilmic_SRGB, sizeof(ToneMap_PSHDR10_ACESFilmic_SRGB) }, + { ToneMap_PSHDR10_Saturate, sizeof(ToneMap_PSHDR10_Saturate) }, + { ToneMap_PSHDR10_Reinhard, sizeof(ToneMap_PSHDR10_Reinhard) }, + { ToneMap_PSHDR10_ACESFilmic, sizeof(ToneMap_PSHDR10_ACESFilmic) }, + { ToneMap_PSHDR10_Saturate_SRGB, sizeof(ToneMap_PSHDR10_Saturate_SRGB) }, + { ToneMap_PSHDR10_Reinhard_SRGB, sizeof(ToneMap_PSHDR10_Reinhard_SRGB) }, + { ToneMap_PSHDR10_ACESFilmic_SRGB, sizeof(ToneMap_PSHDR10_ACESFilmic_SRGB) }, #endif }; static_assert(static_cast(std::size(pixelShaders)) == PixelShaderCount, "array/max mismatch"); - const int pixelShaderIndices[] = - { + const int pixelShaderIndices[] = { // Linear EOTF - 0, // Copy - 1, // Saturate - 2, // Reinhard - 3, // ACES Filmic + 0, // Copy + 1, // Saturate + 2, // Reinhard + 3, // ACES Filmic // Gamam22 EOTF - 4, // SRGB - 5, // Saturate_SRGB - 6, // Reinhard_SRGB - 7, // ACES Filmic + 4, // SRGB + 5, // Saturate_SRGB + 6, // Reinhard_SRGB + 7, // ACES Filmic // ST.2084 EOTF - 8, // HDR10 - 8, // HDR10 - 8, // HDR10 - 8, // HDR10 + 8, // HDR10 + 8, // HDR10 + 8, // HDR10 + 8, // HDR10 #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) // MRT Linear EOTF @@ -206,7 +227,7 @@ namespace 12, // HDR10+Saturate_SRGB 12, // HDR10+Saturate_SRGB 13, // HDR10+Reinhard_SRGB - 14, // HDR10+ACESFilmic + 14, // HDR10+ACESFilmic // MRT ST.2084 EOTF 9, // HDR10+Saturate @@ -226,15 +247,17 @@ namespace : mDevice(device) {} - DeviceResources(const DeviceResources&) = delete; + DeviceResources(const DeviceResources&) = delete; DeviceResources& operator=(const DeviceResources&) = delete; - DeviceResources(DeviceResources&&) = delete; + DeviceResources(DeviceResources&&) = delete; DeviceResources& operator=(DeviceResources&&) = delete; ID3D12RootSignature* GetRootSignature(const D3D12_ROOT_SIGNATURE_DESC& desc) { - return DemandCreate(mRootSignature, mMutex, [&](ID3D12RootSignature** pResult) noexcept -> HRESULT + return DemandCreate(mRootSignature, + mMutex, + [&](ID3D12RootSignature** pResult) noexcept -> HRESULT { HRESULT hr = CreateRootSignature(mDevice.Get(), &desc, pResult); @@ -252,7 +275,7 @@ namespace ComPtr mRootSignature; std::mutex mMutex; }; -} +} // namespace #pragma endregion class ToneMapPostProcess::Impl : public AlignedNew @@ -260,10 +283,10 @@ class ToneMapPostProcess::Impl : public AlignedNew public: Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, Operator op, TransferFunction func, bool mrt = false); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; void Process(_In_ ID3D12GraphicsCommandList* commandList); @@ -278,13 +301,13 @@ class ToneMapPostProcess::Impl : public AlignedNew }; // Fields. - ToneMapConstants constants; - D3D12_GPU_DESCRIPTOR_HANDLE texture; - float linearExposure; - float paperWhiteNits; + ToneMapConstants constants; + D3D12_GPU_DESCRIPTOR_HANDLE texture; + float linearExposure; + float paperWhiteNits; private: - int mDirtyFlags; + int mDirtyFlags; // D3D constant buffer holds a copy of the same data as the public 'constants' field. GraphicsResource mConstantBuffer; @@ -301,18 +324,16 @@ class ToneMapPostProcess::Impl : public AlignedNew static SharedResourcePool deviceResourcesPool; }; - // Global pool of per-device ToneMapPostProcess resources. SharedResourcePool ToneMapPostProcess::Impl::deviceResourcesPool; - // Constructor. ToneMapPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& rtState, Operator op, TransferFunction func, bool mrt) : constants{}, - texture{}, - linearExposure(1.f), - paperWhiteNits(200.f), - mDirtyFlags(INT_MAX) + texture{}, + linearExposure(1.f), + paperWhiteNits(200.f), + mDirtyFlags(INT_MAX) { if (op >= Operator_Max) throw std::invalid_argument("Tonemap operator not defined"); @@ -327,22 +348,18 @@ ToneMapPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetStat // Create root signature. { - ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = - D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS - #ifdef _GAMING_XBOX_SCARLETT - | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS - | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS - #endif + ENUM_FLAGS_CONSTEXPR D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags + = D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS + | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS +#ifdef _GAMING_XBOX_SCARLETT + | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS +#endif ; const CD3DX12_DESCRIPTOR_RANGE textureSRVs(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); // Same as CommonStates::StaticPointClamp - const CD3DX12_STATIC_SAMPLER_DESC sampler( - 0, // register + const CD3DX12_STATIC_SAMPLER_DESC sampler(0, // register D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -397,19 +414,13 @@ ToneMapPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetStat rtState, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE); - psd.CreatePipelineState( - device, - mRootSignature, - vertexShader, - pixelShaders[shaderIndex], - mPipelineState.GetAddressOf()); + psd.CreatePipelineState(device, mRootSignature, vertexShader, pixelShaders[shaderIndex], mPipelineState.GetAddressOf()); memcpy(constants.colorRotation, c_from709to2020, sizeof(c_from709to2020)); SetDebugObjectName(mPipelineState.Get(), L"ToneMapPostProcess"); } - // Sets our state onto the D3D device. void ToneMapPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList) { @@ -449,10 +460,13 @@ void ToneMapPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandLi commandList->DrawInstanced(3, 1, 0, 0); } - // Public constructor. #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) -ToneMapPostProcess::ToneMapPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Operator op, TransferFunction func, bool mrt) +ToneMapPostProcess::ToneMapPostProcess(_In_ ID3D12Device* device, + const RenderTargetState& rtState, + Operator op, + TransferFunction func, + bool mrt) : pImpl(std::make_unique(device, rtState, op, func, mrt)) #else ToneMapPostProcess::ToneMapPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Operator op, TransferFunction func) @@ -460,11 +474,9 @@ ToneMapPostProcess::ToneMapPostProcess(_In_ ID3D12Device* device, const RenderTa #endif {} - -ToneMapPostProcess::ToneMapPostProcess(ToneMapPostProcess&&) noexcept = default; -ToneMapPostProcess& ToneMapPostProcess::operator= (ToneMapPostProcess&&) noexcept = default; -ToneMapPostProcess::~ToneMapPostProcess() = default; - +ToneMapPostProcess::ToneMapPostProcess(ToneMapPostProcess&&) noexcept = default; +ToneMapPostProcess& ToneMapPostProcess::operator=(ToneMapPostProcess&&) noexcept = default; +ToneMapPostProcess::~ToneMapPostProcess() = default; // IPostProcess methods. void ToneMapPostProcess::Process(_In_ ID3D12GraphicsCommandList* commandList) @@ -472,44 +484,39 @@ void ToneMapPostProcess::Process(_In_ ID3D12GraphicsCommandList* commandList) pImpl->Process(commandList); } - // Properties void ToneMapPostProcess::SetHDRSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor) { pImpl->texture = srvDescriptor; } - void ToneMapPostProcess::SetColorRotation(ColorPrimaryRotation value) { switch (value) { - case DCI_P3_D65_to_UHDTV: memcpy(pImpl->constants.colorRotation, c_fromP3D65to2020, sizeof(c_fromP3D65to2020)); break; - case HDTV_to_DCI_P3_D65: memcpy(pImpl->constants.colorRotation, c_from709toP3D65, sizeof(c_from709toP3D65)); break; - default: memcpy(pImpl->constants.colorRotation, c_from709to2020, sizeof(c_from709to2020)); break; + case DCI_P3_D65_to_UHDTV: memcpy(pImpl->constants.colorRotation, c_fromP3D65to2020, sizeof(c_fromP3D65to2020)); break; + case HDTV_to_DCI_P3_D65: memcpy(pImpl->constants.colorRotation, c_from709toP3D65, sizeof(c_from709toP3D65)); break; + default: memcpy(pImpl->constants.colorRotation, c_from709to2020, sizeof(c_from709to2020)); break; } pImpl->SetDirtyFlag(); } - void ToneMapPostProcess::SetColorRotation(CXMMATRIX value) { - const XMMATRIX transpose = XMMatrixTranspose(value); + const XMMATRIX transpose = XMMatrixTranspose(value); pImpl->constants.colorRotation[0] = transpose.r[0]; pImpl->constants.colorRotation[1] = transpose.r[1]; pImpl->constants.colorRotation[2] = transpose.r[2]; pImpl->SetDirtyFlag(); } - void ToneMapPostProcess::SetExposure(float exposureValue) { pImpl->linearExposure = powf(2.f, exposureValue); pImpl->SetDirtyFlag(); } - void ToneMapPostProcess::SetST2084Parameter(float paperWhiteNits) { pImpl->paperWhiteNits = paperWhiteNits; diff --git a/Src/VertexTypes.cpp b/Src/VertexTypes.cpp index f413305e..63ba5ebb 100644 --- a/Src/VertexTypes.cpp +++ b/Src/VertexTypes.cpp @@ -14,153 +14,115 @@ using namespace DirectX; //-------------------------------------------------------------------------------------- // Vertex struct holding position information. -const D3D12_INPUT_ELEMENT_DESC VertexPosition::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPosition::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPosition) == 12, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPosition::InputLayout = -{ - VertexPosition::InputElements, - VertexPosition::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPosition::InputLayout = { VertexPosition::InputElements, VertexPosition::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position and color information. -const D3D12_INPUT_ELEMENT_DESC VertexPositionColor::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionColor::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionColor) == 28, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionColor::InputLayout = -{ - VertexPositionColor::InputElements, - VertexPositionColor::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPositionColor::InputLayout + = { VertexPositionColor::InputElements, VertexPositionColor::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position and texture mapping information. -const D3D12_INPUT_ELEMENT_DESC VertexPositionTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionTexture) == 20, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionTexture::InputLayout = -{ - VertexPositionTexture::InputElements, - VertexPositionTexture::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPositionTexture::InputLayout + = { VertexPositionTexture::InputElements, VertexPositionTexture::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position and dual texture mapping information. -const D3D12_INPUT_ELEMENT_DESC VertexPositionDualTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionDualTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionDualTexture) == 28, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionDualTexture::InputLayout = -{ - VertexPositionDualTexture::InputElements, - VertexPositionDualTexture::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPositionDualTexture::InputLayout + = { VertexPositionDualTexture::InputElements, VertexPositionDualTexture::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position and normal vector. -const D3D12_INPUT_ELEMENT_DESC VertexPositionNormal::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionNormal::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormal) == 24, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionNormal::InputLayout = -{ - VertexPositionNormal::InputElements, - VertexPositionNormal::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPositionNormal::InputLayout + = { VertexPositionNormal::InputElements, VertexPositionNormal::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position, color, and texture mapping information. -const D3D12_INPUT_ELEMENT_DESC VertexPositionColorTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionColorTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionColorTexture) == 36, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionColorTexture::InputLayout = -{ - VertexPositionColorTexture::InputElements, - VertexPositionColorTexture::InputElementCount -}; - +const D3D12_INPUT_LAYOUT_DESC VertexPositionColorTexture::InputLayout + = { VertexPositionColorTexture::InputElements, VertexPositionColorTexture::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position, normal vector, and color information. -const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalColor::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalColor::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalColor) == 40, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalColor::InputLayout = -{ - VertexPositionNormalColor::InputElements, - VertexPositionNormalColor::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalColor::InputLayout + = { VertexPositionNormalColor::InputElements, VertexPositionNormalColor::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position, normal vector, and texture mapping information. -const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalTexture) == 32, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalTexture::InputLayout = -{ - VertexPositionNormalTexture::InputElements, - VertexPositionNormalTexture::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalTexture::InputLayout + = { VertexPositionNormalTexture::InputElements, VertexPositionNormalTexture::InputElementCount }; //-------------------------------------------------------------------------------------- // Vertex struct holding position, normal vector, color, and texture mapping information. -const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalColorTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, +const D3D12_INPUT_ELEMENT_DESC VertexPositionNormalColorTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalColorTexture) == 48, "Vertex struct/layout mismatch"); -const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalColorTexture::InputLayout = -{ - VertexPositionNormalColorTexture::InputElements, - VertexPositionNormalColorTexture::InputElementCount -}; +const D3D12_INPUT_LAYOUT_DESC VertexPositionNormalColorTexture::InputLayout + = { VertexPositionNormalColorTexture::InputElements, VertexPositionNormalColorTexture::InputElementCount }; //-------------------------------------------------------------------------------------- // VertexPositionNormalTangentColorTexture, VertexPositionNormalTangentColorTextureSkinning are not diff --git a/Src/WICTextureLoader.cpp b/Src/WICTextureLoader.cpp index fd820964..7e52d921 100644 --- a/Src/WICTextureLoader.cpp +++ b/Src/WICTextureLoader.cpp @@ -39,17 +39,17 @@ namespace //------------------------------------------------------------------------------------- struct WICTranslate { - const GUID& wic; - DXGI_FORMAT format; + const GUID& wic; + DXGI_FORMAT format; - constexpr WICTranslate(const GUID& wg, DXGI_FORMAT fmt) noexcept : - wic(wg), - format(fmt) + constexpr WICTranslate(const GUID& wg, DXGI_FORMAT fmt) noexcept + : wic(wg), + format(fmt) {} }; - constexpr WICTranslate g_WICFormats[] = - { + constexpr WICTranslate g_WICFormats[] = { + // clang-format off { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, @@ -73,6 +73,7 @@ namespace { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, { GUID_WICPixelFormat96bppRGBFloat, DXGI_FORMAT_R32G32B32_FLOAT }, + // clang-format on }; //------------------------------------------------------------------------------------- @@ -84,14 +85,14 @@ namespace const GUID& source; const GUID& target; - constexpr WICConvert(const GUID& src, const GUID& tgt) noexcept : - source(src), - target(tgt) + constexpr WICConvert(const GUID& src, const GUID& tgt) noexcept + : source(src), + target(tgt) {} }; - constexpr WICConvert g_WICConvert[] = - { + constexpr WICConvert g_WICConvert[] = { + // clang-format off // Note target GUID in this conversion table must be one of those directly supported formats (above). { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM @@ -148,18 +149,17 @@ namespace { GUID_WICPixelFormat96bppRGBFixedPoint, GUID_WICPixelFormat96bppRGBFloat }, // DXGI_FORMAT_R32G32B32_FLOAT // We don't support n-channel formats + // clang-format on }; - BOOL WINAPI InitializeWICFactory(PINIT_ONCE, PVOID, PVOID *ifactory) noexcept + BOOL WINAPI InitializeWICFactory(PINIT_ONCE, PVOID, PVOID* ifactory) noexcept { - return SUCCEEDED(CoCreateInstance( - CLSID_WICImagingFactory2, - nullptr, - CLSCTX_INPROC_SERVER, - __uuidof(IWICImagingFactory2), - ifactory)) ? TRUE : FALSE; + return SUCCEEDED( + CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory2), ifactory)) ? + TRUE : + FALSE; } -} +} // namespace //-------------------------------------------------------------------------------------- namespace DirectX @@ -170,20 +170,16 @@ namespace DirectX { IWICImagingFactory2* GetWIC() noexcept; // Also used by ScreenGrab - } - } -} + } // namespace ToolKitInternal + } // namespace DX12 +} // namespace DirectX IWICImagingFactory2* DirectX::DX12::ToolKitInternal::GetWIC() noexcept { static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; IWICImagingFactory2* factory = nullptr; - if (!InitOnceExecuteOnce( - &s_initOnce, - InitializeWICFactory, - nullptr, - reinterpret_cast(&factory))) + if (!InitOnceExecuteOnce(&s_initOnce, InitializeWICFactory, nullptr, reinterpret_cast(&factory))) { return nullptr; } @@ -238,15 +234,15 @@ namespace //--------------------------------------------------------------------------------- HRESULT CreateTextureFromWIC(_In_ ID3D12Device* device, - _In_ IWICBitmapFrameDecode *frame, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource) noexcept + _In_ IWICBitmapFrameDecode* frame, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource) noexcept { - UINT width, height; + UINT width, height; HRESULT hr = frame->GetSize(&width, &height); if (FAILED(hr)) return hr; @@ -261,7 +257,7 @@ namespace maxsize = size_t(D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); } - UINT twidth = width; + UINT twidth = width; UINT theight = height; if (loadFlags & WIC_LOADER_FIT_POW2) { @@ -272,20 +268,20 @@ namespace const float ar = static_cast(height) / static_cast(width); if (width > height) { - twidth = static_cast(maxsize); + twidth = static_cast(maxsize); theight = std::max(1, static_cast(static_cast(maxsize) * ar)); } else { theight = static_cast(maxsize); - twidth = std::max(1, static_cast(static_cast(maxsize) / ar)); + twidth = std::max(1, static_cast(static_cast(maxsize) / ar)); } assert(twidth <= maxsize && theight <= maxsize); } if (loadFlags & WIC_LOADER_MAKE_SQUARE) { - twidth = std::max(twidth, theight); + twidth = std::max(twidth, theight); theight = twidth; } @@ -318,10 +314,20 @@ namespace if (format == DXGI_FORMAT_UNKNOWN) { - DebugTrace("ERROR: WICTextureLoader does not support all DXGI formats (WIC GUID {%8.8lX-%4.4X-%4.4X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X}). Consider using DirectXTex.\n", - pixelFormat.Data1, pixelFormat.Data2, pixelFormat.Data3, - pixelFormat.Data4[0], pixelFormat.Data4[1], pixelFormat.Data4[2], pixelFormat.Data4[3], - pixelFormat.Data4[4], pixelFormat.Data4[5], pixelFormat.Data4[6], pixelFormat.Data4[7]); + DebugTrace( + "ERROR: WICTextureLoader does not support all DXGI formats (WIC GUID " + "{%8.8lX-%4.4X-%4.4X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X}). Consider using DirectXTex.\n", + pixelFormat.Data1, + pixelFormat.Data2, + pixelFormat.Data3, + pixelFormat.Data4[0], + pixelFormat.Data4[1], + pixelFormat.Data4[2], + pixelFormat.Data4[3], + pixelFormat.Data4[4], + pixelFormat.Data4[5], + pixelFormat.Data4[6], + pixelFormat.Data4[7]); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } @@ -334,7 +340,7 @@ namespace { memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat32bppRGBA, sizeof(GUID)); format = DXGI_FORMAT_R8G8B8A8_UNORM; - bpp = 32; + bpp = 32; } if (!bpp) @@ -375,7 +381,7 @@ namespace sRGB = (loadFlags & WIC_LOADER_SRGB_DEFAULT) != 0; } } - #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) else if (memcmp(&containerFormat, &GUID_ContainerFormatJpeg, sizeof(GUID)) == 0) { if (SUCCEEDED(metareader->GetMetadataByName(L"/app1/ifd/exif/{ushort=40961}", &value)) && value.vt == VT_UI2) @@ -398,7 +404,7 @@ namespace sRGB = (loadFlags & WIC_LOADER_SRGB_DEFAULT) != 0; } } - #else +#else else if (SUCCEEDED(metareader->GetMetadataByName(L"System.Image.ColorSpace", &value)) && value.vt == VT_UI2) { sRGB = (value.uiVal == 1); @@ -407,7 +413,7 @@ namespace { sRGB = (loadFlags & WIC_LOADER_SRGB_DEFAULT) != 0; } - #endif +#endif std::ignore = PropVariantClear(&value); @@ -424,7 +430,7 @@ namespace if (rowBytes > UINT32_MAX || numBytes > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); - const auto rowPitch = static_cast(rowBytes); + const auto rowPitch = static_cast(rowBytes); const auto imageSize = static_cast(numBytes); decodedData.reset(new (std::nothrow) uint8_t[imageSize]); @@ -432,9 +438,7 @@ namespace return E_OUTOFMEMORY; // Load image data - if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0 - && twidth == width - && theight == height) + if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0 && twidth == width && theight == height) { // No format conversion or resize needed hr = frame->CopyPixels(nullptr, static_cast(rowPitch), static_cast(imageSize), decodedData.get()); @@ -477,13 +481,18 @@ namespace return hr; BOOL canConvert = FALSE; - hr = FC->CanConvert(pfScaler, convertGUID, &canConvert); + hr = FC->CanConvert(pfScaler, convertGUID, &canConvert); if (FAILED(hr) || !canConvert) { return E_UNEXPECTED; } - hr = FC->Initialize(scaler.Get(), convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); + hr = FC->Initialize(scaler.Get(), + convertGUID, + WICBitmapDitherTypeErrorDiffusion, + nullptr, + 0, + WICBitmapPaletteTypeMedianCut); if (FAILED(hr)) return hr; @@ -505,7 +514,7 @@ namespace return hr; BOOL canConvert = FALSE; - hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert); + hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert); if (FAILED(hr) || !canConvert) { return E_UNEXPECTED; @@ -521,26 +530,25 @@ namespace } // Count the number of mips - const uint32_t mipCount = (loadFlags & (WIC_LOADER_MIP_AUTOGEN | WIC_LOADER_MIP_RESERVE)) - ? LoaderHelpers::CountMips(twidth, theight) : 1u; + const uint32_t mipCount + = (loadFlags & (WIC_LOADER_MIP_AUTOGEN | WIC_LOADER_MIP_RESERVE)) ? LoaderHelpers::CountMips(twidth, theight) : 1u; // Create texture D3D12_RESOURCE_DESC desc = {}; - desc.Width = twidth; - desc.Height = theight; - desc.MipLevels = static_cast(mipCount); - desc.DepthOrArraySize = 1; - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - desc.Flags = resFlags; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = twidth; + desc.Height = theight; + desc.MipLevels = static_cast(mipCount); + desc.DepthOrArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Flags = resFlags; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; const CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT); ID3D12Resource* tex = nullptr; - hr = device->CreateCommittedResource( - &defaultHeapProperties, + hr = device->CreateCommittedResource(&defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &desc, c_initialCopyTargetState, @@ -554,8 +562,8 @@ namespace _Analysis_assume_(tex != nullptr); - subresource.pData = decodedData.get(); - subresource.RowPitch = static_cast(rowPitch); + subresource.pData = decodedData.get(); + subresource.RowPitch = static_cast(rowPitch); subresource.SlicePitch = static_cast(imageSize); *texture = tex; @@ -563,11 +571,9 @@ namespace } //-------------------------------------------------------------------------------------- - void SetDebugTextureInfo( - _In_z_ const wchar_t* fileName, - _In_ ID3D12Resource* texture) noexcept + void SetDebugTextureInfo(_In_z_ const wchar_t* fileName, _In_ ID3D12Resource* texture) noexcept { - #if !defined(NO_D3D12_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D12_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) const wchar_t* pstrName = wcsrchr(fileName, '\\'); if (!pstrName) { @@ -578,10 +584,10 @@ namespace pstrName++; } texture->SetName(pstrName); - #else +#else UNREFERENCED_PARAMETER(fileName); UNREFERENCED_PARAMETER(texture); - #endif +#endif } //-------------------------------------------------------------------------------------- @@ -607,20 +613,16 @@ namespace } } // anonymous namespace - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWICTextureFromMemory( - ID3D12Device* device, - const uint8_t* wicData, - size_t wicDataSize, - ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource, - size_t maxsize) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWICTextureFromMemory(ID3D12Device* device, + const uint8_t* wicData, + size_t wicDataSize, + ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource, + size_t maxsize) noexcept { - return LoadWICTextureFromMemoryEx( - device, + return LoadWICTextureFromMemoryEx(device, wicData, wicDataSize, maxsize, @@ -631,18 +633,15 @@ HRESULT DirectX::LoadWICTextureFromMemory( subresource); } -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromMemory( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const uint8_t* wicData, - size_t wicDataSize, - ID3D12Resource** texture, - bool generateMips, - size_t maxsize) +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemory(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const uint8_t* wicData, + size_t wicDataSize, + ID3D12Resource** texture, + bool generateMips, + size_t maxsize) { - return CreateWICTextureFromMemoryEx( - device, + return CreateWICTextureFromMemoryEx(device, resourceUpload, wicData, wicDataSize, @@ -652,19 +651,16 @@ HRESULT DirectX::CreateWICTextureFromMemory( texture); } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWICTextureFromMemoryEx( - ID3D12Device* device, - const uint8_t* wicData, - size_t wicDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWICTextureFromMemoryEx(ID3D12Device* device, + const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource) noexcept { if (texture) { @@ -686,7 +682,7 @@ HRESULT DirectX::LoadWICTextureFromMemoryEx( // Create input stream for memory ComPtr stream; - HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); + HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); if (FAILED(hr)) return hr; @@ -705,10 +701,7 @@ HRESULT DirectX::LoadWICTextureFromMemoryEx( if (FAILED(hr)) return hr; - hr = CreateTextureFromWIC(device, - frame.Get(), maxsize, - resFlags, loadFlags, - texture, decodedData, subresource); + hr = CreateTextureFromWIC(device, frame.Get(), maxsize, resFlags, loadFlags, texture, decodedData, subresource); if (FAILED(hr)) return hr; @@ -718,16 +711,14 @@ HRESULT DirectX::LoadWICTextureFromMemoryEx( return hr; } -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromMemoryEx( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const uint8_t* wicData, - size_t wicDataSize, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D12Resource** texture) +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D12Resource** texture) { if (texture) { @@ -749,7 +740,7 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( // Create input stream for memory ComPtr stream; - HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); + HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); if (FAILED(hr)) return hr; @@ -773,17 +764,15 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( const DXGI_FORMAT fmt = GetPixelFormat(frame.Get()); if (!resourceUpload.IsSupportedForGenerateMips(fmt)) { - DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", static_cast(fmt)); + DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", + static_cast(fmt)); loadFlags &= ~WIC_LOADER_MIP_AUTOGEN; } } std::unique_ptr decodedData; - D3D12_SUBRESOURCE_DATA initData; - hr = CreateTextureFromWIC(device, - frame.Get(), maxsize, - resFlags, loadFlags, - texture, decodedData, initData); + D3D12_SUBRESOURCE_DATA initData; + hr = CreateTextureFromWIC(device, frame.Get(), maxsize, resFlags, loadFlags, texture, decodedData, initData); if (SUCCEEDED(hr)) { @@ -791,16 +780,9 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( _Analysis_assume_(texture != nullptr && *texture != nullptr); SetDebugObjectName(*texture, L"WICTextureLoader"); - resourceUpload.Upload( - *texture, - 0, - &initData, - 1); + resourceUpload.Upload(*texture, 0, &initData, 1); - resourceUpload.Transition( - *texture, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + resourceUpload.Transition(*texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); // Generate mips? if (loadFlags & WIC_LOADER_MIP_AUTOGEN) @@ -812,39 +794,25 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( return hr; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWICTextureFromFile( - ID3D12Device* device, - const wchar_t* fileName, - ID3D12Resource** texture, - std::unique_ptr& wicData, - D3D12_SUBRESOURCE_DATA& subresource, - size_t maxsize) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWICTextureFromFile(ID3D12Device* device, + const wchar_t* fileName, + ID3D12Resource** texture, + std::unique_ptr& wicData, + D3D12_SUBRESOURCE_DATA& subresource, + size_t maxsize) noexcept { - return LoadWICTextureFromFileEx( - device, - fileName, - maxsize, - D3D12_RESOURCE_FLAG_NONE, - WIC_LOADER_DEFAULT, - texture, - wicData, - subresource); + return LoadWICTextureFromFileEx(device, fileName, maxsize, D3D12_RESOURCE_FLAG_NONE, WIC_LOADER_DEFAULT, texture, wicData, subresource); } -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromFile( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const wchar_t* fileName, - ID3D12Resource** texture, - bool generateMips, - size_t maxsize) +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFile(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const wchar_t* fileName, + ID3D12Resource** texture, + bool generateMips, + size_t maxsize) { - return CreateWICTextureFromFileEx( - device, + return CreateWICTextureFromFileEx(device, resourceUpload, fileName, maxsize, @@ -853,18 +821,15 @@ HRESULT DirectX::CreateWICTextureFromFile( texture); } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::LoadWICTextureFromFileEx( - ID3D12Device* device, - const wchar_t* fileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource) noexcept +_Use_decl_annotations_ HRESULT DirectX::LoadWICTextureFromFileEx(ID3D12Device* device, + const wchar_t* fileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource) noexcept { if (texture) { @@ -880,11 +845,7 @@ HRESULT DirectX::LoadWICTextureFromFileEx( // Initialize WIC ComPtr decoder; - HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, - nullptr, - GENERIC_READ, - WICDecodeMetadataCacheOnDemand, - decoder.GetAddressOf()); + HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); if (FAILED(hr)) return hr; @@ -893,9 +854,7 @@ HRESULT DirectX::LoadWICTextureFromFileEx( if (FAILED(hr)) return hr; - hr = CreateTextureFromWIC(device, frame.Get(), maxsize, - resFlags, loadFlags, - texture, decodedData, subresource); + hr = CreateTextureFromWIC(device, frame.Get(), maxsize, resFlags, loadFlags, texture, decodedData, subresource); if (SUCCEEDED(hr)) { @@ -905,15 +864,13 @@ HRESULT DirectX::LoadWICTextureFromFileEx( return hr; } -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromFileEx( - ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - const wchar_t* fileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D12Resource** texture) +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFileEx(ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + const wchar_t* fileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D12Resource** texture) { if (texture) { @@ -929,11 +886,7 @@ HRESULT DirectX::CreateWICTextureFromFileEx( // Initialize WIC ComPtr decoder; - HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, - nullptr, - GENERIC_READ, - WICDecodeMetadataCacheOnDemand, - decoder.GetAddressOf()); + HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); if (FAILED(hr)) return hr; @@ -947,31 +900,23 @@ HRESULT DirectX::CreateWICTextureFromFileEx( const DXGI_FORMAT fmt = GetPixelFormat(frame.Get()); if (!resourceUpload.IsSupportedForGenerateMips(fmt)) { - DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", static_cast(fmt)); + DebugTrace("WARNING: Autogen of mips ignored (device doesn't support this format (%d) or trying to use a copy queue)\n", + static_cast(fmt)); loadFlags &= ~WIC_LOADER_MIP_AUTOGEN; } } std::unique_ptr decodedData; - D3D12_SUBRESOURCE_DATA initData; - hr = CreateTextureFromWIC(device, frame.Get(), maxsize, - resFlags, loadFlags, - texture, decodedData, initData); + D3D12_SUBRESOURCE_DATA initData; + hr = CreateTextureFromWIC(device, frame.Get(), maxsize, resFlags, loadFlags, texture, decodedData, initData); if (SUCCEEDED(hr)) { SetDebugTextureInfo(fileName, *texture); - resourceUpload.Upload( - *texture, - 0, - &initData, - 1); + resourceUpload.Upload(*texture, 0, &initData, 1); - resourceUpload.Transition( - *texture, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + resourceUpload.Transition(*texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); // Generate mips? if (loadFlags & WIC_LOADER_MIP_AUTOGEN) @@ -983,7 +928,6 @@ HRESULT DirectX::CreateWICTextureFromFileEx( return hr; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients @@ -991,60 +935,71 @@ HRESULT DirectX::CreateWICTextureFromFileEx( namespace DirectX { - HRESULT __cdecl LoadWICTextureFromFile( - _In_ ID3D12Device* device, - _In_z_ const __wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource, - size_t maxsize) noexcept + HRESULT __cdecl LoadWICTextureFromFile(_In_ ID3D12Device* device, + _In_z_ const __wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource, + size_t maxsize) noexcept { return LoadWICTextureFromFile(device, reinterpret_cast(szFileName), - texture, decodedData, subresource, maxsize); + texture, + decodedData, + subresource, + maxsize); } - HRESULT __cdecl CreateWICTextureFromFile( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const __wchar_t* szFileName, - _Outptr_ ID3D12Resource** texture, - bool generateMips, - size_t maxsize) + HRESULT __cdecl CreateWICTextureFromFile(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const __wchar_t* szFileName, + _Outptr_ ID3D12Resource** texture, + bool generateMips, + size_t maxsize) { - return CreateWICTextureFromFile(device, resourceUpload, + return CreateWICTextureFromFile(device, + resourceUpload, reinterpret_cast(szFileName), - texture, generateMips, maxsize); + texture, + generateMips, + maxsize); } - HRESULT __cdecl LoadWICTextureFromFileEx( - _In_ ID3D12Device* device, - _In_z_ const __wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture, - std::unique_ptr& decodedData, - D3D12_SUBRESOURCE_DATA& subresource) noexcept + HRESULT __cdecl LoadWICTextureFromFileEx(_In_ ID3D12Device* device, + _In_z_ const __wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture, + std::unique_ptr& decodedData, + D3D12_SUBRESOURCE_DATA& subresource) noexcept { return LoadWICTextureFromFileEx(device, reinterpret_cast(szFileName), - maxsize, resFlags, loadFlags, texture, decodedData, subresource); + maxsize, + resFlags, + loadFlags, + texture, + decodedData, + subresource); } - HRESULT __cdecl CreateWICTextureFromFileEx( - _In_ ID3D12Device* device, - ResourceUploadBatch& resourceUpload, - _In_z_ const __wchar_t* szFileName, - size_t maxsize, - D3D12_RESOURCE_FLAGS resFlags, - WIC_LOADER_FLAGS loadFlags, - _Outptr_ ID3D12Resource** texture) + HRESULT __cdecl CreateWICTextureFromFileEx(_In_ ID3D12Device* device, + ResourceUploadBatch& resourceUpload, + _In_z_ const __wchar_t* szFileName, + size_t maxsize, + D3D12_RESOURCE_FLAGS resFlags, + WIC_LOADER_FLAGS loadFlags, + _Outptr_ ID3D12Resource** texture) { - return CreateWICTextureFromFileEx(device, resourceUpload, + return CreateWICTextureFromFileEx(device, + resourceUpload, reinterpret_cast(szFileName), - maxsize, resFlags, loadFlags, texture); + maxsize, + resFlags, + loadFlags, + texture); } -} +} // namespace DirectX #endif // !_NATIVE_WCHAR_T_DEFINED diff --git a/Src/XboxDDSTextureLoader.cpp b/Src/XboxDDSTextureLoader.cpp index 111393af..460be806 100644 --- a/Src/XboxDDSTextureLoader.cpp +++ b/Src/XboxDDSTextureLoader.cpp @@ -34,23 +34,23 @@ namespace //-------------------------------------------------------------------------------------- // Default XMemAlloc attributes for texture loading //-------------------------------------------------------------------------------------- - const uint64_t c_XMemAllocAttributes = MAKE_XALLOC_ATTRIBUTES( - eXALLOCAllocatorId_MiddlewareReservedMin, + const uint64_t c_XMemAllocAttributes = MAKE_XALLOC_ATTRIBUTES(eXALLOCAllocatorId_MiddlewareReservedMin, 0, XALLOC_MEMTYPE_GRAPHICS_WRITECOMBINE_GPU_READONLY, XALLOC_PAGESIZE_64KB, XALLOC_ALIGNMENT_64K - #ifdef _GAMING_XBOX - , 0 - #endif +#ifdef _GAMING_XBOX + , + 0 +#endif ); -//-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- HRESULT LoadTextureDataFromFile(_In_z_ const wchar_t* fileName, - std::unique_ptr& ddsData, - DDS_HEADER** header, - uint8_t** bitData, - size_t* bitSize) noexcept + std::unique_ptr& ddsData, + DDS_HEADER** header, + uint8_t** bitData, + size_t* bitSize) noexcept { if (!header || !bitData || !bitSize) { @@ -58,10 +58,7 @@ namespace } // open the file - ScopedHandle hFile(safe_handle(CreateFile2( - fileName, - GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, - nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); if (!hFile) { @@ -96,12 +93,7 @@ namespace // read the data in DWORD BytesRead = 0; - if (!ReadFile(hFile.get(), - ddsData.get(), - fileInfo.EndOfFile.LowPart, - &BytesRead, - nullptr - )) + if (!ReadFile(hFile.get(), ddsData.get(), fileInfo.EndOfFile.LowPart, &BytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } @@ -121,15 +113,13 @@ namespace auto hdr = reinterpret_cast(ddsData.get() + sizeof(uint32_t)); // Verify header to validate DDS file - if (hdr->size != sizeof(DDS_HEADER) || - hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) + if (hdr->size != sizeof(DDS_HEADER) || hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) { return E_FAIL; } // Check for XBOX extension - if (!(hdr->ddspf.flags & DDS_FOURCC) - || (MAKEFOURCC('X', 'B', 'O', 'X') != hdr->ddspf.fourCC)) + if (!(hdr->ddspf.flags & DDS_FOURCC) || (MAKEFOURCC('X', 'B', 'O', 'X') != hdr->ddspf.fourCC)) { // Use standard DDSTextureLoader instead return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -142,10 +132,10 @@ namespace } // setup the pointers in the process request - *header = hdr; + *header = hdr; auto offset = DDS_XBOX_HEADER_SIZE; - *bitData = ddsData.get() + offset; - *bitSize = fileInfo.EndOfFile.LowPart - offset; + *bitData = ddsData.get() + offset; + *bitSize = fileInfo.EndOfFile.LowPart - offset; return S_OK; } @@ -155,43 +145,35 @@ namespace { switch (format) { - case DXGI_FORMAT_R8G8B8A8_UNORM: - return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + case DXGI_FORMAT_R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - case DXGI_FORMAT_BC1_UNORM: - return DXGI_FORMAT_BC1_UNORM_SRGB; + case DXGI_FORMAT_BC1_UNORM: return DXGI_FORMAT_BC1_UNORM_SRGB; - case DXGI_FORMAT_BC2_UNORM: - return DXGI_FORMAT_BC2_UNORM_SRGB; + case DXGI_FORMAT_BC2_UNORM: return DXGI_FORMAT_BC2_UNORM_SRGB; - case DXGI_FORMAT_BC3_UNORM: - return DXGI_FORMAT_BC3_UNORM_SRGB; + case DXGI_FORMAT_BC3_UNORM: return DXGI_FORMAT_BC3_UNORM_SRGB; - case DXGI_FORMAT_B8G8R8A8_UNORM: - return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; + case DXGI_FORMAT_B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; - case DXGI_FORMAT_B8G8R8X8_UNORM: - return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + case DXGI_FORMAT_B8G8R8X8_UNORM: return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; - case DXGI_FORMAT_BC7_UNORM: - return DXGI_FORMAT_BC7_UNORM_SRGB; + case DXGI_FORMAT_BC7_UNORM: return DXGI_FORMAT_BC7_UNORM_SRGB; - default: - return format; + default: return format; } } //-------------------------------------------------------------------------------------- HRESULT CreateD3DResources(_In_ ID3D12Device* device, - _In_ const DDS_HEADER_XBOX* xboxext, - _In_ uint32_t width, - _In_ uint32_t height, - _In_ uint32_t depth, - _In_ uint32_t mipCount, - _In_ uint32_t arraySize, - _In_ bool forceSRGB, - _In_ void* grfxMemory, - _Outptr_ ID3D12Resource** texture) noexcept + _In_ const DDS_HEADER_XBOX* xboxext, + _In_ uint32_t width, + _In_ uint32_t height, + _In_ uint32_t depth, + _In_ uint32_t mipCount, + _In_ uint32_t arraySize, + _In_ bool forceSRGB, + _In_ void* grfxMemory, + _Outptr_ ID3D12Resource** texture) noexcept { if (!device || !grfxMemory) return E_POINTER; @@ -205,19 +187,19 @@ namespace } D3D12_RESOURCE_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.MipLevels = static_cast(mipCount); - desc.DepthOrArraySize = (xboxext->resourceDimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) ? static_cast(depth) : static_cast(arraySize); - desc.Format = format; - desc.Flags = D3D12_RESOURCE_FLAG_NONE; - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - desc.Dimension = static_cast(xboxext->resourceDimension); - desc.Layout = static_cast((0x100 | xboxext->tileMode) & ~XBOX_TILEMODE_SCARLETT); - - hr = device->CreatePlacedResourceX( - reinterpret_cast(grfxMemory), + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.MipLevels = static_cast(mipCount); + desc.DepthOrArraySize = (xboxext->resourceDimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) ? static_cast(depth) : + static_cast(arraySize); + desc.Format = format; + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Dimension = static_cast(xboxext->resourceDimension); + desc.Layout = static_cast((0x100 | xboxext->tileMode) & ~XBOX_TILEMODE_SCARLETT); + + hr = device->CreatePlacedResourceX(reinterpret_cast(grfxMemory), &desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, @@ -233,19 +215,19 @@ namespace //-------------------------------------------------------------------------------------- HRESULT CreateTextureFromDDS(_In_ ID3D12Device* device, - _In_ const DDS_HEADER* header, - _In_reads_bytes_(bitSize) const uint8_t* bitData, - _In_ size_t bitSize, - _In_ bool forceSRGB, - _Outptr_ ID3D12Resource** texture, - _Outptr_ void** grfxMemory, - _Out_opt_ bool* outIsCubeMap) noexcept + _In_ const DDS_HEADER* header, + _In_reads_bytes_(bitSize) const uint8_t* bitData, + _In_ size_t bitSize, + _In_ bool forceSRGB, + _Outptr_ ID3D12Resource** texture, + _Outptr_ void** grfxMemory, + _Out_opt_ bool* outIsCubeMap) noexcept { HRESULT hr = S_OK; - uint32_t width = header->width; + uint32_t width = header->width; uint32_t height = header->height; - uint32_t depth = header->depth; + uint32_t depth = header->depth; uint32_t mipCount = header->mipMapCount; if (0 == mipCount) @@ -253,8 +235,7 @@ namespace mipCount = 1; } - if (!(header->ddspf.flags & DDS_FOURCC) - || (MAKEFOURCC('X', 'B', 'O', 'X') != header->ddspf.fourCC)) + if (!(header->ddspf.flags & DDS_FOURCC) || (MAKEFOURCC('X', 'B', 'O', 'X') != header->ddspf.fourCC)) { // Use standard DDSTextureLoader instead return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -301,29 +282,28 @@ namespace } break; - default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } if (xboxext->tileMode == uint32_t(-1)) { return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } - #if defined(_GAMING_XBOX_SCARLETT) +#if defined(_GAMING_XBOX_SCARLETT) else if (!(xboxext->tileMode & XBOX_TILEMODE_SCARLETT)) { DebugTrace("ERROR: XboxDDSTextureLoader for Scarlett cannot load textures tiled for Xbox One"); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } - #else +#else else if (xboxext->tileMode & XBOX_TILEMODE_SCARLETT) { DebugTrace("ERROR: XboxDDSTextureLoader for Xbox One cannot load textures tiled for Scarlett"); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } - #endif +#endif - // Bound sizes + // Bound sizes if (mipCount > D3D11_REQ_MIP_LEVELS) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -332,8 +312,7 @@ namespace switch (xboxext->resourceDimension) { case D3D12_RESOURCE_DIMENSION_TEXTURE1D: - if ((arraySize > D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || - (width > D3D12_REQ_TEXTURE1D_U_DIMENSION)) + if ((arraySize > D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || (width > D3D12_REQ_TEXTURE1D_U_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } @@ -343,33 +322,28 @@ namespace if (isCubeMap) { // This is the right bound because we set arraySize to (NumCubes*6) above - if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D12_REQ_TEXTURECUBE_DIMENSION) || - (height > D3D12_REQ_TEXTURECUBE_DIMENSION)) + if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D12_REQ_TEXTURECUBE_DIMENSION) + || (height > D3D12_REQ_TEXTURECUBE_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } - else if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) || - (height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + else if ((arraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) + || (height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; case D3D12_RESOURCE_DIMENSION_TEXTURE3D: - if ((arraySize > 1) || - (width > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (height > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (depth > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) + if ((arraySize > 1) || (width > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) + || (depth > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; - default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } if (xboxext->dxgiFormat == DXGI_FORMAT_UNKNOWN) @@ -396,10 +370,7 @@ namespace memcpy(*grfxMemory, bitData, xboxext->dataSize); // Create the texture - hr = CreateD3DResources(device, xboxext, - width, height, depth, mipCount, arraySize, - forceSRGB, *grfxMemory, - texture); + hr = CreateD3DResources(device, xboxext, width, height, depth, mipCount, arraySize, forceSRGB, *grfxMemory, texture); if (FAILED(hr)) { XMemFree(*grfxMemory, c_XMemAllocAttributes); @@ -422,17 +393,15 @@ namespace if (MAKEFOURCC('X', 'B', 'O', 'X') == header->ddspf.fourCC) { auto xboxext = reinterpret_cast(reinterpret_cast(header) + sizeof(DDS_HEADER)); - auto mode = static_cast(xboxext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK); + auto mode = static_cast(xboxext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK); switch (mode) { case DDS_ALPHA_MODE_STRAIGHT: case DDS_ALPHA_MODE_PREMULTIPLIED: case DDS_ALPHA_MODE_OPAQUE: - case DDS_ALPHA_MODE_CUSTOM: - return mode; + case DDS_ALPHA_MODE_CUSTOM: return mode; - default: - break; + default: break; } } } @@ -441,18 +410,15 @@ namespace } } // anonymous namespace - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT Xbox::CreateDDSTextureFromMemory( - ID3D12Device* device, - const uint8_t* ddsData, - size_t ddsDataSize, - ID3D12Resource** texture, - void** grfxMemory, - DDS_ALPHA_MODE* alphaMode, - bool forceSRGB, - bool* isCubeMap) noexcept +_Use_decl_annotations_ HRESULT Xbox::CreateDDSTextureFromMemory(ID3D12Device* device, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D12Resource** texture, + void** grfxMemory, + DDS_ALPHA_MODE* alphaMode, + bool forceSRGB, + bool* isCubeMap) noexcept { if (texture) { @@ -494,15 +460,13 @@ HRESULT Xbox::CreateDDSTextureFromMemory( auto header = reinterpret_cast(ddsData + sizeof(uint32_t)); // Verify header to validate DDS file - if (header->size != sizeof(DDS_HEADER) || - header->ddspf.size != sizeof(DDS_PIXELFORMAT)) + if (header->size != sizeof(DDS_HEADER) || header->ddspf.size != sizeof(DDS_PIXELFORMAT)) { return E_FAIL; } // Check for XBOX extension - if (!(header->ddspf.flags & DDS_FOURCC) - || (MAKEFOURCC('X', 'B', 'O', 'X') != header->ddspf.fourCC)) + if (!(header->ddspf.flags & DDS_FOURCC) || (MAKEFOURCC('X', 'B', 'O', 'X') != header->ddspf.fourCC)) { // Use standard DDSTextureLoader instead return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -516,9 +480,7 @@ HRESULT Xbox::CreateDDSTextureFromMemory( auto offset = DDS_XBOX_HEADER_SIZE; - HRESULT hr = CreateTextureFromDDS(device, header, - ddsData + offset, ddsDataSize - offset, forceSRGB, - texture, grfxMemory, isCubeMap); + HRESULT hr = CreateTextureFromDDS(device, header, ddsData + offset, ddsDataSize - offset, forceSRGB, texture, grfxMemory, isCubeMap); if (SUCCEEDED(hr)) { _Analysis_assume_(*texture != nullptr); @@ -532,15 +494,13 @@ HRESULT Xbox::CreateDDSTextureFromMemory( } //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT Xbox::CreateDDSTextureFromFile( - ID3D12Device* device, - const wchar_t* fileName, - ID3D12Resource** texture, - void** grfxMemory, - DDS_ALPHA_MODE* alphaMode, - bool forceSRGB, - bool* isCubeMap) noexcept +_Use_decl_annotations_ HRESULT Xbox::CreateDDSTextureFromFile(ID3D12Device* device, + const wchar_t* fileName, + ID3D12Resource** texture, + void** grfxMemory, + DDS_ALPHA_MODE* alphaMode, + bool forceSRGB, + bool* isCubeMap) noexcept { if (texture) { @@ -567,34 +527,27 @@ HRESULT Xbox::CreateDDSTextureFromFile( return E_INVALIDARG; } - DDS_HEADER* header = nullptr; - uint8_t* bitData = nullptr; - size_t bitSize = 0; + DDS_HEADER* header = nullptr; + uint8_t* bitData = nullptr; + size_t bitSize = 0; std::unique_ptr ddsData; - HRESULT hr = LoadTextureDataFromFile(fileName, - ddsData, - &header, - &bitData, - &bitSize - ); + HRESULT hr = LoadTextureDataFromFile(fileName, ddsData, &header, &bitData, &bitSize); if (FAILED(hr)) { return hr; } - hr = CreateTextureFromDDS(device, header, - bitData, bitSize, forceSRGB, - texture, grfxMemory, isCubeMap); + hr = CreateTextureFromDDS(device, header, bitData, bitSize, forceSRGB, texture, grfxMemory, isCubeMap); if (SUCCEEDED(hr)) { - #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D11_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) if (texture != nullptr && *texture != nullptr) { (*texture)->SetName(fileName); } - #endif +#endif if (alphaMode) *alphaMode = GetAlphaMode(header); @@ -604,8 +557,7 @@ HRESULT Xbox::CreateDDSTextureFromFile( } //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -void Xbox::FreeDDSTextureMemory(void* grfxMemory) noexcept +_Use_decl_annotations_ void Xbox::FreeDDSTextureMemory(void* grfxMemory) noexcept { if (grfxMemory) { diff --git a/Src/pch.h b/Src/pch.h index ba91e038..88cf415e 100644 --- a/Src/pch.h +++ b/Src/pch.h @@ -11,7 +11,8 @@ #ifdef _MSC_VER // Off by default warnings -#pragma warning(disable : 4619 4061 4265 4355 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4865 4987 5026 5027 5031 5032 5039 5045 5219 5246 5264 26812) +#pragma warning(disable \ + : 4619 4061 4265 4355 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4865 4987 5026 5027 5031 5032 5039 5045 5219 5246 5264 26812) // C4619 #pragma warning: there is no warning number 'X' // C4061 enumerator 'X' in switch of enum 'X' is not explicitly handled by a case label // C4265 class has virtual functions, but destructor is not virtual @@ -51,11 +52,11 @@ // C5038 data member 'X' will be initialized after data member 'Y' // C5040 dynamic exception specifications are valid only in C++14 and earlier; treating as noexcept(false) // C5043 exception specification does not match previous declaration -// C5204 class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly -// C5246 'anonymous struct or union': the initialization of a subobject should be wrapped in braces -// C5256 a non-defining declaration of an enumeration with a fixed underlying type is only permitted as a standalone declaration -// C5262 implicit fall-through occurs here; are you missing a break statement? -// C5267 definition of implicit copy constructor for 'X' is deprecated because it has a user-provided assignment operator +// C5204 class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be +// destructed correctly C5246 'anonymous struct or union': the initialization of a subobject should be wrapped in braces C5256 a +// non-defining declaration of an enumeration with a fixed underlying type is only permitted as a standalone declaration C5262 implicit +// fall-through occurs here; are you missing a break statement? C5267 definition of implicit copy constructor for 'X' is deprecated because +// it has a user-provided assignment operator #endif // _XBOX_ONE && _TITLE #endif // _MSC_VER @@ -125,13 +126,13 @@ #ifdef _GAMING_XBOX_SCARLETT #pragma warning(push) -#pragma warning(disable: 5204 5249) +#pragma warning(disable : 5204 5249) #include #pragma warning(pop) #include #else #pragma warning(push) -#pragma warning(disable: 5204) +#pragma warning(disable : 5204) #include #pragma warning(pop) #include @@ -184,7 +185,7 @@ #if (defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)) || (defined(_XBOX_ONE) && defined(_TITLE)) #pragma warning(push) -#pragma warning(disable: 4471 5204 5256) +#pragma warning(disable : 4471 5204 5256) #include #pragma warning(pop) #endif @@ -257,10 +258,17 @@ #endif #if defined(USING_GAMEINPUT) && defined(__MINGW32__) -namespace GameInput { namespace v1 { interface IGameInput; } } -template<> inline auto __mingw_uuidof() -> GUID const& +namespace GameInput { - static constexpr GUID the_uuid = { 0x40ffb7e4,0x6150,0x407a,0xb4,0x39,0x13,0x2b,0xad,0xc0,0x8d,0x2d }; + namespace v1 + { + interface IGameInput; + } +} // namespace GameInput +template<> +inline auto __mingw_uuidof() -> GUID const& +{ + static constexpr GUID the_uuid = { 0x40ffb7e4, 0x6150, 0x407a, 0xb4, 0x39, 0x13, 0x2b, 0xad, 0xc0, 0x8d, 0x2d }; return the_uuid; } #endif diff --git a/Src/vbo.h b/Src/vbo.h index 83e9946e..951dd052 100644 --- a/Src/vbo.h +++ b/Src/vbo.h @@ -20,7 +20,7 @@ namespace VBO { -#pragma pack(push,1) +#pragma pack(push, 1) struct header_t { @@ -37,7 +37,7 @@ namespace VBO #pragma pack(pop) -} // namespace +} // namespace VBO static_assert(sizeof(VBO::header_t) == 8, "VBO header size mismatch"); static_assert(sizeof(VBO::vertex_t) == 32, "VBO vertex size mismatch"); diff --git a/build/Format.ps1 b/build/Format.ps1 new file mode 100644 index 00000000..5f2e4b8f --- /dev/null +++ b/build/Format.ps1 @@ -0,0 +1,105 @@ +<# + +.NOTES +Copyright (c) Microsoft Corporation. +Licensed under the MIT License. + +.SYNOPSIS +Runs clang-format on the source code. + +.DESCRIPTION +This is use to clang-format the code using the rules in .github\linters\.clang-format. + +The clang-format version must match the version used by GitHub Super-Linter or false positives can be found. +You can install this version locally using: + +winget install --id=LLVM.LLVM --version 21.1.2 + +.PARAMETER Check +Runs clang-format without modifying the files in place. + +.PARAMETER LLVM +Normally clang-format is found on the path. If you use this switch, then it looks for it in C:\Program Files\LLVM\bin. + +.LINKS +https://github.com/microsoft/DirectXTK12 + +#> + +[CmdletBinding()] +param( + [switch] $Check, + [Alias('UseLLVM')] + [switch] $LLVM +) + +$ErrorActionPreference = 'Stop' + +$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$configFile = Join-Path $repoRoot '.github\linters\.clang-format' + +if (-not (Test-Path -LiteralPath $configFile -PathType Leaf)) { + throw "clang-format configuration was not found: $configFile" +} + +$clangFormatPath = if ($LLVM) { + 'C:\Program Files\LLVM\bin\clang-format.exe' +} +else { + (Get-Command clang-format -ErrorAction SilentlyContinue).Source +} + +if (-not $clangFormatPath -or -not (Test-Path -LiteralPath $clangFormatPath -PathType Leaf)) { + if ($LLVM) { + throw "clang-format was not found at: $clangFormatPath" + } + + throw 'clang-format was not found on PATH.' +} + +# This has to match the version used by GitHub super-linter or results will not match. +$requiredClangFormatVersion = '21.1.2' +$clangFormatVersion = (& $clangFormatPath '--version' 2>&1 | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { + throw "Unable to determine clang-format version." +} + +if ($clangFormatVersion -notmatch "\b$([regex]::Escape($requiredClangFormatVersion))\b") { + throw "clang-format version $requiredClangFormatVersion is required; found: $clangFormatVersion" +} + +$sourceFiles = Get-ChildItem -LiteralPath $repoRoot -Recurse| + Where-Object { + $_.FullName -notmatch '\\(?:\.git|\.vs|build|Tests|vcpkg_installed)\\' -and $_.Extension -in '.c','.cc','.cpp','.cxx','.h','.hh','.hpp','.inl' + } + +if ($sourceFiles.Count -eq 0) { + Write-Output 'No C/C++ source files found.' + exit 0 +} + +$arguments = @( + '--style=file:{0}' -f $configFile +) + +if ($Check) { + $arguments += '--dry-run' + $arguments += '--Werror' +} +else { + $arguments += '-i' +} + +foreach ($sourceFile in $sourceFiles) { + & $clangFormatPath @arguments $sourceFile.FullName + if ($LASTEXITCODE -ne 0) { + throw "clang-format failed for $($sourceFile.FullName)." + } +} + +if ($Check) { + Write-Output "Checked $($sourceFiles.Count) C/C++ source files." +} +else { + Write-Output "Formatted $($sourceFiles.Count) C/C++ source files." +}