From eba6caa1b75bbe0c6140287551e8b3b745c722c2 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 11:32:06 -0700 Subject: [PATCH 01/15] Enable use of clang-format --- .clang-format-ignore | 1 + .github/linters/.clang-format | 87 +++++++++++++++++++++++++++++++++++ .github/workflows/lint.yml | 5 +- Src/Geometry.cpp | 24 ++++++++++ build/Format.ps1 | 54 ++++++++++++++++++++++ 5 files changed, 169 insertions(+), 2 deletions(-) create mode 100644 .clang-format-ignore create mode 100644 .github/linters/.clang-format create mode 100644 build/Format.ps1 diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 00000000..83e6847d --- /dev/null +++ b/.clang-format-ignore @@ -0,0 +1 @@ +*/DDS.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/workflows/lint.yml b/.github/workflows/lint.yml index 0e8e3eda..7923ae89 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_CSHARP: true VALIDATE_GITHUB_ACTIONS: true diff --git a/Src/Geometry.cpp b/Src/Geometry.cpp index 26a70f98..7e9067f7 100644 --- a/Src/Geometry.cpp +++ b/Src/Geometry.cpp @@ -251,8 +251,10 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi XMFLOAT3(-1, 0, 0), // 4 left XMFLOAT3(0, -1, 0), // 5 bottom }; + 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 +263,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; @@ -355,12 +358,15 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // /b\c/d\ // v2 o---o---o v1 // v12 + 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)); } @@ -783,18 +789,22 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in 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] = { + // 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) @@ -853,6 +863,7 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind static const uint32_t faces[8 * 3] = { + // clang-format off 4, 0, 2, 4, 2, 1, 4, 1, 3, @@ -861,6 +872,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) @@ -913,6 +925,7 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i static const XMVECTORF32 verts[20] = { + // clang-format off { { { a, a, a, 0 } } }, { { { a, a, -a, 0 } } }, { { { a, -a, a, 0 } } }, @@ -933,10 +946,12 @@ 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] = { + // clang-format off 0, 8, 9, 4, 16, 0, 16, 17, 2, 12, 12, 2, 10, 3, 13, @@ -949,19 +964,23 @@ 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] = { + // 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] = { + // clang-format off { 0, 1, 2, 3, 4 }, { 2, 3, 4, 0, 1 }, { 4, 0, 1, 2, 3 }, @@ -974,6 +993,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; @@ -1043,6 +1063,7 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in 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 +1076,12 @@ 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] = { + // clang-format off 0, 8, 4, 0, 5, 10, 2, 4, 9, @@ -1079,6 +1102,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) diff --git a/build/Format.ps1 b/build/Format.ps1 new file mode 100644 index 00000000..84ca249d --- /dev/null +++ b/build/Format.ps1 @@ -0,0 +1,54 @@ +[CmdletBinding()] +param( + [switch] $Check +) + +$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" +} + +$clangFormat = Get-Command clang-format -ErrorAction SilentlyContinue +if (-not $clangFormat) { + throw 'clang-format was not found on PATH.' +} + +$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' + } + +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) { + & $clangFormat.Source @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." +} From 4be39079c68a4e5ab4169266ed537e9ca5e20864 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 11:39:39 -0700 Subject: [PATCH 02/15] Reformat source --- Audio/AudioEngine.cpp | 664 ++++++------- Audio/DynamicSoundEffectInstance.cpp | 158 ++-- Audio/SoundCommon.cpp | 467 +++++----- Audio/SoundCommon.h | 101 +- Audio/SoundEffect.cpp | 298 +++--- Audio/SoundEffectInstance.cpp | 124 +-- Audio/SoundStreamInstance.cpp | 412 ++++---- Audio/WAVFileReader.cpp | 323 +++---- Audio/WAVFileReader.h | 49 +- Audio/WaveBank.cpp | 177 ++-- Audio/WaveBankReader.cpp | 525 +++++------ Audio/WaveBankReader.h | 28 +- Inc/Audio.h | 485 +++++----- Inc/BufferHelpers.h | 140 ++- Inc/CommonStates.h | 17 +- Inc/DDSTextureLoader.h | 379 ++++---- Inc/DirectXHelpers.h | 126 ++- Inc/Effects.h | 496 +++++----- Inc/GamePad.h | 113 +-- Inc/GeometricPrimitive.h | 279 +++--- Inc/GraphicsMemory.h | 34 +- Inc/Keyboard.h | 683 +++++++------- Inc/Model.h | 419 ++++----- Inc/Mouse.h | 89 +- Inc/PostProcess.h | 78 +- Inc/PrimitiveBatch.h | 104 +-- Inc/ScreenGrab.h | 31 +- Inc/SimpleMath.h | 1292 +++++++++++++++++--------- Inc/SpriteBatch.h | 126 +-- Inc/SpriteFont.h | 304 +++--- Inc/VertexTypes.h | 282 +++--- Inc/WICTextureLoader.h | 344 +++---- Inc/XboxDDSTextureLoader.h | 75 +- Src/AlignedNew.h | 34 +- Src/AlphaTestEffect.cpp | 171 ++-- Src/BasicEffect.cpp | 461 +++++---- Src/BasicPostProcess.cpp | 263 +++--- Src/Bezier.h | 46 +- Src/BinaryReader.cpp | 28 +- Src/BinaryReader.h | 18 +- Src/BufferHelpers.cpp | 202 ++-- Src/CMO.h | 29 +- Src/CommonStates.cpp | 162 ++-- Src/DDSTextureLoader.cpp | 1207 ++++++++++++------------ Src/DGSLEffect.cpp | 294 +++--- Src/DGSLEffectFactory.cpp | 169 ++-- Src/DebugEffect.cpp | 269 +++--- Src/DemandCreate.h | 23 +- Src/DirectXHelpers.cpp | 20 +- Src/DualPostProcess.cpp | 138 ++- Src/DualTextureEffect.cpp | 115 +-- Src/EffectCommon.cpp | 215 ++--- Src/EffectCommon.h | 146 ++- Src/EffectFactory.cpp | 125 +-- Src/EnvironmentMapEffect.cpp | 449 +++++---- Src/GamePad.cpp | 617 ++++++------ Src/GeometricPrimitive.cpp | 429 +++------ Src/Geometry.cpp | 432 +++++---- Src/Geometry.h | 16 +- Src/GraphicsMemory.cpp | 67 +- Src/Keyboard.cpp | 243 ++--- Src/LoaderHelpers.h | 302 +++--- Src/Model.cpp | 303 +++--- Src/ModelLoadCMO.cpp | 241 +++-- Src/ModelLoadSDKMESH.cpp | 439 ++++----- Src/ModelLoadVBO.cpp | 88 +- Src/Mouse.cpp | 538 +++++------ Src/NPREffect.cpp | 504 +++++----- Src/NPREffectFactory.cpp | 127 +-- Src/NormalMapEffect.cpp | 381 ++++---- Src/PBREffect.cpp | 294 +++--- Src/PBREffectFactory.cpp | 132 +-- Src/PlatformHelpers.h | 53 +- Src/PrimitiveBatch.cpp | 142 ++- Src/SDKMesh.h | 129 ++- Src/ScreenGrab.cpp | 321 ++++--- Src/SharedResourcePool.h | 23 +- Src/SimpleMath.cpp | 89 +- Src/SkinnedEffect.cpp | 346 ++++--- Src/SpriteBatch.cpp | 541 +++++------ Src/SpriteFont.cpp | 520 ++++++----- Src/ToneMapPostProcess.cpp | 246 ++--- Src/VertexTypes.cpp | 118 +-- Src/WICTextureLoader.cpp | 778 ++++++++-------- Src/XboxDDSTextureLoader.cpp | 494 +++++----- Src/pch.h | 28 +- Src/vbo.h | 4 +- XWBTool/CmdLineHelpers.h | 78 +- XWBTool/xwbtool.cpp | 665 ++++++------- 89 files changed, 11437 insertions(+), 12097 deletions(-) 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..dd25c067 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,31 @@ 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 +109,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 +218,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 +302,7 @@ namespace DirectX { // Automatic stop if the buffer has finished playing std::ignore = voice->Stop(); - state = STOPPED; + state = STOPPED; } } @@ -319,10 +319,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 +328,7 @@ namespace DirectX voice->DestroyVoice(); voice = nullptr; } - state = STOPPED; + state = STOPPED; mDirectVoice = nullptr; mReverbVoice = nullptr; } @@ -356,8 +353,8 @@ namespace DirectX voice->DestroyVoice(); voice = nullptr; } - state = STOPPED; - engine = nullptr; + state = STOPPED; + engine = nullptr; mDirectVoice = nullptr; mReverbVoice = nullptr; } @@ -386,9 +383,9 @@ namespace DirectX } } - IXAudio2SourceVoice* voice; - SoundState state; - AudioEngine* engine; + IXAudio2SourceVoice* voice; + SoundState state; + AudioEngine* engine; private: float mVolume; @@ -423,4 +420,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..2126270f 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,89 +219,86 @@ 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 + // 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); @@ -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,29 @@ 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 +412,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 +471,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,25 +490,21 @@ 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 XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Position), v); } void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; @@ -546,10 +512,7 @@ namespace DirectX Position.z = pos.z; } - void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept - { - XMStoreFloat3(reinterpret_cast(&Velocity), v); - } + void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Velocity), v); } void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; @@ -564,9 +527,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 +551,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,45 +570,35 @@ 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 XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Position), v); } void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; @@ -650,10 +606,7 @@ namespace DirectX Position.z = pos.z; } - void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept - { - XMStoreFloat3(reinterpret_cast(&Velocity), v); - } + void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Velocity), v); } void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; @@ -668,9 +621,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 +645,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 +664,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 +678,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 +709,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 +727,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 +755,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 +772,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 +806,12 @@ 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 +843,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 8567f0d7..74c760e6 100644 --- a/Inc/BufferHelpers.h +++ b/Inc/BufferHelpers.h @@ -24,13 +24,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 @@ -39,87 +39,82 @@ #endif #endif - namespace DirectX { // Helpers for creating initialized Direct3D buffer resources. DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateStaticBuffer( - _In_ ID3D11Device* device, - _In_reads_bytes_(count* stride) const void* ptr, - size_t count, - size_t stride, - unsigned int bindFlags, - _COM_Outptr_ ID3D11Buffer** pBuffer) noexcept; + HRESULT __cdecl CreateStaticBuffer(_In_ ID3D11Device* device, + _In_reads_bytes_(count* stride) const void* ptr, + size_t count, + size_t stride, + unsigned int bindFlags, + _COM_Outptr_ ID3D11Buffer** pBuffer) noexcept; template - HRESULT CreateStaticBuffer( - _In_ ID3D11Device* device, - _In_reads_(count) T const* data, - size_t count, - unsigned int bindFlags, - _COM_Outptr_ ID3D11Buffer** pBuffer) noexcept + HRESULT CreateStaticBuffer(_In_ ID3D11Device* device, + _In_reads_(count) T const* data, + size_t count, + unsigned int bindFlags, + _COM_Outptr_ ID3D11Buffer** pBuffer) noexcept { return CreateStaticBuffer(device, data, count, sizeof(T), bindFlags, pBuffer); } template - HRESULT CreateStaticBuffer( - _In_ ID3D11Device* device, - T const& data, - unsigned int bindFlags, - _COM_Outptr_ ID3D11Buffer** pBuffer) noexcept + HRESULT + CreateStaticBuffer(_In_ ID3D11Device* device, T const& data, unsigned int bindFlags, _COM_Outptr_ ID3D11Buffer** pBuffer) noexcept { return CreateStaticBuffer(device, data.data(), data.size(), sizeof(typename T::value_type), bindFlags, pBuffer); } // Helpers for creating texture from memory arrays. DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateTextureFromMemory( - _In_ ID3D11Device* device, - size_t width, - DXGI_FORMAT format, - const D3D11_SUBRESOURCE_DATA& initData, - _COM_Outptr_opt_ ID3D11Texture1D** texture, - _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView, - unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept; + HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device, + size_t width, + DXGI_FORMAT format, + const D3D11_SUBRESOURCE_DATA& initData, + _COM_Outptr_opt_ ID3D11Texture1D** texture, + _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView, + unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateTextureFromMemory( - _In_ ID3D11Device* device, - size_t width, size_t height, - DXGI_FORMAT format, - const D3D11_SUBRESOURCE_DATA& initData, - _COM_Outptr_opt_ ID3D11Texture2D** texture, - _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView, - unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept; + HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device, + size_t width, + size_t height, + DXGI_FORMAT format, + const D3D11_SUBRESOURCE_DATA& initData, + _COM_Outptr_opt_ ID3D11Texture2D** texture, + _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView, + unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateTextureFromMemory( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDeviceX, - _In_ ID3D11DeviceContextX* d3dContextX, - #else - _In_ ID3D11Device* device, - _In_ ID3D11DeviceContext* d3dContext, - #endif - size_t width, size_t height, - DXGI_FORMAT format, - const D3D11_SUBRESOURCE_DATA& initData, - _COM_Outptr_opt_ ID3D11Texture2D** texture, - _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; + HRESULT __cdecl CreateTextureFromMemory( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDeviceX, + _In_ ID3D11DeviceContextX* d3dContextX, +#else + _In_ ID3D11Device* device, + _In_ ID3D11DeviceContext* d3dContext, +#endif + size_t width, + size_t height, + DXGI_FORMAT format, + const D3D11_SUBRESOURCE_DATA& initData, + _COM_Outptr_opt_ ID3D11Texture2D** texture, + _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateTextureFromMemory( - _In_ ID3D11Device* device, - size_t width, size_t height, size_t depth, - DXGI_FORMAT format, - const D3D11_SUBRESOURCE_DATA& initData, - _COM_Outptr_opt_ ID3D11Texture3D** texture, - _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView, - unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept; - - // Strongly typed wrapper around a Direct3D constant buffer. + HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device, + size_t width, + size_t height, + size_t depth, + DXGI_FORMAT format, + const D3D11_SUBRESOURCE_DATA& initData, + _COM_Outptr_opt_ ID3D11Texture3D** texture, + _COM_Outptr_opt_ ID3D11ShaderResourceView** textureView, + unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept; + + // Strongly typed wrapper around a Direct3D constant buffer. inline namespace DX11 { namespace Private @@ -130,8 +125,8 @@ namespace DirectX protected: void __cdecl CreateBuffer(_In_ ID3D11Device* device, size_t bytes, _Outptr_ ID3D11Buffer** pBuffer); }; - } - } + } // namespace Private + } // namespace DX11 template class ConstantBuffer : public DX11::Private::ConstantBufferBase @@ -144,19 +139,16 @@ namespace DirectX CreateBuffer(device, sizeof(T), mConstantBuffer.GetAddressOf()); } - ConstantBuffer(ConstantBuffer&&) = default; - ConstantBuffer& operator= (ConstantBuffer&&) = default; + ConstantBuffer(ConstantBuffer&&) = default; + ConstantBuffer& operator=(ConstantBuffer&&) = default; - ConstantBuffer(ConstantBuffer const&) = delete; - ConstantBuffer& operator= (ConstantBuffer const&) = delete; + ConstantBuffer(ConstantBuffer const&) = delete; + ConstantBuffer& operator=(ConstantBuffer const&) = delete; - void Create(_In_ ID3D11Device* device) - { - CreateBuffer(device, sizeof(T), mConstantBuffer.ReleaseAndGetAddressOf()); - } + void Create(_In_ ID3D11Device* device) { CreateBuffer(device, sizeof(T), mConstantBuffer.ReleaseAndGetAddressOf()); } // Writes new data into the constant buffer. - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) void __cdecl SetData(_In_ ID3D11DeviceContext* deviceContext, T const& value, void** grfxMemory) { assert(grfxMemory != nullptr); @@ -168,7 +160,7 @@ namespace DirectX *grfxMemory = ptr; } - #else +#else void __cdecl SetData(_In_ ID3D11DeviceContext* deviceContext, T const& value) noexcept { @@ -182,7 +174,7 @@ namespace DirectX deviceContext->Unmap(mConstantBuffer.Get(), 0); } } - #endif // _XBOX_ONE && _TITLE +#endif // _XBOX_ONE && _TITLE // Looks up the underlying D3D constant buffer. ID3D11Buffer* GetBuffer() const noexcept { return mConstantBuffer.Get(); } @@ -190,4 +182,4 @@ namespace DirectX private: Microsoft::WRL::ComPtr mConstantBuffer; }; -} +} // namespace DirectX diff --git a/Inc/CommonStates.h b/Inc/CommonStates.h index a1917c99..eb341f83 100644 --- a/Inc/CommonStates.h +++ b/Inc/CommonStates.h @@ -20,13 +20,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 @@ -35,7 +35,6 @@ #endif #endif - namespace DirectX { inline namespace DX11 @@ -45,11 +44,11 @@ namespace DirectX public: DIRECTX_TOOLKIT_API explicit CommonStates(_In_ ID3D11Device* 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(CommonStates const&) = delete; - CommonStates& operator= (CommonStates const&) = delete; + CommonStates(CommonStates const&) = delete; + CommonStates& operator=(CommonStates const&) = delete; DIRECTX_TOOLKIT_API virtual ~CommonStates(); @@ -86,5 +85,5 @@ namespace DirectX std::shared_ptr pImpl; }; - } -} + } // namespace DX11 +} // namespace DirectX diff --git a/Inc/DDSTextureLoader.h b/Inc/DDSTextureLoader.h index a389953f..dcf01530 100644 --- a/Inc/DDSTextureLoader.h +++ b/Inc/DDSTextureLoader.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,18 +43,17 @@ #endif #endif - namespace DirectX { #ifndef DDS_ALPHA_MODE_DEFINED #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 @@ -62,8 +61,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_IGNORE_MIPS = 0x20, }; @@ -71,201 +70,231 @@ namespace DirectX // Standard version DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFile( - _In_ ID3D11Device* d3dDevice, - _In_z_ const wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromFile(_In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; - // Standard version with optional auto-gen mipmap support + // Standard version with optional auto-gen mipmap support DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemory( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromMemory( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFile( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromFile( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; - // Extended version + // Extended version DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemoryEx( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - _In_ size_t ddsDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromMemoryEx(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFileEx( - _In_ ID3D11Device* d3dDevice, - _In_z_ const wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromFileEx(_In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; - // Extended version with optional auto-gen mipmap support + // Extended version with optional auto-gen mipmap support DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemoryEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - _In_ size_t ddsDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromMemoryEx( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFileEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; + HRESULT __cdecl CreateDDSTextureFromFileEx( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept; #ifdef __cpp_lib_byte DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept + inline HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept { - return CreateDDSTextureFromMemory(d3dDevice, reinterpret_cast(ddsData), ddsDataSize, texture, textureView, maxsize, alphaMode); + return CreateDDSTextureFromMemory(d3dDevice, + reinterpret_cast(ddsData), + ddsDataSize, + texture, + textureView, + maxsize, + alphaMode); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemory( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept + inline HRESULT __cdecl CreateDDSTextureFromMemory( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept { - return CreateDDSTextureFromMemory(d3dDevice, d3dContext, reinterpret_cast(ddsData), ddsDataSize, texture, textureView, maxsize, alphaMode); + return CreateDDSTextureFromMemory(d3dDevice, + d3dContext, + reinterpret_cast(ddsData), + ddsDataSize, + texture, + textureView, + maxsize, + alphaMode); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemoryEx( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - _In_ size_t ddsDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept + inline HRESULT __cdecl CreateDDSTextureFromMemoryEx(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + _In_ size_t ddsDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept { - return CreateDDSTextureFromMemoryEx(d3dDevice, reinterpret_cast(ddsData), ddsDataSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView, alphaMode); + return CreateDDSTextureFromMemoryEx(d3dDevice, + reinterpret_cast(ddsData), + ddsDataSize, + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView, + alphaMode); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemoryEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - _In_ size_t ddsDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept + inline HRESULT __cdecl CreateDDSTextureFromMemoryEx( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + _In_ size_t ddsDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept { - return CreateDDSTextureFromMemoryEx(d3dDevice, d3dContext, reinterpret_cast(ddsData), ddsDataSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView, alphaMode); + return CreateDDSTextureFromMemoryEx(d3dDevice, + d3dContext, + reinterpret_cast(ddsData), + ddsDataSize, + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView, + alphaMode); } #endif // __cpp_lib_byte @@ -282,4 +311,4 @@ namespace DirectX #ifdef __clang__ #pragma clang diagnostic pop #endif -} +} // namespace DirectX diff --git a/Inc/DirectXHelpers.h b/Inc/DirectXHelpers.h index bf8e5253..10e8a073 100644 --- a/Inc/DirectXHelpers.h +++ b/Inc/DirectXHelpers.h @@ -16,9 +16,9 @@ #endif #ifdef _MSC_VER -#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D11_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) #if !defined(_XBOX_ONE) || !defined(_TITLE) -#pragma comment(lib,"dxguid.lib") +#pragma comment(lib, "dxguid.lib") #endif #endif #endif @@ -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 @@ -51,7 +51,6 @@ #endif #endif - // // The core Direct3D headers provide the following helper C++ classes // CD3D11_RECT @@ -73,7 +72,6 @@ // CD3D11_COUNTER_DESC // - namespace DirectX { inline namespace DX11 @@ -86,11 +84,13 @@ namespace DirectX { public: MapGuard(_In_ ID3D11DeviceContext* context, - _In_ ID3D11Resource *resource, - _In_ unsigned int subresource, - _In_ D3D11_MAP mapType, - _In_ unsigned int mapFlags) noexcept(false) - : mContext(context), mResource(resource), mSubresource(subresource) + _In_ ID3D11Resource* resource, + _In_ unsigned int subresource, + _In_ D3D11_MAP mapType, + _In_ unsigned int mapFlags) noexcept(false) + : mContext(context), + mResource(resource), + mSubresource(subresource) { HRESULT hr = mContext->Map(resource, subresource, mapType, mapFlags, this); if (FAILED(hr)) @@ -99,44 +99,32 @@ namespace DirectX } } - MapGuard(MapGuard&&) = delete; - MapGuard& operator= (MapGuard&&) = delete; + MapGuard(MapGuard&&) = delete; + MapGuard& operator=(MapGuard&&) = delete; - MapGuard(MapGuard const&) = delete; - MapGuard& operator= (MapGuard const&) = delete; + MapGuard(MapGuard const&) = delete; + MapGuard& operator=(MapGuard const&) = delete; - ~MapGuard() - { - mContext->Unmap(mResource, mSubresource); - } + ~MapGuard() { mContext->Unmap(mResource, mSubresource); } - #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 - uint8_t* get() const noexcept - { - return static_cast(pData); - } - uint8_t* get(size_t slice) const noexcept - { - return static_cast(pData) + (slice * DepthPitch); - } + uint8_t* get() const noexcept { return static_cast(pData); } + uint8_t* get(size_t slice) const noexcept { return static_cast(pData) + (slice * DepthPitch); } - uint8_t* scanline(size_t row) const noexcept - { - return static_cast(pData) + (row * RowPitch); - } + uint8_t* scanline(size_t row) const noexcept { return static_cast(pData) + (row * RowPitch); } uint8_t* scanline(size_t slice, size_t row) const noexcept { return static_cast(pData) + (slice * DepthPitch) + (row * RowPitch); } - #ifdef __clang__ - #pragma clang diagnostic pop - #endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif template void copy(_In_reads_(count) T const* data, size_t count) noexcept @@ -151,52 +139,51 @@ namespace DirectX } private: - ID3D11DeviceContext* mContext; - ID3D11Resource* mResource; - unsigned int mSubresource; + ID3D11DeviceContext* mContext; + ID3D11Resource* mResource; + unsigned int mSubresource; }; - // Helper sets a D3D resource name string (used by PIX and debug layer leak reporting). -#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D11_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) template - inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const char(&name)[TNameLength]) noexcept + inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const char (&name)[TNameLength]) noexcept { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) 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); } - #else +#else resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name); - #endif +#endif } #else template - inline void SetDebugObjectName(_In_ ID3D11DeviceChild*, _In_z_ const char(&)[TNameLength]) noexcept + inline void SetDebugObjectName(_In_ ID3D11DeviceChild*, _In_z_ const char (&)[TNameLength]) noexcept {} #endif -#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D11_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) template - inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const wchar_t(&name)[TNameLength]) + inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const wchar_t (&name)[TNameLength]) { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) resource->SetName(name); - #else +#else char aname[MAX_PATH]; - int result = WideCharToMultiByte(CP_UTF8, 0, name, TNameLength, aname, MAX_PATH, nullptr, nullptr); + int result = WideCharToMultiByte(CP_UTF8, 0, name, TNameLength, aname, MAX_PATH, nullptr, nullptr); if (result > 0) { resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, aname); } - #endif +#endif } #else template - inline void SetDebugObjectName(_In_ ID3D11DeviceChild*, _In_z_ const wchar_t(&)[TNameLength]) + inline void SetDebugObjectName(_In_ ID3D11DeviceChild*, _In_z_ const wchar_t (&)[TNameLength]) {} #endif @@ -204,7 +191,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 @@ -230,22 +220,20 @@ namespace DirectX } return size; } - } + } // namespace DX11 // Helper for creating a Direct3D input layout to match a shader from an IEffect DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateInputLayoutFromEffect( - _In_ ID3D11Device* device, - _In_ IEffect* effect, - _In_reads_(count) const D3D11_INPUT_ELEMENT_DESC* desc, - size_t count, - _COM_Outptr_ ID3D11InputLayout** pInputLayout) noexcept; + HRESULT __cdecl CreateInputLayoutFromEffect(_In_ ID3D11Device* device, + _In_ IEffect* effect, + _In_reads_(count) const D3D11_INPUT_ELEMENT_DESC* desc, + size_t count, + _COM_Outptr_ ID3D11InputLayout** pInputLayout) noexcept; template - HRESULT CreateInputLayoutFromEffect(_In_ ID3D11Device* device, - _In_ IEffect* effect, - _COM_Outptr_ ID3D11InputLayout** pInputLayout) noexcept + HRESULT + CreateInputLayoutFromEffect(_In_ ID3D11Device* device, _In_ IEffect* effect, _COM_Outptr_ ID3D11InputLayout** pInputLayout) noexcept { return CreateInputLayoutFromEffect(device, effect, T::InputElements, T::InputElementCount, pInputLayout); } -} +} // namespace DirectX diff --git a/Inc/Effects.h b/Inc/Effects.h index 0da13b92..575e59e5 100644 --- a/Inc/Effects.h +++ b/Inc/Effects.h @@ -27,13 +27,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 @@ -47,7 +47,6 @@ #pragma warning(disable : 4251 4275) #endif - namespace DirectX { inline namespace DX11 @@ -59,59 +58,55 @@ namespace DirectX public: virtual ~IEffect() = default; - IEffect(const IEffect&) = delete; + IEffect(const IEffect&) = delete; IEffect& operator=(const IEffect&) = delete; virtual void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) = 0; - virtual void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) = 0; + virtual void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) = 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 __cdecl SetLightingEnabled(bool value) = 0; - virtual void __cdecl SetPerPixelLighting(bool value) = 0; + virtual void __cdecl SetLightingEnabled(bool value) = 0; + virtual void __cdecl SetPerPixelLighting(bool value) = 0; 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; @@ -119,51 +114,49 @@ 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 SetFogEnabled(bool value) = 0; - virtual void __cdecl SetFogStart(float value) = 0; - virtual void __cdecl SetFogEnd(float value) = 0; + virtual void __cdecl SetFogEnabled(bool 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 SetWeightsPerVertex(int value) = 0; + virtual void __cdecl SetWeightsPerVertex(int value) = 0; 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; }; @@ -174,20 +167,19 @@ namespace DirectX public: DIRECTX_TOOLKIT_API explicit BasicEffect(_In_ ID3D11Device* device); - 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -239,28 +231,25 @@ 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 explicit AlphaTestEffect(_In_ ID3D11Device* device); - 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -296,28 +285,25 @@ 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 explicit DualTextureEffect(_In_ ID3D11Device* device); - 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -350,35 +336,32 @@ 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 explicit EnvironmentMapEffect(_In_ ID3D11Device* device); - 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -432,28 +415,25 @@ 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 explicit SkinnedEffect(_In_ ID3D11Device* device); - 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -513,24 +493,23 @@ namespace DirectX class DGSLEffect : public IEffect, public IEffectMatrices, public IEffectLights { public: - DIRECTX_TOOLKIT_API inline explicit DGSLEffect(_In_ ID3D11Device* device, _In_opt_ ID3D11PixelShader* pixelShader = nullptr) : - DGSLEffect(device, pixelShader, false) + DIRECTX_TOOLKIT_API inline explicit DGSLEffect(_In_ ID3D11Device* device, _In_opt_ ID3D11PixelShader* pixelShader = nullptr) + : DGSLEffect(device, pixelShader, false) {} - DIRECTX_TOOLKIT_API DGSLEffect(DGSLEffect&&) noexcept; - DIRECTX_TOOLKIT_API DGSLEffect& operator= (DGSLEffect&&) noexcept; + DIRECTX_TOOLKIT_API DGSLEffect(DGSLEffect&&) noexcept; + DIRECTX_TOOLKIT_API DGSLEffect& operator=(DGSLEffect&&) noexcept; - DGSLEffect(DGSLEffect const&) = delete; - DGSLEffect& operator= (DGSLEffect const&) = delete; + DGSLEffect(DGSLEffect const&) = delete; + DGSLEffect& operator=(DGSLEffect const&) = delete; DIRECTX_TOOLKIT_API ~DGSLEffect() override; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -593,15 +572,15 @@ namespace DirectX class DIRECTX_TOOLKIT_API SkinnedDGSLEffect : public DGSLEffect, public IEffectSkinning { public: - explicit SkinnedDGSLEffect(_In_ ID3D11Device* device, _In_opt_ ID3D11PixelShader* pixelShader = nullptr) : - DGSLEffect(device, pixelShader, true) + explicit SkinnedDGSLEffect(_In_ ID3D11Device* device, _In_opt_ ID3D11PixelShader* pixelShader = nullptr) + : DGSLEffect(device, pixelShader, true) {} - SkinnedDGSLEffect(SkinnedDGSLEffect&&) = default; - SkinnedDGSLEffect& operator= (SkinnedDGSLEffect&&) = default; + SkinnedDGSLEffect(SkinnedDGSLEffect&&) = default; + SkinnedDGSLEffect& operator=(SkinnedDGSLEffect&&) = default; - SkinnedDGSLEffect(SkinnedDGSLEffect const&) = delete; - SkinnedDGSLEffect& operator= (SkinnedDGSLEffect const&) = delete; + SkinnedDGSLEffect(SkinnedDGSLEffect const&) = delete; + SkinnedDGSLEffect& operator=(SkinnedDGSLEffect const&) = delete; ~SkinnedDGSLEffect() override; @@ -616,24 +595,23 @@ namespace DirectX class NormalMapEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog { public: - DIRECTX_TOOLKIT_API inline explicit NormalMapEffect(_In_ ID3D11Device* device) : - NormalMapEffect(device, false) + DIRECTX_TOOLKIT_API inline explicit NormalMapEffect(_In_ ID3D11Device* device) + : NormalMapEffect(device, 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -697,15 +675,15 @@ namespace DirectX class DIRECTX_TOOLKIT_API SkinnedNormalMapEffect : public NormalMapEffect, public IEffectSkinning { public: - explicit SkinnedNormalMapEffect(_In_ ID3D11Device* device) : - NormalMapEffect(device, true) + explicit SkinnedNormalMapEffect(_In_ ID3D11Device* device) + : NormalMapEffect(device, 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; @@ -720,24 +698,23 @@ namespace DirectX class PBREffect : public IEffect, public IEffectMatrices, public IEffectLights { public: - DIRECTX_TOOLKIT_API inline explicit PBREffect(_In_ ID3D11Device* device) : - PBREffect(device, false) + DIRECTX_TOOLKIT_API inline explicit PBREffect(_In_ ID3D11Device* device) + : PBREffect(device, 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -765,15 +742,13 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetEmissiveTexture(_In_opt_ ID3D11ShaderResourceView* value); - DIRECTX_TOOLKIT_API void __cdecl SetSurfaceTextures( - _In_opt_ ID3D11ShaderResourceView* albedo, - _In_opt_ ID3D11ShaderResourceView* normal, - _In_opt_ ID3D11ShaderResourceView* roughnessMetallicAmbientOcclusion); + DIRECTX_TOOLKIT_API void __cdecl SetSurfaceTextures(_In_opt_ ID3D11ShaderResourceView* albedo, + _In_opt_ ID3D11ShaderResourceView* normal, + _In_opt_ ID3D11ShaderResourceView* roughnessMetallicAmbientOcclusion); - DIRECTX_TOOLKIT_API void __cdecl SetIBLTextures( - _In_opt_ ID3D11ShaderResourceView* radiance, - int numRadianceMips, - _In_opt_ ID3D11ShaderResourceView* irradiance); + DIRECTX_TOOLKIT_API void __cdecl SetIBLTextures(_In_opt_ ID3D11ShaderResourceView* radiance, + int numRadianceMips, + _In_opt_ ID3D11ShaderResourceView* irradiance); // Normal compression settings. DIRECTX_TOOLKIT_API void __cdecl SetBiasedVertexNormals(bool value); @@ -806,15 +781,15 @@ namespace DirectX class DIRECTX_TOOLKIT_API SkinnedPBREffect : public PBREffect, public IEffectSkinning { public: - explicit SkinnedPBREffect(_In_ ID3D11Device* device) : - PBREffect(device, true) + explicit SkinnedPBREffect(_In_ ID3D11Device* device) + : PBREffect(device, 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; @@ -831,28 +806,27 @@ 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 explicit DebugEffect(_In_ ID3D11Device* device); - 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -888,29 +862,28 @@ 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 explicit NPREffect(_In_ ID3D11Device* device) : - NPREffect(device, false) + DIRECTX_TOOLKIT_API inline explicit NPREffect(_In_ ID3D11Device* device) + : NPREffect(device, 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; // IEffect methods. DIRECTX_TOOLKIT_API void __cdecl Apply(_In_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode( - _Out_ void const** pShaderByteCode, - _Out_ size_t* pByteCodeLength) override; + DIRECTX_TOOLKIT_API void __cdecl GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, + _Out_ size_t* pByteCodeLength) override; // Camera settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetWorld(FXMMATRIX value) override; @@ -986,15 +959,15 @@ namespace DirectX class DIRECTX_TOOLKIT_API SkinnedNPREffect : public NPREffect, public IEffectSkinning { public: - explicit SkinnedNPREffect(_In_ ID3D11Device* device) : - NPREffect(device, true) + explicit SkinnedNPREffect(_In_ ID3D11Device* device) + : NPREffect(device, 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; @@ -1011,86 +984,82 @@ namespace DirectX public: virtual ~IEffectFactory() = default; - IEffectFactory(const IEffectFactory&) = delete; + IEffectFactory(const IEffectFactory&) = delete; IEffectFactory& operator=(const IEffectFactory&) = delete; struct DIRECTX_TOOLKIT_API EffectInfo { - const wchar_t* name; - bool perVertexColor; - bool enableSkinning; - bool enableDualTexture; - bool enableNormalMaps; - bool biasedVertexNormals; - float specularPower; - float alpha; - XMFLOAT3 ambientColor; - XMFLOAT3 diffuseColor; - XMFLOAT3 specularColor; - XMFLOAT3 emissiveColor; - const wchar_t* diffuseTexture; - const wchar_t* specularTexture; - const wchar_t* normalTexture; - const wchar_t* emissiveTexture; - - EffectInfo() noexcept : - name(nullptr), - perVertexColor(false), - enableSkinning(false), - enableDualTexture(false), - enableNormalMaps(false), - biasedVertexNormals(false), - specularPower(0), - alpha(0), - ambientColor(0, 0, 0), - diffuseColor(0, 0, 0), - specularColor(0, 0, 0), - emissiveColor(0, 0, 0), - diffuseTexture(nullptr), - specularTexture(nullptr), - normalTexture(nullptr), - emissiveTexture(nullptr) + const wchar_t* name; + bool perVertexColor; + bool enableSkinning; + bool enableDualTexture; + bool enableNormalMaps; + bool biasedVertexNormals; + float specularPower; + float alpha; + XMFLOAT3 ambientColor; + XMFLOAT3 diffuseColor; + XMFLOAT3 specularColor; + XMFLOAT3 emissiveColor; + const wchar_t* diffuseTexture; + const wchar_t* specularTexture; + const wchar_t* normalTexture; + const wchar_t* emissiveTexture; + + EffectInfo() noexcept + : name(nullptr), + perVertexColor(false), + enableSkinning(false), + enableDualTexture(false), + enableNormalMaps(false), + biasedVertexNormals(false), + specularPower(0), + alpha(0), + ambientColor(0, 0, 0), + diffuseColor(0, 0, 0), + specularColor(0, 0, 0), + emissiveColor(0, 0, 0), + diffuseTexture(nullptr), + specularTexture(nullptr), + normalTexture(nullptr), + emissiveTexture(nullptr) {} }; - virtual std::shared_ptr __cdecl CreateEffect( - _In_ const EffectInfo& info, - _In_opt_ ID3D11DeviceContext* deviceContext) = 0; + virtual std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext) + = 0; - virtual void __cdecl CreateTexture( - _In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) = 0; + virtual void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) + = 0; protected: - IEffectFactory() = default; - IEffectFactory(IEffectFactory&&) = default; + IEffectFactory() = default; + IEffectFactory(IEffectFactory&&) = default; IEffectFactory& operator=(IEffectFactory&&) = default; }; - // Factory for sharing effects and texture resources class EffectFactory : public IEffectFactory { public: DIRECTX_TOOLKIT_API explicit EffectFactory(_In_ ID3D11Device* device); - 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 std::shared_ptr __cdecl CreateEffect( - _In_ const EffectInfo& info, - _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture( - _In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, + _In_opt_ ID3D11DeviceContext* deviceContext) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // Settings. DIRECTX_TOOLKIT_API void __cdecl ReleaseCache(); @@ -1112,29 +1081,26 @@ namespace DirectX std::shared_ptr pImpl; }; - // Factory for Physically Based Rendering (PBR) class PBREffectFactory : public IEffectFactory { public: DIRECTX_TOOLKIT_API explicit PBREffectFactory(_In_ ID3D11Device* device); - 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 std::shared_ptr __cdecl CreateEffect( - _In_ const EffectInfo& info, - _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture( - _In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, + _In_opt_ ID3D11DeviceContext* deviceContext) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // Settings. DIRECTX_TOOLKIT_API void __cdecl ReleaseCache(); @@ -1155,29 +1121,26 @@ namespace DirectX std::shared_ptr pImpl; }; - // Factory for Non-Photorealistic Rendering (NPR) class NPREffectFactory : public IEffectFactory { public: DIRECTX_TOOLKIT_API explicit NPREffectFactory(_In_ ID3D11Device* device); - 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 std::shared_ptr __cdecl CreateEffect( - _In_ const EffectInfo& info, - _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture( - _In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, + _In_opt_ ID3D11DeviceContext* deviceContext) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // Settings. DIRECTX_TOOLKIT_API void __cdecl ReleaseCache(); @@ -1204,29 +1167,26 @@ namespace DirectX std::shared_ptr pImpl; }; - // Factory for sharing Visual Studio Shader Designer (DGSL) shaders and texture resources class DGSLEffectFactory : public IEffectFactory { public: DIRECTX_TOOLKIT_API explicit DGSLEffectFactory(_In_ ID3D11Device* device); - DIRECTX_TOOLKIT_API DGSLEffectFactory(DGSLEffectFactory&&) noexcept; - DIRECTX_TOOLKIT_API DGSLEffectFactory& operator= (DGSLEffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API DGSLEffectFactory(DGSLEffectFactory&&) noexcept; + DIRECTX_TOOLKIT_API DGSLEffectFactory& operator=(DGSLEffectFactory&&) noexcept; - DGSLEffectFactory(DGSLEffectFactory const&) = delete; - DGSLEffectFactory& operator= (DGSLEffectFactory const&) = delete; + DGSLEffectFactory(DGSLEffectFactory const&) = delete; + DGSLEffectFactory& operator=(DGSLEffectFactory const&) = delete; DIRECTX_TOOLKIT_API ~DGSLEffectFactory() override; // IEffectFactory methods. - DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect( - _In_ const EffectInfo& info, - _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture( - _In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, + _In_opt_ ID3D11DeviceContext* deviceContext) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // DGSL methods. struct DIRECTX_TOOLKIT_API DGSLEffectInfo : public EffectInfo @@ -1236,20 +1196,18 @@ namespace DirectX const wchar_t* textures[DGSLEffect::MaxTextures - BaseTextureOffset]; const wchar_t* pixelShader; - DGSLEffectInfo() noexcept : - EffectInfo(), - textures{}, - pixelShader(nullptr) + DGSLEffectInfo() noexcept + : EffectInfo(), + textures{}, + pixelShader(nullptr) {} }; - DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateDGSLEffect( - _In_ const DGSLEffectInfo& info, - _In_opt_ ID3D11DeviceContext* deviceContext); + DIRECTX_TOOLKIT_API virtual std::shared_ptr __cdecl CreateDGSLEffect(_In_ const DGSLEffectInfo& info, + _In_opt_ ID3D11DeviceContext* deviceContext); - DIRECTX_TOOLKIT_API virtual void __cdecl CreatePixelShader( - _In_z_ const wchar_t* shader, - _Outptr_ ID3D11PixelShader** pixelShader); + DIRECTX_TOOLKIT_API virtual void __cdecl CreatePixelShader(_In_z_ const wchar_t* shader, + _Outptr_ ID3D11PixelShader** pixelShader); // Settings. DIRECTX_TOOLKIT_API void __cdecl ReleaseCache(); @@ -1269,8 +1227,8 @@ namespace DirectX std::shared_ptr pImpl; }; - } -} + } // namespace DX11 +} // 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..8b92fddf 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,40 @@ 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 +359,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 051a9b49..b97828b0 100644 --- a/Inc/GeometricPrimitive.h +++ b/Inc/GeometricPrimitive.h @@ -22,13 +22,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 @@ -37,7 +37,6 @@ #endif #endif - namespace DirectX { inline namespace DX11 @@ -47,164 +46,162 @@ 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; - using VertexType = VertexPositionNormalTexture; + using VertexType = VertexPositionNormalTexture; using VertexCollection = std::vector; - using IndexCollection = std::vector; + using IndexCollection = std::vector; DIRECTX_TOOLKIT_API virtual ~GeometricPrimitive(); // Factory methods. - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCube( - _In_ ID3D11DeviceContext* deviceContext, - float size = 1, bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateBox( - _In_ ID3D11DeviceContext* deviceContext, - const XMFLOAT3& size, - bool rhcoords = true, bool invertn = false); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateSphere( - _In_ ID3D11DeviceContext* deviceContext, - float diameter = 1, size_t tessellation = 16, - bool rhcoords = true, bool invertn = false); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateGeoSphere( - _In_ ID3D11DeviceContext* deviceContext, - float diameter = 1, size_t tessellation = 3, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCylinder( - _In_ ID3D11DeviceContext* deviceContext, - float height = 1, float diameter = 1, size_t tessellation = 32, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCone( - _In_ ID3D11DeviceContext* deviceContext, - float diameter = 1, float height = 1, size_t tessellation = 32, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTorus( - _In_ ID3D11DeviceContext* deviceContext, - float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, - bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCube(_In_ ID3D11DeviceContext* deviceContext, + float size = 1, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateBox(_In_ ID3D11DeviceContext* deviceContext, + const XMFLOAT3& size, + bool rhcoords = true, + bool invertn = false); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateSphere(_In_ ID3D11DeviceContext* deviceContext, + float diameter = 1, + size_t tessellation = 16, + bool rhcoords = true, + bool invertn = false); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateGeoSphere(_In_ ID3D11DeviceContext* deviceContext, + float diameter = 1, + size_t tessellation = 3, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCylinder(_In_ ID3D11DeviceContext* deviceContext, + float height = 1, + float diameter = 1, + size_t tessellation = 32, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCone(_In_ ID3D11DeviceContext* deviceContext, + float diameter = 1, + float height = 1, + size_t tessellation = 32, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTorus(_In_ ID3D11DeviceContext* deviceContext, + float diameter = 1, + float thickness = 0.333f, + size_t tessellation = 32, + bool rhcoords = true); DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTetrahedron( _In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateOctahedron( - _In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); + float size = 1, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateOctahedron(_In_ ID3D11DeviceContext* deviceContext, + float size = 1, + bool rhcoords = true); DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateDodecahedron( _In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); + float size = 1, + bool rhcoords = true); DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateIcosahedron( _In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTeapot( - _In_ ID3D11DeviceContext* deviceContext, - float size = 1, size_t tessellation = 8, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCustom( - _In_ ID3D11DeviceContext* deviceContext, - const VertexCollection& vertices, - const IndexCollection& indices); + float size = 1, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTeapot(_In_ ID3D11DeviceContext* deviceContext, + float size = 1, + size_t tessellation = 8, + bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCustom(_In_ ID3D11DeviceContext* deviceContext, + const VertexCollection& vertices, + const IndexCollection& indices); // Vertex/Index methods. - 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 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); // Draw the primitive. - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - FXMVECTOR color = Colors::White, - _In_opt_ ID3D11ShaderResourceView* texture = nullptr, - bool wireframe = false, - _In_ std::function setCustomState = nullptr) const; + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + FXMVECTOR color = Colors::White, + _In_opt_ ID3D11ShaderResourceView* texture = nullptr, + bool wireframe = false, + _In_ std::function setCustomState = nullptr) const; // Draw the primitive using a custom effect. - DIRECTX_TOOLKIT_API void __cdecl Draw( - _In_ IEffect* effect, - _In_ ID3D11InputLayout* inputLayout, - bool alpha = false, bool wireframe = false, - _In_ std::function setCustomState = nullptr) const; - - DIRECTX_TOOLKIT_API void __cdecl DrawInstanced( - _In_ IEffect* effect, - _In_ ID3D11InputLayout* inputLayout, - uint32_t instanceCount, - bool alpha = false, bool wireframe = false, - uint32_t startInstanceLocation = 0, - _In_ std::function setCustomState = nullptr) const; + DIRECTX_TOOLKIT_API void __cdecl Draw(_In_ IEffect* effect, + _In_ ID3D11InputLayout* inputLayout, + bool alpha = false, + bool wireframe = false, + _In_ std::function setCustomState = nullptr) const; + + DIRECTX_TOOLKIT_API void __cdecl DrawInstanced(_In_ IEffect* effect, + _In_ ID3D11InputLayout* inputLayout, + uint32_t instanceCount, + bool alpha = false, + bool wireframe = false, + uint32_t startInstanceLocation = 0, + _In_ std::function setCustomState = nullptr) const; // Create input layout for drawing with a custom effect. - DIRECTX_TOOLKIT_API void __cdecl CreateInputLayout( - _In_ IEffect* effect, - _Outptr_ ID3D11InputLayout** inputLayout) const; + DIRECTX_TOOLKIT_API void __cdecl CreateInputLayout(_In_ IEffect* effect, _Outptr_ ID3D11InputLayout** inputLayout) const; - DIRECTX_TOOLKIT_API static inline void SetDepthBufferMode(bool reverseZ) - { - s_reversez = reverseZ; - } + DIRECTX_TOOLKIT_API static inline void SetDepthBufferMode(bool reverseZ) { s_reversez = reverseZ; } private: DIRECTX_TOOLKIT_API static bool s_reversez; @@ -216,5 +213,5 @@ namespace DirectX std::unique_ptr pImpl; }; - } -} + } // namespace DX11 +} // namespace DirectX diff --git a/Inc/GraphicsMemory.h b/Inc/GraphicsMemory.h index 3113a955..e0d8ecc6 100644 --- a/Inc/GraphicsMemory.h +++ b/Inc/GraphicsMemory.h @@ -21,13 +21,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 @@ -36,7 +36,6 @@ #endif #endif - namespace DirectX { inline namespace DX11 @@ -45,28 +44,21 @@ namespace DirectX { public: DIRECTX_TOOLKIT_API - #if defined(_XBOX_ONE) && defined(_TITLE) - GraphicsMemory( - _In_ ID3D11DeviceX* device, - unsigned int backBufferCount = 2); - #else - GraphicsMemory( - _In_ ID3D11Device* device, - unsigned int backBufferCount = 2); - #endif +#if defined(_XBOX_ONE) && defined(_TITLE) + GraphicsMemory(_In_ ID3D11DeviceX* device, unsigned int backBufferCount = 2); +#else + GraphicsMemory(_In_ ID3D11Device* device, unsigned int backBufferCount = 2); +#endif - 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(); - DIRECTX_TOOLKIT_API void* __cdecl Allocate( - _In_opt_ ID3D11DeviceContext* context, - size_t size, - int alignment); + DIRECTX_TOOLKIT_API void* __cdecl Allocate(_In_opt_ ID3D11DeviceContext* context, size_t size, int alignment); DIRECTX_TOOLKIT_API void __cdecl Commit(); @@ -79,5 +71,5 @@ namespace DirectX std::unique_ptr pImpl; }; - } -} + } // namespace DX11 +} // namespace DirectX 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 0acca615..3eb99dc7 100644 --- a/Inc/Model.h +++ b/Inc/Model.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 @@ -55,7 +55,6 @@ #pragma warning(disable : 4251) #endif - namespace DirectX { inline namespace DX11 @@ -69,41 +68,44 @@ namespace DirectX // Model loading options enum ModelLoaderFlags : uint32_t { - ModelLoader_Clockwise = 0x0, - ModelLoader_CounterClockwise = 0x1, - ModelLoader_PremultipledAlpha = 0x2, + ModelLoader_Clockwise = 0x0, + ModelLoader_CounterClockwise = 0x1, + ModelLoader_PremultipledAlpha = 0x2, ModelLoader_MaterialColorsSRGB = 0x4, - ModelLoader_AllowLargeModels = 0x8, - ModelLoader_IncludeBones = 0x10, - ModelLoader_DisableSkinning = 0x20, + ModelLoader_AllowLargeModels = 0x8, + ModelLoader_IncludeBones = 0x10, + ModelLoader_DisableSkinning = 0x20, }; //------------------------------------------------------------------------------ // 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; @@ -116,7 +118,6 @@ namespace DirectX } }; - //------------------------------------------------------------------------------ // Each mesh part is a submesh with a single effect class DIRECTX_TOOLKIT_API ModelMeshPart @@ -124,53 +125,52 @@ namespace DirectX public: ModelMeshPart() 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 Collection = std::vector>; using InputLayoutCollection = std::vector; - uint32_t indexCount; - uint32_t startIndex; - int32_t vertexOffset; - uint32_t vertexStride; - D3D_PRIMITIVE_TOPOLOGY primitiveType; - DXGI_FORMAT indexFormat; - Microsoft::WRL::ComPtr inputLayout; - Microsoft::WRL::ComPtr indexBuffer; - Microsoft::WRL::ComPtr vertexBuffer; - std::shared_ptr effect; - std::shared_ptr vbDecl; - bool isAlpha; + uint32_t indexCount; + uint32_t startIndex; + int32_t vertexOffset; + uint32_t vertexStride; + D3D_PRIMITIVE_TOPOLOGY primitiveType; + DXGI_FORMAT indexFormat; + Microsoft::WRL::ComPtr inputLayout; + Microsoft::WRL::ComPtr indexBuffer; + Microsoft::WRL::ComPtr vertexBuffer; + std::shared_ptr effect; + std::shared_ptr vbDecl; + bool isAlpha; // Draw mesh part with custom effect - void __cdecl Draw( - _In_ ID3D11DeviceContext* deviceContext, - _In_ IEffect* ieffect, - _In_ ID3D11InputLayout* iinputLayout, + void __cdecl Draw(_In_ ID3D11DeviceContext* deviceContext, + _In_ IEffect* ieffect, + _In_ ID3D11InputLayout* iinputLayout, _In_ std::function setCustomState = nullptr) const; - void __cdecl DrawInstanced( - _In_ ID3D11DeviceContext* deviceContext, - _In_ IEffect* ieffect, - _In_ ID3D11InputLayout* iinputLayout, - uint32_t instanceCount, - uint32_t startInstanceLocation = 0, - _In_ std::function setCustomState = nullptr) const; + void __cdecl DrawInstanced(_In_ ID3D11DeviceContext* deviceContext, + _In_ IEffect* ieffect, + _In_ ID3D11InputLayout* iinputLayout, + uint32_t instanceCount, + uint32_t startInstanceLocation = 0, + _In_ std::function setCustomState = nullptr) const; // Create input layout for drawing with a custom effect. - void __cdecl CreateInputLayout(_In_ ID3D11Device* device, _In_ IEffect* ieffect, _Outptr_ ID3D11InputLayout** iinputLayout) const; + void __cdecl CreateInputLayout(_In_ ID3D11Device* device, + _In_ IEffect* ieffect, + _Outptr_ ID3D11InputLayout** iinputLayout) const; // Change effect used by part and regenerate input layout (be sure to call Model::Modified as well) void __cdecl ModifyEffect(_In_ ID3D11Device* device, _In_ const std::shared_ptr& ieffect, bool isalpha = false); }; - //------------------------------------------------------------------------------ // A mesh consists of one or more model mesh parts class DIRECTX_TOOLKIT_API ModelMesh @@ -178,65 +178,65 @@ 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 meshParts; - uint32_t boneIndex; - std::vector boneInfluences; - std::wstring name; - bool ccw; - bool pmalpha; + BoundingSphere boundingSphere; + BoundingBox boundingBox; + ModelMeshPart::Collection meshParts; + uint32_t boneIndex; + std::vector boneInfluences; + std::wstring name; + bool ccw; + bool pmalpha; using Collection = std::vector>; // Setup states for drawing mesh - void __cdecl PrepareForRendering( - _In_ ID3D11DeviceContext* deviceContext, - const CommonStates& states, - bool alpha = false, - bool wireframe = false) const; + void __cdecl PrepareForRendering(_In_ ID3D11DeviceContext* deviceContext, + const CommonStates& states, + bool alpha = false, + bool wireframe = false) const; // Draw the mesh - void XM_CALLCONV Draw( - _In_ ID3D11DeviceContext* deviceContext, - FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - bool alpha = false, + void XM_CALLCONV Draw(_In_ ID3D11DeviceContext* deviceContext, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool alpha = false, _In_ std::function setCustomState = nullptr) const; // Draw the mesh using model bones - void XM_CALLCONV Draw( - _In_ ID3D11DeviceContext* deviceContext, - size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - bool alpha = false, + void XM_CALLCONV Draw(_In_ ID3D11DeviceContext* deviceContext, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool alpha = false, _In_ std::function setCustomState = nullptr) const; // Draw the mesh using skinning - void XM_CALLCONV DrawSkinned( - _In_ ID3D11DeviceContext* deviceContext, - size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - bool alpha = false, - _In_ std::function setCustomState = nullptr) const; + void XM_CALLCONV DrawSkinned(_In_ ID3D11DeviceContext* deviceContext, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool alpha = false, + _In_ std::function setCustomState = nullptr) const; - static void SetDepthBufferMode(bool reverseZ) - { - s_reversez = reverseZ; - } + static void SetDepthBufferMode(bool reverseZ) { s_reversez = reverseZ; } private: static bool s_reversez; }; - //------------------------------------------------------------------------------ // A model consists of one or more meshes class DIRECTX_TOOLKIT_API Model @@ -244,65 +244,63 @@ namespace DirectX public: Model() = default; - 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(); - ModelMesh::Collection meshes; - ModelBone::Collection bones; - ModelBone::TransformArray boneMatrices; - ModelBone::TransformArray invBindPoseMatrices; - std::wstring name; + ModelMesh::Collection meshes; + ModelBone::Collection bones; + ModelBone::TransformArray boneMatrices; + ModelBone::TransformArray invBindPoseMatrices; + std::wstring name; // Draw all the meshes in the model - void XM_CALLCONV Draw( - _In_ ID3D11DeviceContext* deviceContext, - const CommonStates& states, - FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - bool wireframe = false, - _In_ std::function setCustomState = nullptr) const; + void XM_CALLCONV Draw(_In_ ID3D11DeviceContext* deviceContext, + const CommonStates& states, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool wireframe = false, + _In_ std::function setCustomState = nullptr) const; // Draw all the meshes using model bones - void XM_CALLCONV Draw( - _In_ ID3D11DeviceContext* deviceContext, - const CommonStates& states, - size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - bool wireframe = false, - _In_ std::function setCustomState = nullptr) const; + void XM_CALLCONV Draw(_In_ ID3D11DeviceContext* deviceContext, + const CommonStates& states, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool wireframe = false, + _In_ std::function setCustomState = nullptr) const; // Draw all the meshes using skinning - void XM_CALLCONV DrawSkinned( - _In_ ID3D11DeviceContext* deviceContext, - const CommonStates& states, - size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms, - FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - bool wireframe = false, - _In_ std::function setCustomState = nullptr) const; + void XM_CALLCONV DrawSkinned(_In_ ID3D11DeviceContext* deviceContext, + const CommonStates& states, + size_t nbones, + _In_reads_(nbones) const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool wireframe = false, + _In_ std::function setCustomState = nullptr) 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; // Notify model that effects, parts list, or mesh list has changed void __cdecl Modified() noexcept { mEffectCache.clear(); } @@ -311,116 +309,111 @@ namespace DirectX void __cdecl UpdateEffects(_In_ std::function setEffect); // Loads a model from a Visual Studio Starter Kit .CMO file - static std::unique_ptr __cdecl CreateFromCMO( - _In_ ID3D11Device* device, - _In_reads_bytes_(dataSize) const uint8_t* meshData, size_t dataSize, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_CounterClockwise, - _Out_opt_ size_t* animsOffset = nullptr); - static std::unique_ptr __cdecl CreateFromCMO( - _In_ ID3D11Device* device, - _In_z_ const wchar_t* szFileName, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_CounterClockwise, - _Out_opt_ size_t* animsOffset = nullptr); + static std::unique_ptr __cdecl CreateFromCMO(_In_ ID3D11Device* device, + _In_reads_bytes_(dataSize) const uint8_t* meshData, + size_t dataSize, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_CounterClockwise, + _Out_opt_ size_t* animsOffset = nullptr); + static std::unique_ptr __cdecl CreateFromCMO(_In_ ID3D11Device* device, + _In_z_ const wchar_t* szFileName, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_CounterClockwise, + _Out_opt_ size_t* animsOffset = nullptr); // Loads a model from a DirectX SDK .SDKMESH file - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_ ID3D11Device* device, - _In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_Clockwise); - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_ ID3D11Device* device, - _In_z_ const wchar_t* szFileName, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_Clockwise); + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_ ID3D11Device* device, + _In_reads_bytes_(dataSize) const uint8_t* meshData, + _In_ size_t dataSize, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_Clockwise); + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_ ID3D11Device* device, + _In_z_ const wchar_t* szFileName, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_Clockwise); // Loads a model from a .VBO file - static std::unique_ptr __cdecl CreateFromVBO( - _In_ ID3D11Device* device, - _In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize, + static std::unique_ptr __cdecl CreateFromVBO(_In_ ID3D11Device* device, + _In_reads_bytes_(dataSize) const uint8_t* meshData, + _In_ size_t dataSize, _In_ std::shared_ptr ieffect = nullptr, - ModelLoaderFlags flags = ModelLoader_Clockwise); - static std::unique_ptr __cdecl CreateFromVBO( - _In_ ID3D11Device* device, - _In_z_ const wchar_t* szFileName, + ModelLoaderFlags flags = ModelLoader_Clockwise); + static std::unique_ptr __cdecl CreateFromVBO(_In_ ID3D11Device* device, + _In_z_ const wchar_t* szFileName, _In_ std::shared_ptr ieffect = nullptr, - ModelLoaderFlags flags = ModelLoader_Clockwise); - - #ifdef __cpp_lib_byte - static std::unique_ptr __cdecl CreateFromCMO( - _In_ ID3D11Device* device, - _In_reads_bytes_(dataSize) const std::byte* meshData, size_t dataSize, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_CounterClockwise, - _Out_opt_ size_t* animsOffset = nullptr) + ModelLoaderFlags flags = ModelLoader_Clockwise); + +#ifdef __cpp_lib_byte + static std::unique_ptr __cdecl CreateFromCMO(_In_ ID3D11Device* device, + _In_reads_bytes_(dataSize) const std::byte* meshData, + size_t dataSize, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_CounterClockwise, + _Out_opt_ size_t* animsOffset = nullptr) { return CreateFromCMO(device, reinterpret_cast(meshData), dataSize, fxFactory, flags, animsOffset); } - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_ ID3D11Device* device, - _In_reads_bytes_(dataSize) const std::byte* meshData, _In_ size_t dataSize, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_Clockwise) + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_ ID3D11Device* device, + _In_reads_bytes_(dataSize) const std::byte* meshData, + _In_ size_t dataSize, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_Clockwise) { return CreateFromSDKMESH(device, reinterpret_cast(meshData), dataSize, fxFactory, flags); } - static std::unique_ptr __cdecl CreateFromVBO( - _In_ ID3D11Device* device, - _In_reads_bytes_(dataSize) const std::byte* meshData, _In_ size_t dataSize, + static std::unique_ptr __cdecl CreateFromVBO(_In_ ID3D11Device* device, + _In_reads_bytes_(dataSize) const std::byte* meshData, + _In_ size_t dataSize, _In_ std::shared_ptr ieffect = nullptr, - ModelLoaderFlags flags = ModelLoader_Clockwise) + ModelLoaderFlags flags = ModelLoader_Clockwise) { return CreateFromVBO(device, reinterpret_cast(meshData), dataSize, ieffect, flags); } - #endif // __cpp_lib_byte - - #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) - static std::unique_ptr __cdecl CreateFromCMO( - _In_ ID3D11Device* device, - _In_z_ const __wchar_t* szFileName, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_CounterClockwise, - _Out_opt_ size_t* animsOffset = nullptr); - - static std::unique_ptr __cdecl CreateFromSDKMESH( - _In_ ID3D11Device* device, - _In_z_ const __wchar_t* szFileName, - _In_ IEffectFactory& fxFactory, - ModelLoaderFlags flags = ModelLoader_Clockwise); - - static std::unique_ptr __cdecl CreateFromVBO( - _In_ ID3D11Device* device, - _In_z_ const __wchar_t* szFileName, +#endif // __cpp_lib_byte + +#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) + static std::unique_ptr __cdecl CreateFromCMO(_In_ ID3D11Device* device, + _In_z_ const __wchar_t* szFileName, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_CounterClockwise, + _Out_opt_ size_t* animsOffset = nullptr); + + static std::unique_ptr __cdecl CreateFromSDKMESH(_In_ ID3D11Device* device, + _In_z_ const __wchar_t* szFileName, + _In_ IEffectFactory& fxFactory, + ModelLoaderFlags flags = ModelLoader_Clockwise); + + static std::unique_ptr __cdecl CreateFromVBO(_In_ ID3D11Device* device, + _In_z_ const __wchar_t* szFileName, _In_ std::shared_ptr ieffect = nullptr, - ModelLoaderFlags flags = ModelLoader_Clockwise); - #endif // !_NATIVE_WCHAR_T_DEFINED + ModelLoaderFlags flags = ModelLoader_Clockwise); +#endif // !_NATIVE_WCHAR_T_DEFINED private: - std::set mEffectCache; + std::set mEffectCache; - void __cdecl ComputeAbsolute(uint32_t index, - CXMMATRIX local, size_t nbones, + 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; }; - #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 DX11 +} // 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..d2d2137f 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) +#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 559a7a57..b0b2c21f 100644 --- a/Inc/PostProcess.h +++ b/Inc/PostProcess.h @@ -24,13 +24,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 @@ -39,7 +39,6 @@ #endif #endif - namespace DirectX { inline namespace DX11 @@ -51,20 +50,19 @@ namespace DirectX public: virtual ~IPostProcess() = default; - IPostProcess(const IPostProcess&) = delete; + IPostProcess(const IPostProcess&) = delete; IPostProcess& operator=(const IPostProcess&) = delete; - virtual void __cdecl Process( - _In_ ID3D11DeviceContext* deviceContext, - _In_ std::function setCustomState = nullptr) = 0; + virtual void __cdecl Process(_In_ ID3D11DeviceContext* deviceContext, + _In_ std::function setCustomState = nullptr) + = 0; protected: - IPostProcess() = default; - IPostProcess(IPostProcess&&) = default; + IPostProcess() = default; + IPostProcess(IPostProcess&&) = default; IPostProcess& operator=(IPostProcess&&) = default; }; - //------------------------------------------------------------------------------ // Basic post-process class BasicPostProcess : public IPostProcess @@ -85,17 +83,16 @@ namespace DirectX DIRECTX_TOOLKIT_API explicit BasicPostProcess(_In_ ID3D11Device* device); - 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; // IPostProcess methods. - DIRECTX_TOOLKIT_API void __cdecl Process( - _In_ ID3D11DeviceContext* deviceContext, + DIRECTX_TOOLKIT_API void __cdecl Process(_In_ ID3D11DeviceContext* deviceContext, _In_ std::function setCustomState = nullptr) override; // Shader control @@ -120,7 +117,6 @@ namespace DirectX std::unique_ptr pImpl; }; - //------------------------------------------------------------------------------ // Dual-texure post-process class DualPostProcess : public IPostProcess @@ -135,17 +131,16 @@ namespace DirectX DIRECTX_TOOLKIT_API explicit DualPostProcess(_In_ ID3D11Device* device); - 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; // IPostProcess methods. - DIRECTX_TOOLKIT_API void __cdecl Process( - _In_ ID3D11DeviceContext* deviceContext, + DIRECTX_TOOLKIT_API void __cdecl Process(_In_ ID3D11DeviceContext* deviceContext, _In_ std::function setCustomState = nullptr) override; // Shader control @@ -159,7 +154,10 @@ 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 +166,6 @@ namespace DirectX std::unique_ptr pImpl; }; - //------------------------------------------------------------------------------ // Tone-map post-process class ToneMapPostProcess : public IPostProcess @@ -177,9 +174,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 +184,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 }; @@ -203,17 +200,16 @@ namespace DirectX DIRECTX_TOOLKIT_API explicit ToneMapPostProcess(_In_ ID3D11Device* device); - 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; // IPostProcess methods. - DIRECTX_TOOLKIT_API void __cdecl Process( - _In_ ID3D11DeviceContext* deviceContext, + DIRECTX_TOOLKIT_API void __cdecl Process(_In_ ID3D11DeviceContext* deviceContext, _In_ std::function setCustomState = nullptr) override; // Shader control @@ -221,10 +217,10 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetTransferFunction(TransferFunction func); - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) // Uses Multiple Render Targets to generate both HDR10 and GameDVR SDR signals DIRECTX_TOOLKIT_API void __cdecl SetMRTOutput(bool value = true); - #endif +#endif // Properties DIRECTX_TOOLKIT_API void __cdecl SetHDRSourceTexture(_In_opt_ ID3D11ShaderResourceView* value); @@ -245,5 +241,5 @@ namespace DirectX std::unique_ptr pImpl; }; - } -} + } // namespace DX11 +} // namespace DirectX diff --git a/Inc/PrimitiveBatch.h b/Inc/PrimitiveBatch.h index 9e321ae4..899f4643 100644 --- a/Inc/PrimitiveBatch.h +++ b/Inc/PrimitiveBatch.h @@ -24,13 +24,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 @@ -39,25 +39,23 @@ #endif #endif - namespace DirectX { inline namespace DX11 { namespace Private { - // Base class, not to be used directly: clients should access this via the derived PrimitiveBatch. + // Base class, not to be used directly: clients should access this via the derived PrimitiveBatch. class PrimitiveBatchBase { protected: - DIRECTX_TOOLKIT_API PrimitiveBatchBase( - _In_ ID3D11DeviceContext* deviceContext, - 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(_In_ ID3D11DeviceContext* deviceContext, size_t maxIndices, size_t maxVertices, size_t vertexSize); + 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(); @@ -68,11 +66,12 @@ namespace DirectX protected: // Internal, untyped drawing method. - DIRECTX_TOOLKIT_API void __cdecl Draw( - D3D11_PRIMITIVE_TOPOLOGY topology, - bool isIndexed, _In_opt_count_(indexCount) uint16_t const* indices, - size_t indexCount, size_t vertexCount, - _Out_ void** pMappedVertices); + DIRECTX_TOOLKIT_API void __cdecl Draw(D3D11_PRIMITIVE_TOPOLOGY topology, + bool isIndexed, + _In_opt_count_(indexCount) uint16_t const* indices, + size_t indexCount, + size_t vertexCount, + _Out_ void** pMappedVertices); private: // Private implementation. @@ -80,7 +79,7 @@ namespace DirectX std::unique_ptr pImpl; }; - } + } // namespace Private // Template makes the API typesafe, eg. PrimitiveBatch. template @@ -89,22 +88,20 @@ namespace DirectX static constexpr size_t DefaultBatchSize = 2048; public: - explicit PrimitiveBatch( - _In_ ID3D11DeviceContext* deviceContext, - size_t maxIndices = DefaultBatchSize * 3, size_t maxVertices = DefaultBatchSize) + explicit PrimitiveBatch(_In_ ID3D11DeviceContext* deviceContext, + size_t maxIndices = DefaultBatchSize * 3, + size_t maxVertices = DefaultBatchSize) : PrimitiveBatchBase(deviceContext, 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( - D3D11_PRIMITIVE_TOPOLOGY topology, - _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount) + void Draw(D3D11_PRIMITIVE_TOPOLOGY topology, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount) { void* mappedVertices; @@ -113,12 +110,12 @@ namespace DirectX memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex)); } - // Similar to the D3D9 API DrawIndexedPrimitiveUP. - void DrawIndexed( - D3D11_PRIMITIVE_TOPOLOGY topology, - _In_reads_(indexCount) uint16_t const* indices, size_t indexCount, - _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount) + void DrawIndexed(D3D11_PRIMITIVE_TOPOLOGY topology, + _In_reads_(indexCount) uint16_t const* indices, + size_t indexCount, + _In_reads_(vertexCount) TVertex const* vertices, + size_t vertexCount) { void* mappedVertices; @@ -127,46 +124,49 @@ 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; - PrimitiveBatchBase::Draw(D3D11_PRIMITIVE_TOPOLOGY_LINELIST, false, nullptr, 0, 2, reinterpret_cast(&mappedVertices)); + PrimitiveBatchBase::Draw(D3D11_PRIMITIVE_TOPOLOGY_LINELIST, + false, + nullptr, + 0, + 2, + reinterpret_cast(&mappedVertices)); mappedVertices[0] = v1; 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(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, false, nullptr, 0, 3, reinterpret_cast(&mappedVertices)); + PrimitiveBatchBase::Draw(D3D11_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(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, true, quadIndices, 6, 4, reinterpret_cast(&mappedVertices)); + PrimitiveBatchBase::Draw(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + true, + quadIndices, + 6, + 4, + reinterpret_cast(&mappedVertices)); mappedVertices[0] = v1; mappedVertices[1] = v2; @@ -174,5 +174,5 @@ namespace DirectX mappedVertices[3] = v4; } }; - } -} + } // namespace DX11 +} // namespace DirectX diff --git a/Inc/ScreenGrab.h b/Inc/ScreenGrab.h index 5447c6aa..64c8ff45 100644 --- a/Inc/ScreenGrab.h +++ b/Inc/ScreenGrab.h @@ -32,19 +32,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 @@ -53,22 +53,19 @@ #endif #endif - namespace DirectX { DIRECTX_TOOLKIT_API - HRESULT __cdecl SaveDDSTextureToFile( - _In_ ID3D11DeviceContext* pContext, - _In_ ID3D11Resource* pSource, - _In_z_ const wchar_t* fileName) noexcept; + HRESULT __cdecl SaveDDSTextureToFile(_In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_z_ const wchar_t* fileName) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl SaveWICTextureToFile( - _In_ ID3D11DeviceContext* pContext, - _In_ ID3D11Resource* pSource, - _In_ REFGUID guidContainerFormat, - _In_z_ const wchar_t* fileName, - _In_opt_ const GUID* targetFormat = nullptr, - _In_ std::function setCustomProps = nullptr, - _In_ bool forceSRGB = false); -} + HRESULT __cdecl SaveWICTextureToFile(_In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_ REFGUID guidContainerFormat, + _In_z_ const wchar_t* fileName, + _In_opt_ const GUID* targetFormat = nullptr, + _In_ std::function setCustomProps = nullptr, + _In_ bool forceSRGB = false); +} // namespace DirectX diff --git a/Inc/SimpleMath.h b/Inc/SimpleMath.h index d0d85657..2e64dbe1 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; @@ -771,13 +1148,13 @@ 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; @@ -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); } 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); } 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/SpriteBatch.h b/Inc/SpriteBatch.h index 14db7b8d..7256721b 100644 --- a/Inc/SpriteBatch.h +++ b/Inc/SpriteBatch.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 DX11 @@ -57,10 +56,10 @@ 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 SpriteBatch @@ -68,65 +67,82 @@ namespace DirectX public: DIRECTX_TOOLKIT_API explicit SpriteBatch(_In_ ID3D11DeviceContext* deviceContext); - 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( - SpriteSortMode sortMode = SpriteSortMode_Deferred, - _In_opt_ ID3D11BlendState* blendState = nullptr, - _In_opt_ ID3D11SamplerState* samplerState = nullptr, - _In_opt_ ID3D11DepthStencilState* depthStencilState = nullptr, - _In_opt_ ID3D11RasterizerState* rasterizerState = nullptr, - _In_ std::function setCustomShaders = nullptr, - FXMMATRIX transformMatrix = MatrixIdentity); + DIRECTX_TOOLKIT_API void XM_CALLCONV Begin(SpriteSortMode sortMode = SpriteSortMode_Deferred, + _In_opt_ ID3D11BlendState* blendState = nullptr, + _In_opt_ ID3D11SamplerState* samplerState = nullptr, + _In_opt_ ID3D11DepthStencilState* depthStencilState = nullptr, + _In_opt_ ID3D11RasterizerState* rasterizerState = nullptr, + _In_ std::function setCustomShaders = nullptr, + FXMMATRIX transformMatrix = MatrixIdentity); DIRECTX_TOOLKIT_API void __cdecl End(); // Draw overloads specifying position, origin and scale as XMFLOAT2. - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - _In_ ID3D11ShaderResourceView* texture, - XMFLOAT2 const& position, FXMVECTOR color = Colors::White); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - _In_ ID3D11ShaderResourceView* texture, - 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( - _In_ ID3D11ShaderResourceView* texture, - 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(_In_ ID3D11ShaderResourceView* texture, + XMFLOAT2 const& position, + FXMVECTOR color = Colors::White); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, + 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(_In_ ID3D11ShaderResourceView* texture, + 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( - _In_ ID3D11ShaderResourceView* texture, - FXMVECTOR position, FXMVECTOR color = Colors::White); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - _In_ ID3D11ShaderResourceView* texture, - 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( - _In_ ID3D11ShaderResourceView* texture, - 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(_In_ ID3D11ShaderResourceView* texture, + FXMVECTOR position, + FXMVECTOR color = Colors::White); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, + 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(_In_ ID3D11ShaderResourceView* texture, + 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( - _In_ ID3D11ShaderResourceView* texture, - RECT const& destinationRectangle, - FXMVECTOR color = Colors::White); - DIRECTX_TOOLKIT_API void XM_CALLCONV Draw( - _In_ ID3D11ShaderResourceView* texture, - 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(_In_ ID3D11ShaderResourceView* texture, + RECT const& destinationRectangle, + FXMVECTOR color = Colors::White); + DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, + 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 DIRECTX_TOOLKIT_API void __cdecl SetRotation(DXGI_MODE_ROTATION mode); @@ -147,5 +163,5 @@ namespace DirectX DIRECTX_TOOLKIT_API static const XMMATRIX MatrixIdentity; DIRECTX_TOOLKIT_API static const XMFLOAT2 Float2Zero; }; - } -} + } // namespace DX11 +} // namespace DirectX diff --git a/Inc/SpriteFont.h b/Inc/SpriteFont.h index 7d3fe4f5..ed115e19 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 DX11 @@ -43,104 +42,115 @@ namespace DirectX public: struct Glyph; - DIRECTX_TOOLKIT_API SpriteFont( - _In_ ID3D11Device* device, - _In_z_ wchar_t const* fileName, - bool forceSRGB = false); - DIRECTX_TOOLKIT_API SpriteFont( - _In_ ID3D11Device* device, - _In_reads_bytes_(dataSize) uint8_t const* dataBlob, _In_ size_t dataSize, - bool forceSRGB = false); - DIRECTX_TOOLKIT_API SpriteFont( - _In_ ID3D11ShaderResourceView* texture, - _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, - _In_ 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_ ID3D11Device* device, _In_z_ wchar_t const* fileName, bool forceSRGB = false); + DIRECTX_TOOLKIT_API SpriteFont(_In_ ID3D11Device* device, + _In_reads_bytes_(dataSize) uint8_t const* dataBlob, + _In_ size_t dataSize, + bool forceSRGB = false); + DIRECTX_TOOLKIT_API SpriteFont(_In_ ID3D11ShaderResourceView* texture, + _In_reads_(glyphCount) Glyph const* glyphs, + _In_ size_t glyphCount, + _In_ 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; @@ -162,62 +172,66 @@ namespace DirectX 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( - _In_ ID3D11Device* device, - _In_z_ __wchar_t const* fileName, - 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(_In_ ID3D11Device* device, _In_z_ __wchar_t const* fileName, 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. @@ -227,5 +241,5 @@ namespace DirectX DIRECTX_TOOLKIT_API static const XMFLOAT2 Float2Zero; }; - } -} + } // namespace DX11 +} // namespace DirectX diff --git a/Inc/VertexTypes.h b/Inc/VertexTypes.h index 728f1c92..ce365fa2 100644 --- a/Inc/VertexTypes.h +++ b/Inc/VertexTypes.h @@ -22,13 +22,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 @@ -42,52 +42,47 @@ #pragma warning(disable : 4251) #endif - namespace DirectX { inline namespace DX11 { - // 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 constexpr unsigned int InputElementCount = 1; + static constexpr unsigned int InputElementCount = 1; static const D3D11_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 @@ -99,25 +94,24 @@ namespace DirectX XMFLOAT3 position; XMFLOAT4 color; - static constexpr unsigned int InputElementCount = 2; + static constexpr unsigned int InputElementCount = 2; static const D3D11_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 @@ -129,35 +123,30 @@ namespace DirectX XMFLOAT3 position; XMFLOAT2 textureCoordinate; - static constexpr unsigned int InputElementCount = 2; + static constexpr unsigned int InputElementCount = 2; static const D3D11_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); @@ -168,25 +157,24 @@ namespace DirectX XMFLOAT2 textureCoordinate0; XMFLOAT2 textureCoordinate1; - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D11_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 @@ -198,26 +186,25 @@ namespace DirectX XMFLOAT3 position; XMFLOAT3 normal; - static constexpr unsigned int InputElementCount = 2; + static constexpr unsigned int InputElementCount = 2; static const D3D11_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 @@ -231,26 +218,25 @@ namespace DirectX XMFLOAT4 color; XMFLOAT2 textureCoordinate; - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D11_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 @@ -264,26 +250,25 @@ namespace DirectX XMFLOAT3 normal; XMFLOAT4 color; - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D11_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 @@ -297,34 +282,35 @@ namespace DirectX XMFLOAT3 normal; XMFLOAT2 textureCoordinate; - static constexpr unsigned int InputElementCount = 3; + static constexpr unsigned int InputElementCount = 3; static const D3D11_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); @@ -337,21 +323,20 @@ namespace DirectX XMFLOAT4 color; XMFLOAT2 textureCoordinate; - static constexpr unsigned int InputElementCount = 4; + static constexpr unsigned int InputElementCount = 4; static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct for Visual Studio Shader Designer (DGSL) holding position, normal, // tangent, color (RGBA), and texture mapping information struct DIRECTX_TOOLKIT_API VertexPositionNormalTangentColorTexture { VertexPositionNormalTangentColorTexture() = default; - VertexPositionNormalTangentColorTexture(const VertexPositionNormalTangentColorTexture&) = default; + VertexPositionNormalTangentColorTexture(const VertexPositionNormalTangentColorTexture&) = default; VertexPositionNormalTangentColorTexture& operator=(const VertexPositionNormalTangentColorTexture&) = default; - VertexPositionNormalTangentColorTexture(VertexPositionNormalTangentColorTexture&&) = default; + VertexPositionNormalTangentColorTexture(VertexPositionNormalTangentColorTexture&&) = default; VertexPositionNormalTangentColorTexture& operator=(VertexPositionNormalTangentColorTexture&&) = default; XMFLOAT3 position; @@ -360,25 +345,23 @@ namespace DirectX uint32_t color; XMFLOAT2 textureCoordinate; - VertexPositionNormalTangentColorTexture( - XMFLOAT3 const& iposition, - XMFLOAT3 const& inormal, - XMFLOAT4 const& itangent, - uint32_t irgba, - XMFLOAT2 const& itextureCoordinate) noexcept + VertexPositionNormalTangentColorTexture(XMFLOAT3 const& iposition, + XMFLOAT3 const& inormal, + XMFLOAT4 const& itangent, + uint32_t irgba, + XMFLOAT2 const& itextureCoordinate) noexcept : position(iposition), - normal(inormal), - tangent(itangent), - color(irgba), - textureCoordinate(itextureCoordinate) + normal(inormal), + tangent(itangent), + color(irgba), + textureCoordinate(itextureCoordinate) {} - VertexPositionNormalTangentColorTexture( - FXMVECTOR iposition, - FXMVECTOR inormal, - FXMVECTOR itangent, - uint32_t irgba, - CXMVECTOR itextureCoordinate) noexcept + VertexPositionNormalTangentColorTexture(FXMVECTOR iposition, + FXMVECTOR inormal, + FXMVECTOR itangent, + uint32_t irgba, + CXMVECTOR itextureCoordinate) noexcept : color(irgba) { XMStoreFloat3(&this->position, iposition); @@ -387,27 +370,25 @@ namespace DirectX XMStoreFloat2(&this->textureCoordinate, itextureCoordinate); } - VertexPositionNormalTangentColorTexture( - XMFLOAT3 const& iposition, - XMFLOAT3 const& inormal, - XMFLOAT4 const& itangent, - XMFLOAT4 const& icolor, - XMFLOAT2 const& itextureCoordinate) noexcept + VertexPositionNormalTangentColorTexture(XMFLOAT3 const& iposition, + XMFLOAT3 const& inormal, + XMFLOAT4 const& itangent, + XMFLOAT4 const& icolor, + XMFLOAT2 const& itextureCoordinate) noexcept : position(iposition), - normal(inormal), - tangent(itangent), - color{}, - textureCoordinate(itextureCoordinate) + normal(inormal), + tangent(itangent), + color{}, + textureCoordinate(itextureCoordinate) { SetColor(icolor); } - VertexPositionNormalTangentColorTexture( - FXMVECTOR iposition, - FXMVECTOR inormal, - FXMVECTOR itangent, - CXMVECTOR icolor, - CXMVECTOR itextureCoordinate) noexcept + VertexPositionNormalTangentColorTexture(FXMVECTOR iposition, + FXMVECTOR inormal, + FXMVECTOR itangent, + CXMVECTOR icolor, + CXMVECTOR itextureCoordinate) noexcept : color{} { XMStoreFloat3(&this->position, iposition); @@ -421,85 +402,80 @@ namespace DirectX void __cdecl SetColor(XMFLOAT4 const& icolor) noexcept { SetColor(XMLoadFloat4(&icolor)); } void XM_CALLCONV SetColor(FXMVECTOR icolor) noexcept; - static constexpr unsigned int InputElementCount = 5; + static constexpr unsigned int InputElementCount = 5; static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - // Vertex struct for Visual Studio Shader Designer (DGSL) holding position, normal, // tangent, color (RGBA), texture mapping information, and skinning weights struct DIRECTX_TOOLKIT_API VertexPositionNormalTangentColorTextureSkinning : public VertexPositionNormalTangentColorTexture { VertexPositionNormalTangentColorTextureSkinning() = default; - VertexPositionNormalTangentColorTextureSkinning(const VertexPositionNormalTangentColorTextureSkinning&) = default; + VertexPositionNormalTangentColorTextureSkinning(const VertexPositionNormalTangentColorTextureSkinning&) = default; VertexPositionNormalTangentColorTextureSkinning& operator=(const VertexPositionNormalTangentColorTextureSkinning&) = default; - VertexPositionNormalTangentColorTextureSkinning(VertexPositionNormalTangentColorTextureSkinning&&) = default; + VertexPositionNormalTangentColorTextureSkinning(VertexPositionNormalTangentColorTextureSkinning&&) = default; VertexPositionNormalTangentColorTextureSkinning& operator=(VertexPositionNormalTangentColorTextureSkinning&&) = default; uint32_t indices; uint32_t weights; - VertexPositionNormalTangentColorTextureSkinning( - XMFLOAT3 const& iposition, - XMFLOAT3 const& inormal, - XMFLOAT4 const& itangent, - uint32_t irgba, - XMFLOAT2 const& itextureCoordinate, - XMUINT4 const& iindices, - XMFLOAT4 const& iweights) noexcept + VertexPositionNormalTangentColorTextureSkinning(XMFLOAT3 const& iposition, + XMFLOAT3 const& inormal, + XMFLOAT4 const& itangent, + uint32_t irgba, + XMFLOAT2 const& itextureCoordinate, + XMUINT4 const& iindices, + XMFLOAT4 const& iweights) noexcept : VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, irgba, itextureCoordinate), - indices{}, - weights{} + indices{}, + weights{} { SetBlendIndices(iindices); SetBlendWeights(iweights); } - VertexPositionNormalTangentColorTextureSkinning( - FXMVECTOR iposition, - FXMVECTOR inormal, - FXMVECTOR itangent, - uint32_t irgba, - CXMVECTOR itextureCoordinate, - XMUINT4 const& iindices, - CXMVECTOR iweights) noexcept + VertexPositionNormalTangentColorTextureSkinning(FXMVECTOR iposition, + FXMVECTOR inormal, + FXMVECTOR itangent, + uint32_t irgba, + CXMVECTOR itextureCoordinate, + XMUINT4 const& iindices, + CXMVECTOR iweights) noexcept : VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, irgba, itextureCoordinate), - indices{}, - weights{} + indices{}, + weights{} { SetBlendIndices(iindices); SetBlendWeights(iweights); } - VertexPositionNormalTangentColorTextureSkinning( - XMFLOAT3 const& iposition, - XMFLOAT3 const& inormal, - XMFLOAT4 const& itangent, - XMFLOAT4 const& icolor, - XMFLOAT2 const& itextureCoordinate, - XMUINT4 const& iindices, - XMFLOAT4 const& iweights) noexcept + VertexPositionNormalTangentColorTextureSkinning(XMFLOAT3 const& iposition, + XMFLOAT3 const& inormal, + XMFLOAT4 const& itangent, + XMFLOAT4 const& icolor, + XMFLOAT2 const& itextureCoordinate, + XMUINT4 const& iindices, + XMFLOAT4 const& iweights) noexcept : VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, icolor, itextureCoordinate), - indices{}, - weights{} + indices{}, + weights{} { SetBlendIndices(iindices); SetBlendWeights(iweights); } - VertexPositionNormalTangentColorTextureSkinning( - FXMVECTOR iposition, - FXMVECTOR inormal, - FXMVECTOR itangent, - CXMVECTOR icolor, - CXMVECTOR itextureCoordinate, - XMUINT4 const& iindices, - CXMVECTOR iweights) noexcept + VertexPositionNormalTangentColorTextureSkinning(FXMVECTOR iposition, + FXMVECTOR inormal, + FXMVECTOR itangent, + CXMVECTOR icolor, + CXMVECTOR itextureCoordinate, + XMUINT4 const& iindices, + CXMVECTOR iweights) noexcept : VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, icolor, itextureCoordinate), - indices{}, - weights{} + indices{}, + weights{} { SetBlendIndices(iindices); SetBlendWeights(iweights); @@ -510,11 +486,11 @@ namespace DirectX void __cdecl SetBlendWeights(XMFLOAT4 const& iweights) noexcept { SetBlendWeights(XMLoadFloat4(&iweights)); } void XM_CALLCONV SetBlendWeights(FXMVECTOR iweights) noexcept; - static constexpr unsigned int InputElementCount = 7; + static constexpr unsigned int InputElementCount = 7; static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount]; }; - } -} + } // namespace DX11 +} // namespace DirectX #if defined(DIRECTX_TOOLKIT_IMPORT) && defined(_MSC_VER) #pragma warning(pop) diff --git a/Inc/WICTextureLoader.h b/Inc/WICTextureLoader.h index 575c6b38..60fd12cc 100644 --- a/Inc/WICTextureLoader.h +++ b/Inc/WICTextureLoader.h @@ -33,19 +33,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 @@ -54,208 +54,228 @@ #endif #endif - namespace DirectX { inline namespace DX11 { 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_FIT_POW2 = 0x20, - WIC_LOADER_MAKE_SQUARE = 0x40, + WIC_LOADER_FIT_POW2 = 0x20, + WIC_LOADER_MAKE_SQUARE = 0x40, WIC_LOADER_FORCE_RGBA32 = 0x80, }; } // Standard version DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromMemory( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - _In_ size_t wicDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0) noexcept; + HRESULT __cdecl CreateWICTextureFromMemory(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromFile( - _In_ ID3D11Device* d3dDevice, - _In_z_ const wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0) noexcept; + HRESULT __cdecl CreateWICTextureFromFile(_In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0) noexcept; - // Standard version with optional auto-gen mipmap support + // Standard version with optional auto-gen mipmap support DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromMemory( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - _In_ size_t wicDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0) noexcept; + HRESULT __cdecl CreateWICTextureFromMemory( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromFile( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0) noexcept; + HRESULT __cdecl CreateWICTextureFromFile( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0) noexcept; - // Extended version + // Extended version DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromMemoryEx( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - _In_ size_t wicDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; + HRESULT __cdecl CreateWICTextureFromMemoryEx(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromFileEx( - _In_ ID3D11Device* d3dDevice, - _In_z_ const wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; + HRESULT __cdecl CreateWICTextureFromFileEx(_In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; - // Extended version with optional auto-gen mipmap support + // Extended version with optional auto-gen mipmap support DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromMemoryEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(wicDataSize) const uint8_t* wicData, - _In_ size_t wicDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; + HRESULT __cdecl CreateWICTextureFromMemoryEx( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateWICTextureFromFileEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; + HRESULT __cdecl CreateWICTextureFromFileEx( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept; #ifdef __cpp_lib_byte DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateWICTextureFromMemory( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - _In_ size_t wicDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0) noexcept + inline HRESULT __cdecl CreateWICTextureFromMemory(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + _In_ size_t wicDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0) noexcept { return CreateWICTextureFromMemory(d3dDevice, reinterpret_cast(wicData), wicDataSize, texture, textureView, maxsize); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateWICTextureFromMemory( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - _In_ size_t wicDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0) noexcept + inline HRESULT __cdecl CreateWICTextureFromMemory( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + _In_ size_t wicDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0) noexcept { - return CreateWICTextureFromMemory(d3dDevice, d3dContext, reinterpret_cast(wicData), wicDataSize, texture, textureView, maxsize); + return CreateWICTextureFromMemory(d3dDevice, + d3dContext, + reinterpret_cast(wicData), + wicDataSize, + texture, + textureView, + maxsize); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateWICTextureFromMemoryEx( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - _In_ size_t wicDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept + inline HRESULT __cdecl CreateWICTextureFromMemoryEx(_In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + _In_ size_t wicDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { - return CreateWICTextureFromMemoryEx(d3dDevice, reinterpret_cast(wicData), wicDataSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); + return CreateWICTextureFromMemoryEx(d3dDevice, + reinterpret_cast(wicData), + wicDataSize, + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView); } DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateWICTextureFromMemoryEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, - _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_reads_bytes_(wicDataSize) const std::byte* wicData, - _In_ size_t wicDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept + inline HRESULT __cdecl CreateWICTextureFromMemoryEx( +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, + _In_opt_ ID3D11DeviceContextX* d3dContext, +#else + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#endif + _In_reads_bytes_(wicDataSize) const std::byte* wicData, + _In_ size_t wicDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { - return CreateWICTextureFromMemoryEx(d3dDevice, d3dContext, reinterpret_cast(wicData), wicDataSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); + return CreateWICTextureFromMemoryEx(d3dDevice, + d3dContext, + reinterpret_cast(wicData), + wicDataSize, + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView); } #endif // __cpp_lib_byte @@ -272,4 +292,4 @@ namespace DirectX #ifdef __clang__ #pragma clang diagnostic pop #endif -} +} // namespace DirectX diff --git a/Inc/XboxDDSTextureLoader.h b/Inc/XboxDDSTextureLoader.h index cc25d71f..a3af6bad 100644 --- a/Inc/XboxDDSTextureLoader.h +++ b/Inc/XboxDDSTextureLoader.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 @@ -50,57 +50,60 @@ 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 - namespace Xbox { using DirectX::DDS_ALPHA_MODE; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D11DeviceX* d3dDevice, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _In_ bool forceSRGB = false) noexcept; + HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D11DeviceX* d3dDevice, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Outptr_ void** grfxMemory, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _In_ bool forceSRGB = false) noexcept; DIRECTX_TOOLKIT_API - HRESULT __cdecl CreateDDSTextureFromFile( - _In_ ID3D11DeviceX* d3dDevice, - _In_z_ const wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _In_ bool forceSRGB = false) noexcept; + HRESULT __cdecl CreateDDSTextureFromFile(_In_ ID3D11DeviceX* d3dDevice, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Outptr_ void** grfxMemory, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _In_ bool forceSRGB = false) noexcept; DIRECTX_TOOLKIT_API - void FreeDDSTextureMemory(_In_opt_ void* grfxMemory) noexcept; + void FreeDDSTextureMemory(_In_opt_ void* grfxMemory) noexcept; #ifdef __cpp_lib_byte DIRECTX_TOOLKIT_API - inline HRESULT __cdecl CreateDDSTextureFromMemory( - _In_ ID3D11DeviceX* d3dDevice, - _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, - _In_ bool forceSRGB = false) noexcept + inline HRESULT __cdecl CreateDDSTextureFromMemory(_In_ ID3D11DeviceX* d3dDevice, + _In_reads_bytes_(ddsDataSize) const std::byte* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Outptr_ void** grfxMemory, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _In_ bool forceSRGB = false) noexcept { - return CreateDDSTextureFromMemory(d3dDevice, reinterpret_cast(ddsData), ddsDataSize, texture, textureView, grfxMemory, alphaMode, forceSRGB); + return CreateDDSTextureFromMemory(d3dDevice, + reinterpret_cast(ddsData), + ddsDataSize, + texture, + textureView, + grfxMemory, + alphaMode, + forceSRGB); } #endif // __cpp_lib_byte -} +} // namespace Xbox 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 d19b8045..aaf90091 100644 --- a/Src/AlphaTestEffect.cpp +++ b/Src/AlphaTestEffect.cpp @@ -31,11 +31,11 @@ namespace { 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; }; -} +} // namespace // Internal AlphaTestEffect implementation class. class AlphaTestEffect::Impl : public EffectBase @@ -43,14 +43,14 @@ class AlphaTestEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; D3D11_COMPARISON_FUNC alphaFunction; - int referenceAlpha; + int referenceAlpha; bool vertexColorEnabled; @@ -61,7 +61,6 @@ class AlphaTestEffect::Impl : public EffectBase void Apply(_In_ ID3D11DeviceContext* deviceContext); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -87,78 +86,77 @@ namespace #include "AlphaTestEffect_PSAlphaTestEqNe.inc" #include "AlphaTestEffect_PSAlphaTestEqNeNoFog.inc" #endif -} - +} // namespace template<> -const ShaderBytecode EffectBase::VertexShaderBytecode[] = -{ - { AlphaTestEffect_VSAlphaTest, sizeof(AlphaTestEffect_VSAlphaTest) }, - { AlphaTestEffect_VSAlphaTestNoFog, sizeof(AlphaTestEffect_VSAlphaTestNoFog) }, - { AlphaTestEffect_VSAlphaTestVc, sizeof(AlphaTestEffect_VSAlphaTestVc) }, +const ShaderBytecode 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 ShaderBytecode EffectBase::PixelShaderBytecode[] = -{ - { AlphaTestEffect_PSAlphaTestLtGt, sizeof(AlphaTestEffect_PSAlphaTestLtGt) }, +const ShaderBytecode 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_ ID3D11Device* device) : EffectBase(device), - alphaFunction(D3D11_COMPARISON_GREATER), - referenceAlpha(0), - vertexColorEnabled(false) + alphaFunction(D3D11_COMPARISON_GREATER), + referenceAlpha(0), + vertexColorEnabled(false) { - 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"); } - int AlphaTestEffect::Impl::GetCurrentShaderPermutation() const noexcept { int permutation = 0; @@ -176,8 +174,7 @@ int AlphaTestEffect::Impl::GetCurrentShaderPermutation() const noexcept } // Which alpha compare mode? - if (alphaFunction == D3D11_COMPARISON_EQUAL || - alphaFunction == D3D11_COMPARISON_NOT_EQUAL) + if (alphaFunction == D3D11_COMPARISON_EQUAL || alphaFunction == D3D11_COMPARISON_NOT_EQUAL) { permutation += 4; } @@ -185,7 +182,6 @@ int AlphaTestEffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void AlphaTestEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -208,66 +204,65 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) 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 (alphaFunction) { case D3D11_COMPARISON_LESS: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference - threshold; + compareTo = reference - threshold; resultSelector = selectIfTrue; break; case D3D11_COMPARISON_LESS_EQUAL: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference + threshold; + compareTo = reference + threshold; resultSelector = selectIfTrue; break; case D3D11_COMPARISON_GREATER_EQUAL: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference - threshold; + compareTo = reference - threshold; resultSelector = selectIfFalse; break; case D3D11_COMPARISON_GREATER: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = reference + threshold; + compareTo = reference + threshold; resultSelector = selectIfFalse; break; case D3D11_COMPARISON_EQUAL: // Shader will evaluate: clip((abs(a - x) < y) ? z : w) - compareTo = reference; + compareTo = reference; resultSelector = selectIfTrue; break; case D3D11_COMPARISON_NOT_EQUAL: // Shader will evaluate: clip((abs(a - x) < y) ? z : w) - compareTo = reference; + compareTo = reference; resultSelector = selectIfFalse; break; case D3D11_COMPARISON_NEVER: // Shader will evaluate: clip((a < x) ? z : w) - compareTo = 0; + compareTo = 0; resultSelector = selectNever; break; case D3D11_COMPARISON_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. @@ -284,17 +279,14 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - // Public constructor. AlphaTestEffect::AlphaTestEffect(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext) @@ -302,13 +294,11 @@ void AlphaTestEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void AlphaTestEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV AlphaTestEffect::SetWorld(FXMMATRIX value) { @@ -317,7 +307,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; @@ -325,7 +314,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; @@ -333,17 +321,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) { @@ -352,7 +339,6 @@ void XM_CALLCONV AlphaTestEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void AlphaTestEffect::SetAlpha(float value) { pImpl->color.alpha = value; @@ -360,16 +346,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::SetFogEnabled(bool value) { @@ -378,7 +362,6 @@ void AlphaTestEffect::SetFogEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::FogEnable; } - void AlphaTestEffect::SetFogStart(float value) { pImpl->fog.start = value; @@ -386,7 +369,6 @@ void AlphaTestEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void AlphaTestEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -394,7 +376,6 @@ void AlphaTestEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV AlphaTestEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -402,21 +383,18 @@ void XM_CALLCONV AlphaTestEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Vertex color setting. void AlphaTestEffect::SetVertexColorEnabled(bool value) { pImpl->vertexColorEnabled = value; } - // Texture settings. void AlphaTestEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - void AlphaTestEffect::SetAlphaFunction(D3D11_COMPARISON_FUNC value) { pImpl->alphaFunction = value; @@ -424,7 +402,6 @@ void AlphaTestEffect::SetAlphaFunction(D3D11_COMPARISON_FUNC value) pImpl->dirtyFlags |= EffectDirtyFlags::AlphaTest; } - void AlphaTestEffect::SetReferenceAlpha(int value) { pImpl->referenceAlpha = value; diff --git a/Src/BasicEffect.cpp b/Src/BasicEffect.cpp index 2bb71447..546f8bb2 100644 --- a/Src/BasicEffect.cpp +++ b/Src/BasicEffect.cpp @@ -42,11 +42,11 @@ namespace { using ConstantBufferType = BasicEffectConstants; - static constexpr int VertexShaderCount = 32; - static constexpr int PixelShaderCount = 10; + static constexpr int VertexShaderCount = 32; + static constexpr int PixelShaderCount = 10; static constexpr int ShaderPermutationCount = 56; }; -} +} // namespace // Internal BasicEffect implementation class. class BasicEffect::Impl : public EffectBase @@ -54,10 +54,10 @@ class BasicEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; bool lightingEnabled; @@ -73,7 +73,6 @@ class BasicEffect::Impl : public EffectBase void Apply(_In_ ID3D11DeviceContext* deviceContext); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -183,204 +182,196 @@ namespace #include "BasicEffect_PSBasicPixelLighting.inc" #include "BasicEffect_PSBasicPixelLightingTx.inc" #endif -} - +} // namespace template<> -const ShaderBytecode 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_VSBasicOneLight, sizeof(BasicEffect_VSBasicOneLight) }, - { BasicEffect_VSBasicOneLightVc, sizeof(BasicEffect_VSBasicOneLightVc) }, - { BasicEffect_VSBasicOneLightTx, sizeof(BasicEffect_VSBasicOneLightTx) }, - { BasicEffect_VSBasicOneLightTxVc, sizeof(BasicEffect_VSBasicOneLightTxVc) }, - - { 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 ShaderBytecode 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_VSBasicOneLight, sizeof(BasicEffect_VSBasicOneLight) }, + { BasicEffect_VSBasicOneLightVc, sizeof(BasicEffect_VSBasicOneLightVc) }, + { BasicEffect_VSBasicOneLightTx, sizeof(BasicEffect_VSBasicOneLightTx) }, + { BasicEffect_VSBasicOneLightTxVc, sizeof(BasicEffect_VSBasicOneLightTxVc) }, + + { 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_VSBasicOneLightBn, sizeof(BasicEffect_VSBasicOneLightBn) }, - { BasicEffect_VSBasicOneLightVcBn, sizeof(BasicEffect_VSBasicOneLightVcBn) }, - { BasicEffect_VSBasicOneLightTxBn, sizeof(BasicEffect_VSBasicOneLightTxBn) }, - { BasicEffect_VSBasicOneLightTxVcBn, sizeof(BasicEffect_VSBasicOneLightTxVcBn) }, + { BasicEffect_VSBasicOneLightBn, sizeof(BasicEffect_VSBasicOneLightBn) }, + { BasicEffect_VSBasicOneLightVcBn, sizeof(BasicEffect_VSBasicOneLightVcBn) }, + { BasicEffect_VSBasicOneLightTxBn, sizeof(BasicEffect_VSBasicOneLightTxBn) }, + { BasicEffect_VSBasicOneLightTxVcBn, sizeof(BasicEffect_VSBasicOneLightTxVcBn) }, - { 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, // one light - 12, // one light, no fog - 13, // one light + vertex color - 13, // one light + vertex color, no fog - 14, // one light + texture - 14, // one light + texture, no fog - 15, // one light + texture + vertex color - 15, // one light + texture + vertex color, no fog - - 16, // pixel lighting - 16, // pixel lighting, no fog - 17, // pixel lighting + vertex color - 17, // pixel lighting + vertex color, no fog - 18, // pixel lighting + texture - 18, // pixel lighting + texture, no fog - 19, // pixel lighting + texture + vertex color - 19, // pixel lighting + texture + vertex color, no fog - - 20, // vertex lighting (biased vertex normals) - 20, // vertex lighting (biased vertex normals), no fog - 21, // vertex lighting (biased vertex normals) + vertex color - 21, // vertex lighting (biased vertex normals) + vertex color, no fog - 22, // vertex lighting (biased vertex normals) + texture - 22, // vertex lighting (biased vertex normals) + texture, no fog - 23, // vertex lighting (biased vertex normals) + texture + vertex color - 23, // vertex lighting (biased vertex normals) + texture + vertex color, no fog - - 24, // one light (biased vertex normals) - 24, // one light (biased vertex normals), no fog - 25, // one light (biased vertex normals) + vertex color - 25, // one light (biased vertex normals) + vertex color, no fog - 26, // one light (biased vertex normals) + texture - 26, // one light (biased vertex normals) + texture, no fog - 27, // one light (biased vertex normals) + texture + vertex color - 27, // one light (biased vertex normals) + texture + vertex color, no fog - - 28, // pixel lighting (biased vertex normals) - 28, // pixel lighting (biased vertex normals), no fog - 29, // pixel lighting (biased vertex normals) + vertex color - 29, // pixel lighting (biased vertex normals) + vertex color, no fog - 30, // pixel lighting (biased vertex normals) + texture - 30, // pixel lighting (biased vertex normals) + texture, no fog - 31, // pixel lighting (biased vertex normals) + texture + vertex color - 31, // 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, // one light + 12, // one light, no fog + 13, // one light + vertex color + 13, // one light + vertex color, no fog + 14, // one light + texture + 14, // one light + texture, no fog + 15, // one light + texture + vertex color + 15, // one light + texture + vertex color, no fog + + 16, // pixel lighting + 16, // pixel lighting, no fog + 17, // pixel lighting + vertex color + 17, // pixel lighting + vertex color, no fog + 18, // pixel lighting + texture + 18, // pixel lighting + texture, no fog + 19, // pixel lighting + texture + vertex color + 19, // pixel lighting + texture + vertex color, no fog + + 20, // vertex lighting (biased vertex normals) + 20, // vertex lighting (biased vertex normals), no fog + 21, // vertex lighting (biased vertex normals) + vertex color + 21, // vertex lighting (biased vertex normals) + vertex color, no fog + 22, // vertex lighting (biased vertex normals) + texture + 22, // vertex lighting (biased vertex normals) + texture, no fog + 23, // vertex lighting (biased vertex normals) + texture + vertex color + 23, // vertex lighting (biased vertex normals) + texture + vertex color, no fog + + 24, // one light (biased vertex normals) + 24, // one light (biased vertex normals), no fog + 25, // one light (biased vertex normals) + vertex color + 25, // one light (biased vertex normals) + vertex color, no fog + 26, // one light (biased vertex normals) + texture + 26, // one light (biased vertex normals) + texture, no fog + 27, // one light (biased vertex normals) + texture + vertex color + 27, // one light (biased vertex normals) + texture + vertex color, no fog + + 28, // pixel lighting (biased vertex normals) + 28, // pixel lighting (biased vertex normals), no fog + 29, // pixel lighting (biased vertex normals) + vertex color + 29, // pixel lighting (biased vertex normals) + vertex color, no fog + 30, // pixel lighting (biased vertex normals) + texture + 30, // pixel lighting (biased vertex normals) + texture, no fog + 31, // pixel lighting (biased vertex normals) + texture + vertex color + 31, // pixel lighting (biased vertex normals) + texture + vertex color, no fog }; - template<> -const ShaderBytecode 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 ShaderBytecode 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 - - 4, // one light - 5, // one light, no fog - 4, // one light + vertex color - 5, // one light + vertex color, no fog - 6, // one light + texture - 7, // one light + texture, no fog - 6, // one light + texture + vertex color - 7, // one light + 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 - - 4, // one light (biased vertex normals) - 5, // one light (biased vertex normals), no fog - 4, // one light (biased vertex normals) + vertex color - 5, // one light (biased vertex normals) + vertex color, no fog - 6, // one light (biased vertex normals) + texture - 7, // one light (biased vertex normals) + texture, no fog - 6, // one light (biased vertex normals) + texture + vertex color - 7, // one light (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 + + 4, // one light + 5, // one light, no fog + 4, // one light + vertex color + 5, // one light + vertex color, no fog + 6, // one light + texture + 7, // one light + texture, no fog + 6, // one light + texture + vertex color + 7, // one light + 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 + + 4, // one light (biased vertex normals) + 5, // one light (biased vertex normals), no fog + 4, // one light (biased vertex normals) + vertex color + 5, // one light (biased vertex normals) + vertex color, no fog + 6, // one light (biased vertex normals) + texture + 7, // one light (biased vertex normals) + texture, no fog + 6, // one light (biased vertex normals) + texture + vertex color + 7, // one light (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 @@ -388,25 +379,32 @@ const int EffectBase::PixelShaderIndices[] = template<> SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - // Constructor. BasicEffect::Impl::Impl(_In_ ID3D11Device* device) : EffectBase(device), - lightingEnabled(false), - preferPerPixelLighting(false), - vertexColorEnabled(false), - textureEnabled(false), - biasedVertexNormals(false) -{ - 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"); - - lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); + lightingEnabled(false), + preferPerPixelLighting(false), + vertexColorEnabled(false), + textureEnabled(false), + biasedVertexNormals(false) +{ + 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"); + + lights.InitializeConstants(constants.specularColorAndPower, + constants.lightDirection, + constants.lightDiffuseColor, + constants.lightSpecularColor); } - int BasicEffect::Impl::GetCurrentShaderPermutation() const noexcept { int permutation = 0; @@ -457,7 +455,6 @@ int BasicEffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void BasicEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -468,7 +465,14 @@ void BasicEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) 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); // Set the texture. if (textureEnabled) @@ -480,17 +484,14 @@ void BasicEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - // Public constructor. BasicEffect::BasicEffect(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext) @@ -498,13 +499,11 @@ void BasicEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void BasicEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV BasicEffect::SetWorld(FXMMATRIX value) { @@ -513,7 +512,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; @@ -521,7 +519,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; @@ -529,17 +526,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) { @@ -548,7 +544,6 @@ void XM_CALLCONV BasicEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV BasicEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -556,7 +551,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). @@ -565,7 +559,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). @@ -574,7 +567,6 @@ void BasicEffect::SetSpecularPower(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void BasicEffect::DisableSpecular() { // Set specular color to black, power to 1 @@ -585,7 +577,6 @@ void BasicEffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void BasicEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -593,16 +584,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 BasicEffect::SetLightingEnabled(bool value) { @@ -611,13 +600,11 @@ void BasicEffect::SetLightingEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void BasicEffect::SetPerPixelLighting(bool value) { pImpl->preferPerPixelLighting = value; } - void XM_CALLCONV BasicEffect::SetAmbientLightColor(FXMVECTOR value) { pImpl->lights.ambientLightColor = value; @@ -625,13 +612,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); @@ -641,25 +627,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::SetFogEnabled(bool value) { @@ -668,7 +650,6 @@ void BasicEffect::SetFogEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::FogEnable; } - void BasicEffect::SetFogStart(float value) { pImpl->fog.start = value; @@ -676,7 +657,6 @@ void BasicEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void BasicEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -684,7 +664,6 @@ void BasicEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV BasicEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -692,27 +671,23 @@ void XM_CALLCONV BasicEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Vertex color setting. void BasicEffect::SetVertexColorEnabled(bool value) { pImpl->vertexColorEnabled = value; } - // Texture settings. void BasicEffect::SetTextureEnabled(bool value) { pImpl->textureEnabled = value; } - void BasicEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - // Normal compression settings. void BasicEffect::SetBiasedVertexNormals(bool value) { diff --git a/Src/BasicPostProcess.cpp b/Src/BasicPostProcess.cpp index 04782d6c..629cf17b 100644 --- a/Src/BasicPostProcess.cpp +++ b/Src/BasicPostProcess.cpp @@ -26,7 +26,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 @@ -42,7 +42,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. @@ -75,19 +75,18 @@ namespace struct ShaderBytecode { void const* code; - size_t length; + size_t length; }; - const ShaderBytecode 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 ShaderBytecode 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"); @@ -98,10 +97,10 @@ namespace public: DeviceResources(_In_ ID3D11Device* device) : stateObjects(device), - mDevice(device), - mVertexShader{}, - mPixelShaders{}, - mMutex{} + mDevice(device), + mVertexShader{}, + mPixelShaders{}, + mMutex{} { if (!device) { @@ -114,16 +113,18 @@ namespace } } - DeviceResources(const DeviceResources&) = delete; + DeviceResources(const DeviceResources&) = delete; DeviceResources& operator=(const DeviceResources&) = delete; - DeviceResources(DeviceResources&&) = delete; + DeviceResources(DeviceResources&&) = delete; DeviceResources& operator=(DeviceResources&&) = delete; // Gets or lazily creates the vertex shader. ID3D11VertexShader* GetVertexShader() { - return DemandCreate(mVertexShader, mMutex, [&](ID3D11VertexShader** pResult) -> HRESULT + return DemandCreate(mVertexShader, + mMutex, + [&](ID3D11VertexShader** pResult) -> HRESULT { HRESULT hr = mDevice->CreateVertexShader(PostProcess_VSQuad, sizeof(PostProcess_VSQuad), nullptr, pResult); @@ -140,9 +141,12 @@ namespace assert(shaderIndex < BasicPostProcess::Effect_Max); _Analysis_assume_(shaderIndex < BasicPostProcess::Effect_Max); - return DemandCreate(mPixelShaders[shaderIndex], mMutex, [&](ID3D11PixelShader** pResult) -> HRESULT + return DemandCreate(mPixelShaders[shaderIndex], + mMutex, + [&](ID3D11PixelShader** pResult) -> HRESULT { - HRESULT hr = mDevice->CreatePixelShader(pixelShaders[shaderIndex].code, pixelShaders[shaderIndex].length, nullptr, pResult); + HRESULT hr + = mDevice->CreatePixelShader(pixelShaders[shaderIndex].code, pixelShaders[shaderIndex].length, nullptr, pResult); if (SUCCEEDED(hr)) SetDebugObjectName(*pResult, "BasicPostProcess"); @@ -151,92 +155,90 @@ namespace }); } - CommonStates stateObjects; + CommonStates stateObjects; protected: - ComPtr mDevice; - ComPtr mVertexShader; - ComPtr mPixelShaders[BasicPostProcess::Effect_Max]; - std::mutex mMutex; + ComPtr mDevice; + ComPtr mVertexShader; + ComPtr mPixelShaders[BasicPostProcess::Effect_Max]; + std::mutex mMutex; }; -} +} // namespace #pragma endregion - class BasicPostProcess::Impl : public AlignedNew { public: explicit Impl(_In_ ID3D11Device* 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 Process(_In_ ID3D11DeviceContext* deviceContext, const std::function& setCustomState); - void SetConstants(bool value = true) noexcept { mUseConstants = value; mDirtyFlags = INT_MAX; } + void SetConstants(bool value = true) noexcept + { + mUseConstants = value; + mDirtyFlags = INT_MAX; + } void SetDirtyFlag() noexcept { mDirtyFlags = INT_MAX; } // Fields. - PostProcessConstants constants; - BasicPostProcess::Effect fx; - ComPtr texture; - unsigned texWidth; - unsigned texHeight; - float guassianMultiplier; - float bloomSize; - float bloomBrightness; - float bloomThreshold; - bool bloomHorizontal; + PostProcessConstants constants; + BasicPostProcess::Effect fx; + ComPtr 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); - ConstantBuffer mConstantBuffer; + ConstantBuffer mConstantBuffer; // Per-device resources. - std::shared_ptr mDeviceResources; + std::shared_ptr mDeviceResources; static SharedResourcePool deviceResourcesPool; }; - // Global pool of per-device BasicPostProcess resources. SharedResourcePool BasicPostProcess::Impl::deviceResourcesPool; - // Constructor. BasicPostProcess::Impl::Impl(_In_ ID3D11Device* device) : constants{}, - fx(BasicPostProcess::Copy), - texWidth(0), - texHeight(0), - guassianMultiplier(1.f), - bloomSize(1.f), - bloomBrightness(1.f), - bloomThreshold(0.25f), - bloomHorizontal(true), - mUseConstants(false), - mDirtyFlags(INT_MAX), - mConstantBuffer(device), - mDeviceResources(deviceResourcesPool.DemandCreate(device)) + fx(BasicPostProcess::Copy), + texWidth(0), + texHeight(0), + guassianMultiplier(1.f), + bloomSize(1.f), + bloomBrightness(1.f), + bloomThreshold(0.25f), + bloomHorizontal(true), + mUseConstants(false), + mDirtyFlags(INT_MAX), + mConstantBuffer(device), + mDeviceResources(deviceResourcesPool.DemandCreate(device)) { SetDebugObjectName(mConstantBuffer.GetBuffer(), "BasicPostProcess"); } - // Sets our state onto the D3D device. -void BasicPostProcess::Impl::Process( - _In_ ID3D11DeviceContext* deviceContext, - const std::function& setCustomState) +void BasicPostProcess::Impl::Process(_In_ ID3D11DeviceContext* deviceContext, const std::function& setCustomState) { // Set the texture. ID3D11ShaderResourceView* textures[1] = { texture.Get() }; @@ -252,7 +254,7 @@ void BasicPostProcess::Impl::Process( // Set shaders. auto vertexShader = mDeviceResources->GetVertexShader(); - auto pixelShader = mDeviceResources->GetPixelShader(fx); + auto pixelShader = mDeviceResources->GetPixelShader(fx); deviceContext->VSSetShader(vertexShader, nullptr, 0); deviceContext->PSSetShader(pixelShader, nullptr, 0); @@ -267,33 +269,22 @@ void BasicPostProcess::Impl::Process( 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; } } - #if defined(_XBOX_ONE) && defined(_TITLE) - void *grfxMemory; +#if defined(_XBOX_ONE) && defined(_TITLE) + void* grfxMemory; mConstantBuffer.SetData(deviceContext, constants, &grfxMemory); ComPtr deviceContextX; @@ -302,7 +293,7 @@ void BasicPostProcess::Impl::Process( auto buffer = mConstantBuffer.GetBuffer(); deviceContextX->PSSetPlacementConstantBuffer(0, buffer, grfxMemory); - #else +#else if (mDirtyFlags & Dirty_ConstantBuffer) { mDirtyFlags &= ~Dirty_ConstantBuffer; @@ -313,7 +304,7 @@ void BasicPostProcess::Impl::Process( auto buffer = mConstantBuffer.GetBuffer(); deviceContext->PSSetConstantBuffers(0, 1, &buffer); - #endif +#endif } if (setCustomState) @@ -328,7 +319,6 @@ void BasicPostProcess::Impl::Process( deviceContext->Draw(3, 0); } - void BasicPostProcess::Impl::DownScale2x2() { mUseConstants = true; @@ -355,7 +345,6 @@ void BasicPostProcess::Impl::DownScale2x2() } } - void BasicPostProcess::Impl::DownScale4x4() { mUseConstants = true; @@ -380,10 +369,8 @@ void BasicPostProcess::Impl::DownScale4x4() ++ptr; } } - } - void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) { mUseConstants = true; @@ -396,10 +383,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) @@ -417,7 +404,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]); @@ -431,7 +418,7 @@ 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) { weights[i] = XMVectorDivide(weights[i], vtw); @@ -439,8 +426,7 @@ void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) } } - -void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightness) +void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightness) { mUseConstants = true; @@ -465,14 +451,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); } @@ -485,27 +471,21 @@ void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightnes } } - // Public constructor. BasicPostProcess::BasicPostProcess(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext, - _In_ std::function setCustomState) +void BasicPostProcess::Process(_In_ ID3D11DeviceContext* deviceContext, _In_ std::function setCustomState) { pImpl->Process(deviceContext, setCustomState); } - // Shader control. void BasicPostProcess::SetEffect(Effect fx) { @@ -523,13 +503,10 @@ void BasicPostProcess::SetEffect(Effect fx) pImpl->SetConstants(false); break; - default: - pImpl->SetConstants(true); - break; + default: pImpl->SetConstants(true); break; } } - // Properties void BasicPostProcess::SetSourceTexture(_In_opt_ ID3D11ShaderResourceView* value) { @@ -545,35 +522,32 @@ void BasicPostProcess::SetSourceTexture(_In_opt_ ID3D11ShaderResourceView* value switch (resType) { - case D3D11_RESOURCE_DIMENSION_TEXTURE1D: - { - ComPtr tex; - ThrowIfFailed(res.As(&tex)); - - D3D11_TEXTURE1D_DESC desc = {}; - tex->GetDesc(&desc); - pImpl->texWidth = desc.Width; - pImpl->texHeight = 1; - break; - } + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: { + ComPtr tex; + ThrowIfFailed(res.As(&tex)); + + D3D11_TEXTURE1D_DESC desc = {}; + tex->GetDesc(&desc); + pImpl->texWidth = desc.Width; + pImpl->texHeight = 1; + break; + } - case D3D11_RESOURCE_DIMENSION_TEXTURE2D: - { - ComPtr tex; - ThrowIfFailed(res.As(&tex)); - - D3D11_TEXTURE2D_DESC desc = {}; - tex->GetDesc(&desc); - pImpl->texWidth = desc.Width; - pImpl->texHeight = desc.Height; - break; - } + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: { + ComPtr tex; + ThrowIfFailed(res.As(&tex)); + + D3D11_TEXTURE2D_DESC desc = {}; + tex->GetDesc(&desc); + pImpl->texWidth = desc.Width; + pImpl->texHeight = desc.Height; + break; + } case D3D11_RESOURCE_DIMENSION_UNKNOWN: case D3D11_RESOURCE_DIMENSION_BUFFER: case D3D11_RESOURCE_DIMENSION_TEXTURE3D: - default: - throw std::invalid_argument("Unsupported texture type"); + default: throw std::invalid_argument("Unsupported texture type"); } } else @@ -582,24 +556,21 @@ void BasicPostProcess::SetSourceTexture(_In_opt_ ID3D11ShaderResourceView* value } } - 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 1772791d..d70543fe 100644 --- a/Src/BufferHelpers.cpp +++ b/Src/BufferHelpers.cpp @@ -11,19 +11,16 @@ #include "BufferHelpers.h" #include "PlatformHelpers.h" - using namespace DirectX; using Microsoft::WRL::ComPtr; //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateStaticBuffer( - ID3D11Device* device, - const void* ptr, - size_t count, - size_t stride, - unsigned int bindFlags, - ID3D11Buffer** pBuffer) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateStaticBuffer(ID3D11Device* device, + const void* ptr, + size_t count, + size_t stride, + unsigned int bindFlags, + ID3D11Buffer** pBuffer) noexcept { if (!pBuffer) return E_INVALIDARG; @@ -45,26 +42,23 @@ HRESULT DirectX::CreateStaticBuffer( } D3D11_BUFFER_DESC bufferDesc = {}; - bufferDesc.ByteWidth = static_cast(sizeInbytes); - bufferDesc.BindFlags = bindFlags; - bufferDesc.Usage = D3D11_USAGE_DEFAULT; + bufferDesc.ByteWidth = static_cast(sizeInbytes); + bufferDesc.BindFlags = bindFlags; + bufferDesc.Usage = D3D11_USAGE_DEFAULT; D3D11_SUBRESOURCE_DATA initData = { ptr, 0, 0 }; return device->CreateBuffer(&bufferDesc, &initData, pBuffer); } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateTextureFromMemory( - ID3D11Device* device, - size_t width, - DXGI_FORMAT format, - const D3D11_SUBRESOURCE_DATA& initData, - ID3D11Texture1D** texture, - ID3D11ShaderResourceView** textureView, - unsigned int bindFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateTextureFromMemory(ID3D11Device* device, + size_t width, + DXGI_FORMAT format, + const D3D11_SUBRESOURCE_DATA& initData, + ID3D11Texture1D** texture, + ID3D11ShaderResourceView** textureView, + unsigned int bindFlags) noexcept { if (texture) { @@ -90,14 +84,14 @@ HRESULT DirectX::CreateTextureFromMemory( } D3D11_TEXTURE1D_DESC desc = {}; - desc.Width = static_cast(width); + desc.Width = static_cast(width); desc.MipLevels = desc.ArraySize = 1; - desc.Format = format; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = bindFlags; + desc.Format = format; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = bindFlags; ComPtr tex; - HRESULT hr = device->CreateTexture1D(&desc, &initData, tex.GetAddressOf()); + HRESULT hr = device->CreateTexture1D(&desc, &initData, tex.GetAddressOf()); if (SUCCEEDED(hr)) { if (textureView) @@ -116,16 +110,14 @@ HRESULT DirectX::CreateTextureFromMemory( return hr; } -_Use_decl_annotations_ -HRESULT DirectX::CreateTextureFromMemory( - ID3D11Device* device, - size_t width, - size_t height, - DXGI_FORMAT format, - const D3D11_SUBRESOURCE_DATA& initData, - ID3D11Texture2D** texture, - ID3D11ShaderResourceView** textureView, - unsigned int bindFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateTextureFromMemory(ID3D11Device* device, + size_t width, + size_t height, + DXGI_FORMAT format, + const D3D11_SUBRESOURCE_DATA& initData, + ID3D11Texture2D** texture, + ID3D11ShaderResourceView** textureView, + unsigned int bindFlags) noexcept { if (texture) { @@ -136,8 +128,7 @@ HRESULT DirectX::CreateTextureFromMemory( *textureView = nullptr; } - if (!device || !width || !height - || !initData.pSysMem || !initData.SysMemPitch) + if (!device || !width || !height || !initData.pSysMem || !initData.SysMemPitch) return E_INVALIDARG; if (!texture && !textureView) @@ -145,24 +136,23 @@ HRESULT DirectX::CreateTextureFromMemory( static_assert(D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION <= UINT32_MAX, "Exceeded integer limits"); - if ((width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) - || (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + if ((width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) || (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (2D: size %zu by %zu)\n", width, height); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } D3D11_TEXTURE2D_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); + desc.Width = static_cast(width); + desc.Height = static_cast(height); desc.MipLevels = desc.ArraySize = 1; - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = bindFlags; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = bindFlags; ComPtr tex; - HRESULT hr = device->CreateTexture2D(&desc, &initData, tex.GetAddressOf()); + HRESULT hr = device->CreateTexture2D(&desc, &initData, tex.GetAddressOf()); if (SUCCEEDED(hr)) { if (textureView) @@ -181,22 +171,20 @@ HRESULT DirectX::CreateTextureFromMemory( return hr; } - -_Use_decl_annotations_ -HRESULT DirectX::CreateTextureFromMemory( +_Use_decl_annotations_ HRESULT DirectX::CreateTextureFromMemory( #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* device, + _In_ ID3D11DeviceX* device, _In_ ID3D11DeviceContextX* d3dContext, #else - _In_ ID3D11Device* device, + _In_ ID3D11Device* device, _In_ ID3D11DeviceContext* d3dContext, #endif - size_t width, - size_t height, - DXGI_FORMAT format, + size_t width, + size_t height, + DXGI_FORMAT format, const D3D11_SUBRESOURCE_DATA& initData, - ID3D11Texture2D** texture, - ID3D11ShaderResourceView** textureView) noexcept + ID3D11Texture2D** texture, + ID3D11ShaderResourceView** textureView) noexcept { if (texture) { @@ -207,8 +195,7 @@ HRESULT DirectX::CreateTextureFromMemory( *textureView = nullptr; } - if (!device || !d3dContext || !width || !height - || !initData.pSysMem || !initData.SysMemPitch) + if (!device || !d3dContext || !width || !height || !initData.pSysMem || !initData.SysMemPitch) return E_INVALIDARG; if (!texture && !textureView) @@ -216,21 +203,20 @@ HRESULT DirectX::CreateTextureFromMemory( static_assert(D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION <= UINT32_MAX, "Exceeded integer limits"); - if ((width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) - || (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + if ((width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) || (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (2D: size %zu by %zu)\n", width, height); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } D3D11_TEXTURE2D_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.ArraySize = 1; - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.ArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; UINT fmtSupport = 0; if (SUCCEEDED(device->CheckFormatSupport(format, &fmtSupport)) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) @@ -245,7 +231,7 @@ HRESULT DirectX::CreateTextureFromMemory( } ComPtr tex; - HRESULT hr = device->CreateTexture2D(&desc, nullptr, tex.GetAddressOf()); + HRESULT hr = device->CreateTexture2D(&desc, nullptr, tex.GetAddressOf()); if (SUCCEEDED(hr)) { ComPtr srv; @@ -255,22 +241,25 @@ HRESULT DirectX::CreateTextureFromMemory( if (desc.MipLevels != 1) { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) ComPtr staging; desc.MipLevels = 1; - desc.Usage = D3D11_USAGE_STAGING; + desc.Usage = D3D11_USAGE_STAGING; desc.BindFlags = desc.MiscFlags = 0; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; - hr = device->CreateTexture2D(&desc, &initData, staging.GetAddressOf()); + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + hr = device->CreateTexture2D(&desc, &initData, staging.GetAddressOf()); if (FAILED(hr)) return hr; d3dContext->CopySubresourceRegion(tex.Get(), 0, 0, 0, 0, staging.Get(), 0, nullptr); UINT64 copyFence = d3dContext->InsertFence(0); - while (device->IsFencePending(copyFence)) { SwitchToThread(); } - #else + while (device->IsFencePending(copyFence)) + { + SwitchToThread(); + } +#else d3dContext->UpdateSubresource(tex.Get(), 0, nullptr, initData.pSysMem, initData.SysMemPitch, 0); - #endif +#endif d3dContext->GenerateMips(srv.Get()); } @@ -287,15 +276,15 @@ HRESULT DirectX::CreateTextureFromMemory( return hr; } -_Use_decl_annotations_ -HRESULT DirectX::CreateTextureFromMemory( - ID3D11Device* device, - size_t width, size_t height, size_t depth, - DXGI_FORMAT format, - const D3D11_SUBRESOURCE_DATA& initData, - ID3D11Texture3D** texture, - ID3D11ShaderResourceView** textureView, - unsigned int bindFlags) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateTextureFromMemory(ID3D11Device* device, + size_t width, + size_t height, + size_t depth, + DXGI_FORMAT format, + const D3D11_SUBRESOURCE_DATA& initData, + ID3D11Texture3D** texture, + ID3D11ShaderResourceView** textureView, + unsigned int bindFlags) noexcept { if (texture) { @@ -306,8 +295,7 @@ HRESULT DirectX::CreateTextureFromMemory( *textureView = nullptr; } - if (!device || !width || !height || !depth - || !initData.pSysMem || !initData.SysMemPitch || !initData.SysMemSlicePitch) + if (!device || !width || !height || !depth || !initData.pSysMem || !initData.SysMemPitch || !initData.SysMemSlicePitch) return E_INVALIDARG; if (!texture && !textureView) @@ -315,8 +303,7 @@ HRESULT DirectX::CreateTextureFromMemory( static_assert(D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION <= UINT32_MAX, "Exceeded integer limits"); - if ((width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) - || (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) + if ((width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (3D: size %zu by %zu by %zu)\n", width, height, depth); @@ -324,16 +311,16 @@ HRESULT DirectX::CreateTextureFromMemory( } D3D11_TEXTURE3D_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.Depth = static_cast(depth); - desc.MipLevels = 1; - desc.Format = format; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = bindFlags; + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.Depth = static_cast(depth); + desc.MipLevels = 1; + desc.Format = format; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = bindFlags; ComPtr tex; - HRESULT hr = device->CreateTexture3D(&desc, &initData, tex.GetAddressOf()); + HRESULT hr = device->CreateTexture3D(&desc, &initData, tex.GetAddressOf()); if (SUCCEEDED(hr)) { if (textureView) @@ -352,13 +339,8 @@ HRESULT DirectX::CreateTextureFromMemory( return hr; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -void Private::ConstantBufferBase::CreateBuffer( - ID3D11Device* device, - size_t bytes, - ID3D11Buffer** pBuffer) +_Use_decl_annotations_ void Private::ConstantBufferBase::CreateBuffer(ID3D11Device* device, size_t bytes, ID3D11Buffer** pBuffer) { if (!device) throw std::invalid_argument("Direct3D device is null"); @@ -369,10 +351,10 @@ void Private::ConstantBufferBase::CreateBuffer( *pBuffer = nullptr; D3D11_BUFFER_DESC desc = {}; - desc.ByteWidth = static_cast(bytes); - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.ByteWidth = static_cast(bytes); + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; #if defined(_XBOX_ONE) && defined(_TITLE) @@ -385,9 +367,7 @@ void Private::ConstantBufferBase::CreateBuffer( desc.Usage = D3D11_USAGE_DYNAMIC; - ThrowIfFailed( - device->CreateBuffer(&desc, nullptr, pBuffer) - ); + ThrowIfFailed(device->CreateBuffer(&desc, nullptr, pBuffer)); #endif 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 946dd49e..af350a34 100644 --- a/Src/CommonStates.cpp +++ b/Src/CommonStates.cpp @@ -16,7 +16,6 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - // Internal state object implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing CommonStates instances. class CommonStates::Impl @@ -26,10 +25,10 @@ class CommonStates::Impl : mDevice(device) {} - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = delete; + Impl(Impl&&) = delete; Impl& operator=(Impl&&) = delete; HRESULT CreateBlendState(D3D11_BLEND srcBlend, D3D11_BLEND destBlend, _Outptr_ ID3D11BlendState** pResult); @@ -67,21 +66,15 @@ class CommonStates::Impl static SharedResourcePool instancePool; }; - // Global instance pool. SharedResourcePool CommonStates::Impl::instancePool; - // Helper for creating blend state objects. -HRESULT CommonStates::Impl::CreateBlendState( - D3D11_BLEND srcBlend, - D3D11_BLEND destBlend, - _Outptr_ ID3D11BlendState** pResult) +HRESULT CommonStates::Impl::CreateBlendState(D3D11_BLEND srcBlend, D3D11_BLEND destBlend, _Outptr_ ID3D11BlendState** pResult) { D3D11_BLEND_DESC desc = {}; - desc.RenderTarget[0].BlendEnable = (srcBlend != D3D11_BLEND_ONE) || - (destBlend != D3D11_BLEND_ZERO); + desc.RenderTarget[0].BlendEnable = (srcBlend != D3D11_BLEND_ONE) || (destBlend != D3D11_BLEND_ZERO); desc.RenderTarget[0].SrcBlend = desc.RenderTarget[0].SrcBlendAlpha = srcBlend; desc.RenderTarget[0].DestBlend = desc.RenderTarget[0].DestBlendAlpha = destBlend; @@ -97,27 +90,23 @@ HRESULT CommonStates::Impl::CreateBlendState( return hr; } - // Helper for creating depth stencil state objects. -HRESULT CommonStates::Impl::CreateDepthStencilState( - bool enable, - bool writeEnable, - bool reverseZ, - _Outptr_ ID3D11DepthStencilState** pResult) +HRESULT +CommonStates::Impl::CreateDepthStencilState(bool enable, bool writeEnable, bool reverseZ, _Outptr_ ID3D11DepthStencilState** pResult) { D3D11_DEPTH_STENCIL_DESC desc = {}; - desc.DepthEnable = enable ? TRUE : FALSE; + desc.DepthEnable = enable ? TRUE : FALSE; desc.DepthWriteMask = writeEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; - desc.DepthFunc = reverseZ ? D3D11_COMPARISON_GREATER_EQUAL : D3D11_COMPARISON_LESS_EQUAL; + desc.DepthFunc = reverseZ ? D3D11_COMPARISON_GREATER_EQUAL : D3D11_COMPARISON_LESS_EQUAL; - desc.StencilEnable = FALSE; - desc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; + desc.StencilEnable = FALSE; + desc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; desc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; - desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; - desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; - desc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + desc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; desc.BackFace = desc.FrontFace; @@ -130,18 +119,15 @@ HRESULT CommonStates::Impl::CreateDepthStencilState( return hr; } - // Helper for creating rasterizer state objects. -HRESULT CommonStates::Impl::CreateRasterizerState( - D3D11_CULL_MODE cullMode, - D3D11_FILL_MODE fillMode, - _Outptr_ ID3D11RasterizerState** pResult) +HRESULT +CommonStates::Impl::CreateRasterizerState(D3D11_CULL_MODE cullMode, D3D11_FILL_MODE fillMode, _Outptr_ ID3D11RasterizerState** pResult) { D3D11_RASTERIZER_DESC desc = {}; - desc.CullMode = cullMode; - desc.FillMode = fillMode; - desc.DepthClipEnable = TRUE; + desc.CullMode = cullMode; + desc.FillMode = fillMode; + desc.DepthClipEnable = TRUE; desc.MultisampleEnable = TRUE; HRESULT hr = mDevice->CreateRasterizerState(&desc, pResult); @@ -152,12 +138,9 @@ HRESULT CommonStates::Impl::CreateRasterizerState( return hr; } - // Helper for creating sampler state objects. -HRESULT CommonStates::Impl::CreateSamplerState( - D3D11_FILTER filter, - D3D11_TEXTURE_ADDRESS_MODE addressMode, - _Outptr_ ID3D11SamplerState** pResult) +HRESULT +CommonStates::Impl::CreateSamplerState(D3D11_FILTER filter, D3D11_TEXTURE_ADDRESS_MODE addressMode, _Outptr_ ID3D11SamplerState** pResult) { D3D11_SAMPLER_DESC desc = {}; @@ -169,7 +152,7 @@ HRESULT CommonStates::Impl::CreateSamplerState( desc.MaxAnisotropy = (mDevice->GetFeatureLevel() > D3D_FEATURE_LEVEL_9_1) ? D3D11_MAX_MAXANISOTROPY : 2u; - desc.MaxLOD = FLT_MAX; + desc.MaxLOD = FLT_MAX; desc.ComparisonFunc = D3D11_COMPARISON_NEVER; HRESULT hr = mDevice->CreateSamplerState(&desc, pResult); @@ -180,7 +163,6 @@ HRESULT CommonStates::Impl::CreateSamplerState( return hr; } - //-------------------------------------------------------------------------------------- // CommonStates //-------------------------------------------------------------------------------------- @@ -194,11 +176,9 @@ CommonStates::CommonStates(_In_ ID3D11Device* device) pImpl = Impl::instancePool.DemandCreate(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; //-------------------------------------------------------------------------------------- // Blend states @@ -206,181 +186,201 @@ CommonStates::~CommonStates() = default; ID3D11BlendState* CommonStates::Opaque() const { - return DemandCreate(pImpl->opaque, pImpl->mutex, [&](ID3D11BlendState** pResult) + return DemandCreate(pImpl->opaque, + pImpl->mutex, + [&](ID3D11BlendState** pResult) { return pImpl->CreateBlendState(D3D11_BLEND_ONE, D3D11_BLEND_ZERO, pResult); }); } - ID3D11BlendState* CommonStates::AlphaBlend() const { - return DemandCreate(pImpl->alphaBlend, pImpl->mutex, [&](ID3D11BlendState** pResult) + return DemandCreate(pImpl->alphaBlend, + pImpl->mutex, + [&](ID3D11BlendState** pResult) { return pImpl->CreateBlendState(D3D11_BLEND_ONE, D3D11_BLEND_INV_SRC_ALPHA, pResult); }); } - ID3D11BlendState* CommonStates::Additive() const { - return DemandCreate(pImpl->additive, pImpl->mutex, [&](ID3D11BlendState** pResult) + return DemandCreate(pImpl->additive, + pImpl->mutex, + [&](ID3D11BlendState** pResult) { return pImpl->CreateBlendState(D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_ONE, pResult); }); } - ID3D11BlendState* CommonStates::NonPremultiplied() const { - return DemandCreate(pImpl->nonPremultiplied, pImpl->mutex, [&](ID3D11BlendState** pResult) + return DemandCreate(pImpl->nonPremultiplied, + pImpl->mutex, + [&](ID3D11BlendState** pResult) { return pImpl->CreateBlendState(D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA, pResult); }); } - //-------------------------------------------------------------------------------------- // Depth stencil states //-------------------------------------------------------------------------------------- ID3D11DepthStencilState* CommonStates::DepthNone() const { - return DemandCreate(pImpl->depthNone, pImpl->mutex, [&](ID3D11DepthStencilState** pResult) + return DemandCreate(pImpl->depthNone, + pImpl->mutex, + [&](ID3D11DepthStencilState** pResult) { return pImpl->CreateDepthStencilState(false, false, false, pResult); }); } - ID3D11DepthStencilState* CommonStates::DepthDefault() const { - return DemandCreate(pImpl->depthDefault, pImpl->mutex, [&](ID3D11DepthStencilState** pResult) + return DemandCreate(pImpl->depthDefault, + pImpl->mutex, + [&](ID3D11DepthStencilState** pResult) { return pImpl->CreateDepthStencilState(true, true, false, pResult); }); } - ID3D11DepthStencilState* CommonStates::DepthRead() const { - return DemandCreate(pImpl->depthRead, pImpl->mutex, [&](ID3D11DepthStencilState** pResult) + return DemandCreate(pImpl->depthRead, + pImpl->mutex, + [&](ID3D11DepthStencilState** pResult) { return pImpl->CreateDepthStencilState(true, false, false, pResult); }); } - ID3D11DepthStencilState* CommonStates::DepthReverseZ() const { - return DemandCreate(pImpl->depthReverseZ, pImpl->mutex, [&](ID3D11DepthStencilState** pResult) + return DemandCreate(pImpl->depthReverseZ, + pImpl->mutex, + [&](ID3D11DepthStencilState** pResult) { return pImpl->CreateDepthStencilState(true, true, true, pResult); }); } - ID3D11DepthStencilState* CommonStates::DepthReadReverseZ() const { - return DemandCreate(pImpl->depthReadReverseZ, pImpl->mutex, [&](ID3D11DepthStencilState** pResult) + return DemandCreate(pImpl->depthReadReverseZ, + pImpl->mutex, + [&](ID3D11DepthStencilState** pResult) { return pImpl->CreateDepthStencilState(true, false, true, pResult); }); } - //-------------------------------------------------------------------------------------- // Rasterizer states //-------------------------------------------------------------------------------------- ID3D11RasterizerState* CommonStates::CullNone() const { - return DemandCreate(pImpl->cullNone, pImpl->mutex, [&](ID3D11RasterizerState** pResult) + return DemandCreate(pImpl->cullNone, + pImpl->mutex, + [&](ID3D11RasterizerState** pResult) { return pImpl->CreateRasterizerState(D3D11_CULL_NONE, D3D11_FILL_SOLID, pResult); }); } - ID3D11RasterizerState* CommonStates::CullClockwise() const { - return DemandCreate(pImpl->cullClockwise, pImpl->mutex, [&](ID3D11RasterizerState** pResult) + return DemandCreate(pImpl->cullClockwise, + pImpl->mutex, + [&](ID3D11RasterizerState** pResult) { return pImpl->CreateRasterizerState(D3D11_CULL_FRONT, D3D11_FILL_SOLID, pResult); }); } - ID3D11RasterizerState* CommonStates::CullCounterClockwise() const { - return DemandCreate(pImpl->cullCounterClockwise, pImpl->mutex, [&](ID3D11RasterizerState** pResult) + return DemandCreate(pImpl->cullCounterClockwise, + pImpl->mutex, + [&](ID3D11RasterizerState** pResult) { return pImpl->CreateRasterizerState(D3D11_CULL_BACK, D3D11_FILL_SOLID, pResult); }); } - ID3D11RasterizerState* CommonStates::Wireframe() const { - return DemandCreate(pImpl->wireframe, pImpl->mutex, [&](ID3D11RasterizerState** pResult) + return DemandCreate(pImpl->wireframe, + pImpl->mutex, + [&](ID3D11RasterizerState** pResult) { return pImpl->CreateRasterizerState(D3D11_CULL_NONE, D3D11_FILL_WIREFRAME, pResult); }); } - //-------------------------------------------------------------------------------------- // Sampler states //-------------------------------------------------------------------------------------- ID3D11SamplerState* CommonStates::PointWrap() const { - return DemandCreate(pImpl->pointWrap, pImpl->mutex, [&](ID3D11SamplerState** pResult) + return DemandCreate(pImpl->pointWrap, + pImpl->mutex, + [&](ID3D11SamplerState** pResult) { return pImpl->CreateSamplerState(D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_TEXTURE_ADDRESS_WRAP, pResult); }); } - ID3D11SamplerState* CommonStates::PointClamp() const { - return DemandCreate(pImpl->pointClamp, pImpl->mutex, [&](ID3D11SamplerState** pResult) + return DemandCreate(pImpl->pointClamp, + pImpl->mutex, + [&](ID3D11SamplerState** pResult) { return pImpl->CreateSamplerState(D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_TEXTURE_ADDRESS_CLAMP, pResult); }); } - ID3D11SamplerState* CommonStates::LinearWrap() const { - return DemandCreate(pImpl->linearWrap, pImpl->mutex, [&](ID3D11SamplerState** pResult) + return DemandCreate(pImpl->linearWrap, + pImpl->mutex, + [&](ID3D11SamplerState** pResult) { return pImpl->CreateSamplerState(D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_TEXTURE_ADDRESS_WRAP, pResult); }); } - ID3D11SamplerState* CommonStates::LinearClamp() const { - return DemandCreate(pImpl->linearClamp, pImpl->mutex, [&](ID3D11SamplerState** pResult) + return DemandCreate(pImpl->linearClamp, + pImpl->mutex, + [&](ID3D11SamplerState** pResult) { return pImpl->CreateSamplerState(D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_TEXTURE_ADDRESS_CLAMP, pResult); }); } - ID3D11SamplerState* CommonStates::AnisotropicWrap() const { - return DemandCreate(pImpl->anisotropicWrap, pImpl->mutex, [&](ID3D11SamplerState** pResult) + return DemandCreate(pImpl->anisotropicWrap, + pImpl->mutex, + [&](ID3D11SamplerState** pResult) { return pImpl->CreateSamplerState(D3D11_FILTER_ANISOTROPIC, D3D11_TEXTURE_ADDRESS_WRAP, pResult); }); } - ID3D11SamplerState* CommonStates::AnisotropicClamp() const { - return DemandCreate(pImpl->anisotropicClamp, pImpl->mutex, [&](ID3D11SamplerState** pResult) + return DemandCreate(pImpl->anisotropicClamp, + pImpl->mutex, + [&](ID3D11SamplerState** pResult) { return pImpl->CreateSamplerState(D3D11_FILTER_ANISOTROPIC, D3D11_TEXTURE_ADDRESS_CLAMP, pResult); }); diff --git a/Src/DDSTextureLoader.cpp b/Src/DDSTextureLoader.cpp index cb58b4df..d56dc0d1 100644 --- a/Src/DDSTextureLoader.cpp +++ b/Src/DDSTextureLoader.cpp @@ -34,21 +34,20 @@ static_assert(static_cast(DDS_RESOURCE_MISC_TEXTURECUBE) == static_cast(RowBytes); + initData[index].pSysMem = pSrcBits; + initData[index].SysMemPitch = static_cast(RowBytes); initData[index].SysMemSlicePitch = static_cast(NumBytes); ++index; } @@ -102,7 +101,7 @@ namespace ++skipMip; } - if (pSrcBits + (NumBytes*d) > pEndBits) + if (pSrcBits + (NumBytes * d) > pEndBits) { return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } @@ -131,24 +130,23 @@ namespace } //-------------------------------------------------------------------------------------- - HRESULT CreateD3DResources( - _In_ ID3D11Device* d3dDevice, - _In_ uint32_t resDim, - _In_ size_t width, - _In_ size_t height, - _In_ size_t depth, - _In_ size_t mipCount, - _In_ size_t arraySize, - _In_ DXGI_FORMAT format, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _In_ bool isCubeMap, - _In_reads_opt_(mipCount*arraySize) const D3D11_SUBRESOURCE_DATA* initData, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept + HRESULT CreateD3DResources(_In_ ID3D11Device* d3dDevice, + _In_ uint32_t resDim, + _In_ size_t width, + _In_ size_t height, + _In_ size_t depth, + _In_ size_t mipCount, + _In_ size_t arraySize, + _In_ DXGI_FORMAT format, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _In_ bool isCubeMap, + _In_reads_opt_(mipCount* arraySize) const D3D11_SUBRESOURCE_DATA* initData, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { if (!d3dDevice) return E_POINTER; @@ -166,241 +164,218 @@ namespace switch (resDim) { - case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: { + D3D11_TEXTURE1D_DESC desc = {}; + desc.Width = static_cast(width); + desc.MipLevels = static_cast(mipCount); + desc.ArraySize = static_cast(arraySize); + desc.Format = format; + desc.Usage = usage; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuAccessFlags; + desc.MiscFlags = miscFlags & ~static_cast(D3D11_RESOURCE_MISC_TEXTURECUBE); + + ID3D11Texture1D* tex = nullptr; + hr = d3dDevice->CreateTexture1D(&desc, initData, &tex); + if (SUCCEEDED(hr) && tex) { - D3D11_TEXTURE1D_DESC desc = {}; - desc.Width = static_cast(width); - desc.MipLevels = static_cast(mipCount); - desc.ArraySize = static_cast(arraySize); - desc.Format = format; - desc.Usage = usage; - desc.BindFlags = bindFlags; - desc.CPUAccessFlags = cpuAccessFlags; - desc.MiscFlags = miscFlags & ~static_cast(D3D11_RESOURCE_MISC_TEXTURECUBE); - - ID3D11Texture1D* tex = nullptr; - hr = d3dDevice->CreateTexture1D(&desc, - initData, - &tex - ); - if (SUCCEEDED(hr) && tex) + if (textureView) { - if (textureView) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = format; - - if (arraySize > 1) - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; - SRVDesc.Texture1DArray.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; - SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); - } - else - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; - SRVDesc.Texture1D.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; - } + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; - hr = d3dDevice->CreateShaderResourceView(tex, - &SRVDesc, - textureView - ); - if (FAILED(hr)) - { - tex->Release(); - return hr; - } - } - - if (texture) + if (arraySize > 1) { - *texture = tex; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; + SRVDesc.Texture1DArray.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; + SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); } else { - SetDebugObjectName(tex, "DDSTextureLoader"); + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; + SRVDesc.Texture1D.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) + { tex->Release(); + return hr; } } - } - break; - case D3D11_RESOURCE_DIMENSION_TEXTURE2D: - { - D3D11_TEXTURE2D_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.MipLevels = static_cast(mipCount); - desc.ArraySize = static_cast(arraySize); - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - desc.Usage = usage; - desc.BindFlags = bindFlags; - desc.CPUAccessFlags = cpuAccessFlags; - if (isCubeMap) + if (texture) { - desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE; + *texture = tex; } else { - desc.MiscFlags = miscFlags & ~static_cast(D3D11_RESOURCE_MISC_TEXTURECUBE); + SetDebugObjectName(tex, "DDSTextureLoader"); + tex->Release(); } + } + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: { + D3D11_TEXTURE2D_DESC desc = {}; + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.MipLevels = static_cast(mipCount); + desc.ArraySize = static_cast(arraySize); + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = usage; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuAccessFlags; + if (isCubeMap) + { + desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE; + } + else + { + desc.MiscFlags = miscFlags & ~static_cast(D3D11_RESOURCE_MISC_TEXTURECUBE); + } - ID3D11Texture2D* tex = nullptr; - hr = d3dDevice->CreateTexture2D(&desc, - initData, - &tex - ); - if (SUCCEEDED(hr) && tex) + ID3D11Texture2D* tex = nullptr; + hr = d3dDevice->CreateTexture2D(&desc, initData, &tex); + if (SUCCEEDED(hr) && tex) + { + if (textureView) { - if (textureView) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = format; + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; - if (isCubeMap) - { - if (arraySize > 6) - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; - SRVDesc.TextureCubeArray.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; - - // Earlier we set arraySize to (NumCubes * 6) - SRVDesc.TextureCubeArray.NumCubes = static_cast(arraySize / 6); - } - else - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; - SRVDesc.TextureCube.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; - } - } - else if (arraySize > 1) + if (isCubeMap) + { + if (arraySize > 6) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; - SRVDesc.Texture2DArray.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; - SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; + SRVDesc.TextureCubeArray.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; + + // Earlier we set arraySize to (NumCubes * 6) + SRVDesc.TextureCubeArray.NumCubes = static_cast(arraySize / 6); } else { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Texture2D.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; - } - - hr = d3dDevice->CreateShaderResourceView(tex, - &SRVDesc, - textureView - ); - if (FAILED(hr)) - { - tex->Release(); - return hr; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; + SRVDesc.TextureCube.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; } } - - if (texture) + else if (arraySize > 1) { - *texture = tex; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; + SRVDesc.Texture2DArray.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; + SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); } else { - SetDebugObjectName(tex, "DDSTextureLoader"); + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) + { tex->Release(); + return hr; } } - } - break; - case D3D11_RESOURCE_DIMENSION_TEXTURE3D: + if (texture) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "DDSTextureLoader"); + tex->Release(); + } + } + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: { + D3D11_TEXTURE3D_DESC desc = {}; + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.Depth = static_cast(depth); + desc.MipLevels = static_cast(mipCount); + desc.Format = format; + desc.Usage = usage; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuAccessFlags; + desc.MiscFlags = miscFlags & ~UINT(D3D11_RESOURCE_MISC_TEXTURECUBE); + + ID3D11Texture3D* tex = nullptr; + hr = d3dDevice->CreateTexture3D(&desc, initData, &tex); + if (SUCCEEDED(hr) && tex) { - D3D11_TEXTURE3D_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.Depth = static_cast(depth); - desc.MipLevels = static_cast(mipCount); - desc.Format = format; - desc.Usage = usage; - desc.BindFlags = bindFlags; - desc.CPUAccessFlags = cpuAccessFlags; - desc.MiscFlags = miscFlags & ~UINT(D3D11_RESOURCE_MISC_TEXTURECUBE); - - ID3D11Texture3D* tex = nullptr; - hr = d3dDevice->CreateTexture3D(&desc, - initData, - &tex - ); - if (SUCCEEDED(hr) && tex) + if (textureView) { - if (textureView) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = format; + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; - SRVDesc.Texture3D.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; + SRVDesc.Texture3D.MipLevels = (!mipCount) ? UINT(-1) : desc.MipLevels; - hr = d3dDevice->CreateShaderResourceView(tex, - &SRVDesc, - textureView - ); - if (FAILED(hr)) - { - tex->Release(); - return hr; - } - } - - if (texture) - { - *texture = tex; - } - else + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) { - SetDebugObjectName(tex, "DDSTextureLoader"); tex->Release(); + return hr; } } + + if (texture) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "DDSTextureLoader"); + tex->Release(); + } } - break; + } + break; - default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } return hr; } //-------------------------------------------------------------------------------------- - HRESULT CreateTextureFromDDS( - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_opt_ ID3D11DeviceX* d3dDeviceX, + HRESULT CreateTextureFromDDS(_In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_opt_ ID3D11DeviceX* d3dDeviceX, _In_opt_ ID3D11DeviceContextX* d3dContextX, - #endif - _In_ const DDS_HEADER* header, +#endif + _In_ const DDS_HEADER* header, _In_reads_bytes_(bitSize) const uint8_t* bitData, - _In_ size_t bitSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept + _In_ size_t bitSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { 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; - uint32_t resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN; - UINT arraySize = 1; - DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; - bool isCubeMap = false; + uint32_t resDim = D3D11_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)) @@ -408,8 +383,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)); @@ -425,8 +399,7 @@ namespace case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: case DXGI_FORMAT_420_OPAQUE: - if ((d3d10ext->resourceDimension != D3D11_RESOURCE_DIMENSION_TEXTURE2D) - || (width % 2) != 0 || (height % 2) != 0) + if ((d3d10ext->resourceDimension != D3D11_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); @@ -543,7 +516,7 @@ namespace isCubeMap = true; } - depth = 1; + depth = 1; resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D; // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture @@ -552,9 +525,7 @@ namespace assert(BitsPerPixel(format) != 0); } - if ((miscFlags & D3D11_RESOURCE_MISC_TEXTURECUBE) - && (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE2D) - && ((arraySize % 6) == 0)) + if ((miscFlags & D3D11_RESOURCE_MISC_TEXTURECUBE) && (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE2D) && ((arraySize % 6) == 0)) { isCubeMap = true; } @@ -569,8 +540,7 @@ namespace switch (resDim) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: - if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) + if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (1D: array %u, size %u)\n", arraySize, width); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -581,17 +551,18 @@ namespace if (isCubeMap) { // This is the right bound because we set arraySize to (NumCubes*6) above - if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURECUBE_DIMENSION) || - (height > D3D11_REQ_TEXTURECUBE_DIMENSION)) + if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURECUBE_DIMENSION) + || (height > D3D11_REQ_TEXTURECUBE_DIMENSION)) { - DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (2D cubemap: array %u, size %u by %u)\n", arraySize, width, height); + DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (2D cubemap: array %u, size %u by %u)\n", + arraySize, + width, + height); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } - else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) || - (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) + || (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (2D: array %u, size %u by %u)\n", arraySize, width, height); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); @@ -599,12 +570,14 @@ namespace break; case D3D11_RESOURCE_DIMENSION_TEXTURE3D: - if ((arraySize > 1) || - (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) + if ((arraySize > 1) || (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) + || (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) { - DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (3D: array %u, size %u by %u by %u)\n", arraySize, width, height, depth); + DebugTrace("ERROR: Resource dimensions too large for DirectX 11 (3D: array %u, size %u by %u by %u)\n", + arraySize, + width, + height, + depth); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; @@ -624,18 +597,17 @@ namespace { // See if format is supported for auto-gen mipmaps (varies by feature level) UINT fmtSupport = 0; - hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); + hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) { // 10level9 feature levels do not support auto-gen mipgen for volume textures - if ((resDim != D3D11_RESOURCE_DIMENSION_TEXTURE3D) - || (d3dDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_10_0)) + if ((resDim != D3D11_RESOURCE_DIMENSION_TEXTURE3D) || (d3dDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_10_0)) { autogen = true; - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) if (!d3dDeviceX || !d3dContextX) return E_INVALIDARG; - #endif +#endif } } } @@ -644,21 +616,28 @@ namespace { // Create texture with auto-generated mipmaps ID3D11Resource* tex = nullptr; - hr = CreateD3DResources(d3dDevice, - resDim, width, height, depth, 0, arraySize, + hr = CreateD3DResources(d3dDevice, + resDim, + width, + height, + depth, + 0, + arraySize, format, usage, bindFlags | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, cpuAccessFlags, - miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS, loadFlags, + miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS, + loadFlags, isCubeMap, nullptr, - &tex, textureView); + &tex, + textureView); if (SUCCEEDED(hr)) { size_t numBytes = 0; size_t rowBytes = 0; - hr = GetSurfaceInfo(width, height, format, &numBytes, &rowBytes, nullptr); + hr = GetSurfaceInfo(width, height, format, &numBytes, &rowBytes, nullptr); if (FAILED(hr)) return hr; @@ -680,13 +659,13 @@ namespace switch (desc.ViewDimension) { - case D3D_SRV_DIMENSION_TEXTURE1D: mipLevels = desc.Texture1D.MipLevels; break; - case D3D_SRV_DIMENSION_TEXTURE1DARRAY: mipLevels = desc.Texture1DArray.MipLevels; break; - case D3D_SRV_DIMENSION_TEXTURE2D: mipLevels = desc.Texture2D.MipLevels; break; - case D3D_SRV_DIMENSION_TEXTURE2DARRAY: mipLevels = desc.Texture2DArray.MipLevels; break; - case D3D_SRV_DIMENSION_TEXTURECUBE: mipLevels = desc.TextureCube.MipLevels; break; - case D3D_SRV_DIMENSION_TEXTURECUBEARRAY:mipLevels = desc.TextureCubeArray.MipLevels; break; - case D3D_SRV_DIMENSION_TEXTURE3D: mipLevels = desc.Texture3D.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE1D: mipLevels = desc.Texture1D.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE1DARRAY: mipLevels = desc.Texture1DArray.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE2D: mipLevels = desc.Texture2D.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE2DARRAY: mipLevels = desc.Texture2DArray.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURECUBE: mipLevels = desc.TextureCube.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURECUBEARRAY: mipLevels = desc.TextureCubeArray.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE3D: mipLevels = desc.Texture3D.MipLevels; break; default: (*textureView)->Release(); *textureView = nullptr; @@ -694,7 +673,7 @@ namespace return E_UNEXPECTED; } - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) std::unique_ptr initData(new (std::nothrow) D3D11_SUBRESOURCE_DATA[arraySize]); if (!initData) @@ -714,8 +693,8 @@ namespace return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } - initData[item].pSysMem = pSrcBits; - initData[item].SysMemPitch = static_cast(rowBytes); + initData[item].pSysMem = pSrcBits; + initData[item].SysMemPitch = static_cast(rowBytes); initData[item].SysMemSlicePitch = static_cast(numBytes); pSrcBits += numBytes; } @@ -723,35 +702,42 @@ namespace ID3D11Resource* pStaging = nullptr; switch (resDim) { - case D3D11_RESOURCE_DIMENSION_TEXTURE1D: - { - ID3D11Texture1D *temp = nullptr; - CD3D11_TEXTURE1D_DESC stagingDesc(format, width, arraySize, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ); - hr = d3dDevice->CreateTexture1D(&stagingDesc, initData.get(), &temp); - if (SUCCEEDED(hr)) - pStaging = temp; - } - break; + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: { + ID3D11Texture1D* temp = nullptr; + CD3D11_TEXTURE1D_DESC stagingDesc(format, width, arraySize, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ); + hr = d3dDevice->CreateTexture1D(&stagingDesc, initData.get(), &temp); + if (SUCCEEDED(hr)) + pStaging = temp; + } + break; - case D3D11_RESOURCE_DIMENSION_TEXTURE2D: - { - ID3D11Texture2D *temp = nullptr; - CD3D11_TEXTURE2D_DESC stagingDesc(format, width, height, arraySize, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, isCubeMap ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0); - hr = d3dDevice->CreateTexture2D(&stagingDesc, initData.get(), &temp); - if (SUCCEEDED(hr)) - pStaging = temp; - } - break; + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: { + ID3D11Texture2D* temp = nullptr; + CD3D11_TEXTURE2D_DESC stagingDesc(format, + width, + height, + arraySize, + 1, + 0, + D3D11_USAGE_STAGING, + D3D11_CPU_ACCESS_READ, + 1, + 0, + isCubeMap ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0); + hr = d3dDevice->CreateTexture2D(&stagingDesc, initData.get(), &temp); + if (SUCCEEDED(hr)) + pStaging = temp; + } + break; - case D3D11_RESOURCE_DIMENSION_TEXTURE3D: - { - ID3D11Texture3D *temp = nullptr; - CD3D11_TEXTURE3D_DESC stagingDesc(format, width, height, depth, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ); - hr = d3dDevice->CreateTexture3D(&stagingDesc, initData.get(), &temp); - if (SUCCEEDED(hr)) - pStaging = temp; - } - break; + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: { + ID3D11Texture3D* temp = nullptr; + CD3D11_TEXTURE3D_DESC stagingDesc(format, width, height, depth, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ); + hr = d3dDevice->CreateTexture3D(&stagingDesc, initData.get(), &temp); + if (SUCCEEDED(hr)) + pStaging = temp; + } + break; }; if (SUCCEEDED(hr)) @@ -763,10 +749,13 @@ namespace } UINT64 copyFence = d3dContextX->InsertFence(0); - while (d3dDeviceX->IsFencePending(copyFence)) { SwitchToThread(); } + while (d3dDeviceX->IsFencePending(copyFence)) + { + SwitchToThread(); + } pStaging->Release(); } - #else +#else if (arraySize > 1) { const uint8_t* pSrcBits = bitData; @@ -782,7 +771,8 @@ namespace } const UINT res = D3D11CalcSubresource(0, item, mipLevels); - d3dContext->UpdateSubresource(tex, res, nullptr, pSrcBits, static_cast(rowBytes), static_cast(numBytes)); + d3dContext + ->UpdateSubresource(tex, res, nullptr, pSrcBits, static_cast(rowBytes), static_cast(numBytes)); pSrcBits += numBytes; } } @@ -790,7 +780,7 @@ namespace { d3dContext->UpdateSubresource(tex, 0, nullptr, bitData, static_cast(rowBytes), static_cast(numBytes)); } - #endif +#endif d3dContext->GenerateMips(*textureView); @@ -814,23 +804,43 @@ namespace } 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, format, - maxsize, bitSize, bitData, - twidth, theight, tdepth, skipMip, initData.get()); + size_t tdepth = 0; + hr = FillInitData(width, + height, + depth, + mipCount, + arraySize, + format, + maxsize, + bitSize, + bitData, + twidth, + theight, + tdepth, + skipMip, + initData.get()); if (SUCCEEDED(hr)) { hr = CreateD3DResources(d3dDevice, - resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, + resDim, + twidth, + theight, + tdepth, + mipCount - skipMip, + arraySize, format, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, isCubeMap, initData.get(), - texture, textureView); + texture, + textureView); if (FAILED(hr) && !maxsize && (mipCount > 1)) { @@ -839,36 +849,54 @@ namespace { case D3D_FEATURE_LEVEL_9_1: case D3D_FEATURE_LEVEL_9_2: - case D3D_FEATURE_LEVEL_9_3: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + case D3D_FEATURE_LEVEL_9_3: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); case D3D_FEATURE_LEVEL_10_0: case D3D_FEATURE_LEVEL_10_1: - maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? 2048u /*D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ - : 8192u /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) ? 2048u /*D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ + : + 8192u /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; break; default: // D3D_FEATURE_LEVEL_11_0 - maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION - : D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) ? D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : + D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; break; } - hr = FillInitData(width, height, depth, mipCount, arraySize, format, - maxsize, bitSize, bitData, - twidth, theight, tdepth, skipMip, initData.get()); + hr = FillInitData(width, + height, + depth, + mipCount, + arraySize, + format, + maxsize, + bitSize, + bitData, + twidth, + theight, + tdepth, + skipMip, + initData.get()); if (SUCCEEDED(hr)) { hr = CreateD3DResources(d3dDevice, - resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, + resDim, + twidth, + theight, + tdepth, + mipCount - skipMip, + arraySize, format, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, isCubeMap, initData.get(), - texture, textureView); + texture, + textureView); } } } @@ -878,15 +906,14 @@ namespace } //-------------------------------------------------------------------------------------- - void SetDebugTextureInfo( - _In_z_ const wchar_t* fileName, - _In_opt_ ID3D11Resource** texture, - _In_opt_ ID3D11ShaderResourceView** textureView) noexcept + void SetDebugTextureInfo(_In_z_ const wchar_t* fileName, + _In_opt_ ID3D11Resource** texture, + _In_opt_ ID3D11ShaderResourceView** textureView) noexcept { - #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D11_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) if (texture || textureView) { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) if (texture && *texture) { (*texture)->SetName(fileName); @@ -895,104 +922,98 @@ namespace { (*textureView)->SetName(fileName); } - #else - CHAR strFileA[MAX_PATH]; - const int result = WideCharToMultiByte(CP_UTF8, - WC_NO_BEST_FIT_CHARS, - fileName, - -1, - strFileA, - MAX_PATH, - nullptr, - nullptr - ); +#else + CHAR strFileA[MAX_PATH]; + const int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, fileName, -1, strFileA, MAX_PATH, nullptr, nullptr); if (result > 0) { if (texture && *texture) { - (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, - static_cast(result), - strFileA - ); + (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast(result), strFileA); } if (textureView && *textureView) { - (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, - static_cast(result), - strFileA - ); + (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast(result), strFileA); } } - #endif +#endif } - #else +#else UNREFERENCED_PARAMETER(fileName); UNREFERENCED_PARAMETER(texture); UNREFERENCED_PARAMETER(textureView); - #endif +#endif } } // anonymous namespace - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromMemory( - ID3D11Device* d3dDevice, - const uint8_t* ddsData, - size_t ddsDataSize, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) noexcept { return CreateDDSTextureFromMemoryEx(d3dDevice, - ddsData, ddsDataSize, + ddsData, + ddsDataSize, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, DDS_LOADER_DEFAULT, - texture, textureView, alphaMode); + texture, + textureView, + alphaMode); } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateDDSTextureFromMemory( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateDDSTextureFromMemory(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateDDSTextureFromMemory( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const uint8_t* ddsData, - size_t ddsDataSize, - ID3D11Resource** texture, + HRESULT + DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode) noexcept + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) noexcept { - return CreateDDSTextureFromMemoryEx(d3dDevice, d3dContext, - ddsData, ddsDataSize, + return CreateDDSTextureFromMemoryEx(d3dDevice, + d3dContext, + ddsData, + ddsDataSize, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, DDS_LOADER_DEFAULT, - texture, textureView, alphaMode); + texture, + textureView, + alphaMode); } -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromMemoryEx( - ID3D11Device* d3dDevice, - const uint8_t* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - DDS_ALPHA_MODE* alphaMode) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, + const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) noexcept { if (texture) { @@ -1018,29 +1039,33 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( } // Validate DDS file in memory - const DDS_HEADER* header = nullptr; - const uint8_t* bitData = nullptr; - size_t bitSize = 0; - - HRESULT hr = LoadTextureDataFromMemory(ddsData, ddsDataSize, - &header, - &bitData, - &bitSize - ); + const DDS_HEADER* header = nullptr; + const uint8_t* bitData = nullptr; + size_t bitSize = 0; + + HRESULT hr = LoadTextureDataFromMemory(ddsData, ddsDataSize, &header, &bitData, &bitSize); if (FAILED(hr)) { return hr; } - hr = CreateTextureFromDDS(d3dDevice, nullptr, - #if defined(_XBOX_ONE) && defined(_TITLE) - nullptr, nullptr, - #endif - header, bitData, bitSize, + hr = CreateTextureFromDDS(d3dDevice, + nullptr, +#if defined(_XBOX_ONE) && defined(_TITLE) + nullptr, + nullptr, +#endif + header, + bitData, + bitSize, maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (SUCCEEDED(hr)) { if (texture && *texture) @@ -1062,25 +1087,25 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateDDSTextureFromMemoryEx( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateDDSTextureFromMemoryEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateDDSTextureFromMemoryEx( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const uint8_t* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, + HRESULT + DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, - DDS_ALPHA_MODE* alphaMode) noexcept + DDS_ALPHA_MODE* alphaMode) noexcept { if (texture) { @@ -1106,29 +1131,33 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( } // Validate DDS file in memory - const DDS_HEADER* header = nullptr; - const uint8_t* bitData = nullptr; - size_t bitSize = 0; - - HRESULT hr = LoadTextureDataFromMemory(ddsData, ddsDataSize, - &header, - &bitData, - &bitSize - ); + const DDS_HEADER* header = nullptr; + const uint8_t* bitData = nullptr; + size_t bitSize = 0; + + HRESULT hr = LoadTextureDataFromMemory(ddsData, ddsDataSize, &header, &bitData, &bitSize); if (FAILED(hr)) { return hr; } - hr = CreateTextureFromDDS(d3dDevice, d3dContext, - #if defined(_XBOX_ONE) && defined(_TITLE) - d3dDevice, d3dContext, - #endif - header, bitData, bitSize, + hr = CreateTextureFromDDS(d3dDevice, + d3dContext, +#if defined(_XBOX_ONE) && defined(_TITLE) + d3dDevice, + d3dContext, +#endif + header, + bitData, + bitSize, maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (SUCCEEDED(hr)) { if (texture && *texture) @@ -1149,60 +1178,67 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx( } //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromFile( - ID3D11Device* d3dDevice, - const wchar_t* fileName, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) noexcept { return CreateDDSTextureFromFileEx(d3dDevice, fileName, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, DDS_LOADER_DEFAULT, - texture, textureView, alphaMode); + texture, + textureView, + alphaMode); } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateDDSTextureFromFile( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateDDSTextureFromFile(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateDDSTextureFromFile( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const wchar_t* fileName, - ID3D11Resource** texture, + HRESULT + DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const wchar_t* fileName, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, - size_t maxsize, - DDS_ALPHA_MODE* alphaMode) noexcept + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) noexcept { - return CreateDDSTextureFromFileEx(d3dDevice, d3dContext, + return CreateDDSTextureFromFileEx(d3dDevice, + d3dContext, fileName, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, DDS_LOADER_DEFAULT, - texture, textureView, alphaMode); + texture, + textureView, + alphaMode); } -_Use_decl_annotations_ -HRESULT DirectX::CreateDDSTextureFromFileEx( - ID3D11Device* d3dDevice, - const wchar_t* fileName, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - DDS_ALPHA_MODE* alphaMode) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) noexcept { if (texture) { @@ -1227,31 +1263,34 @@ 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; } - hr = CreateTextureFromDDS(d3dDevice, nullptr, - #if defined(_XBOX_ONE) && defined(_TITLE) - nullptr, nullptr, - #endif - header, bitData, bitSize, + hr = CreateTextureFromDDS(d3dDevice, + nullptr, +#if defined(_XBOX_ONE) && defined(_TITLE) + nullptr, + nullptr, +#endif + header, + bitData, + bitSize, maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (SUCCEEDED(hr)) { @@ -1266,24 +1305,24 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateDDSTextureFromFileEx( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateDDSTextureFromFileEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateDDSTextureFromFileEx( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const wchar_t* fileName, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - DDS_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, + HRESULT + DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + DDS_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, - DDS_ALPHA_MODE* alphaMode) noexcept + DDS_ALPHA_MODE* alphaMode) noexcept { if (texture) { @@ -1308,31 +1347,34 @@ 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; } - hr = CreateTextureFromDDS(d3dDevice, d3dContext, - #if defined(_XBOX_ONE) && defined(_TITLE) - d3dDevice, d3dContext, - #endif - header, bitData, bitSize, + hr = CreateTextureFromDDS(d3dDevice, + d3dContext, +#if defined(_XBOX_ONE) && defined(_TITLE) + d3dDevice, + d3dContext, +#endif + header, + bitData, + bitSize, maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (SUCCEEDED(hr)) { @@ -1345,7 +1387,6 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( return hr; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients @@ -1353,79 +1394,101 @@ HRESULT DirectX::CreateDDSTextureFromFileEx( namespace DirectX { - HRESULT __cdecl CreateDDSTextureFromFile( - _In_ ID3D11Device* d3dDevice, - _In_z_ const __wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize, - _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept + HRESULT __cdecl CreateDDSTextureFromFile(_In_ ID3D11Device* d3dDevice, + _In_z_ const __wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize, + _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept { return CreateDDSTextureFromFile(d3dDevice, reinterpret_cast(szFileName), - texture, textureView, maxsize, alphaMode); + texture, + textureView, + maxsize, + alphaMode); } HRESULT __cdecl CreateDDSTextureFromFile( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, +#else + _In_ ID3D11Device* d3dDevice, _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const __wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, +#endif + _In_z_ const __wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize, - _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept + _In_ size_t maxsize, + _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept { - return CreateDDSTextureFromFile(d3dDevice, d3dContext, + return CreateDDSTextureFromFile(d3dDevice, + d3dContext, reinterpret_cast(szFileName), - texture, textureView, maxsize, alphaMode); + texture, + textureView, + maxsize, + alphaMode); } - HRESULT __cdecl CreateDDSTextureFromFileEx( - _In_ ID3D11Device* d3dDevice, - _In_z_ const __wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept + HRESULT __cdecl CreateDDSTextureFromFileEx(_In_ ID3D11Device* d3dDevice, + _In_z_ const __wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept { return CreateDDSTextureFromFileEx(d3dDevice, reinterpret_cast(szFileName), - maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView, alphaMode); + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView, + alphaMode); } HRESULT __cdecl CreateDDSTextureFromFileEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, +#else + _In_ ID3D11Device* d3dDevice, _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const __wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ DDS_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, +#endif + _In_z_ const __wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ DDS_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept + _Out_opt_ DDS_ALPHA_MODE* alphaMode) noexcept { - return CreateDDSTextureFromFileEx(d3dDevice, d3dContext, + return CreateDDSTextureFromFileEx(d3dDevice, + d3dContext, reinterpret_cast(szFileName), - maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView, alphaMode); + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView, + alphaMode); } -} +} // namespace DirectX #endif // !_NATIVE_WCHAR_T_DEFINED diff --git a/Src/DGSLEffect.cpp b/Src/DGSLEffect.cpp index 7c1fd69b..9a17a3dc 100644 --- a/Src/DGSLEffect.cpp +++ b/Src/DGSLEffect.cpp @@ -22,12 +22,12 @@ namespace DirectX namespace EffectDirtyFlags { constexpr int ConstantBufferMaterial = 0x10000; - constexpr int ConstantBufferLight = 0x20000; - constexpr int ConstantBufferObject = 0x40000; - constexpr int ConstantBufferMisc = 0x80000; - constexpr int ConstantBufferBones = 0x100000; - } -} + constexpr int ConstantBufferLight = 0x20000; + constexpr int ConstantBufferObject = 0x40000; + constexpr int ConstantBufferMisc = 0x80000; + constexpr int ConstantBufferBones = 0x100000; + } // namespace EffectDirtyFlags +} // namespace DirectX using namespace DirectX; using Microsoft::WRL::ComPtr; @@ -35,34 +35,34 @@ using Microsoft::WRL::ComPtr; namespace { // Constant buffer layout. Must match the shader! -#pragma pack(push,1) +#pragma pack(push, 1) -// Slot 0 + // Slot 0 struct MaterialConstants { - XMVECTOR Ambient; - XMVECTOR Diffuse; - XMVECTOR Specular; - XMVECTOR Emissive; - float SpecularPower; - float Padding0; - float Padding1; - float Padding2; + XMVECTOR Ambient; + XMVECTOR Diffuse; + XMVECTOR Specular; + XMVECTOR Emissive; + float SpecularPower; + float Padding0; + float Padding1; + float Padding2; }; // Slot 1 struct LightConstants { - XMVECTOR Ambient; - XMVECTOR LightColor[DGSLEffect::MaxDirectionalLights]; - XMVECTOR LightAttenuation[DGSLEffect::MaxDirectionalLights]; - XMVECTOR LightDirection[DGSLEffect::MaxDirectionalLights]; - XMVECTOR LightSpecularIntensity[DGSLEffect::MaxDirectionalLights]; - UINT IsPointLight[DGSLEffect::MaxDirectionalLights]; - UINT ActiveLights; - float Padding0; - float Padding1; - float Padding2; + XMVECTOR Ambient; + XMVECTOR LightColor[DGSLEffect::MaxDirectionalLights]; + XMVECTOR LightAttenuation[DGSLEffect::MaxDirectionalLights]; + XMVECTOR LightDirection[DGSLEffect::MaxDirectionalLights]; + XMVECTOR LightSpecularIntensity[DGSLEffect::MaxDirectionalLights]; + UINT IsPointLight[DGSLEffect::MaxDirectionalLights]; + UINT ActiveLights; + float Padding0; + float Padding1; + float Padding2; }; // Note - DGSL does not appear to make use of LightAttenuation or IsPointLight. Not sure if it uses ActiveLights either. @@ -70,12 +70,12 @@ namespace // Slot 2 struct ObjectConstants { - XMMATRIX LocalToWorld4x4; - XMMATRIX LocalToProjected4x4; - XMMATRIX WorldToLocal4x4; - XMMATRIX WorldToView4x4; - XMMATRIX UvTransform4x4; - XMVECTOR EyePosition; + XMMATRIX LocalToWorld4x4; + XMMATRIX LocalToProjected4x4; + XMMATRIX WorldToLocal4x4; + XMMATRIX WorldToView4x4; + XMMATRIX UvTransform4x4; + XMVECTOR EyePosition; }; // Slot 3 @@ -103,23 +103,22 @@ namespace XM_ALIGNED_STRUCT(16) DGSLEffectConstants { - MaterialConstants material; - LightConstants light; - ObjectConstants object; - MiscConstants misc; - BoneConstants bones; + MaterialConstants material; + LightConstants light; + ObjectConstants object; + MiscConstants misc; + BoneConstants bones; }; struct DGSLEffectTraits { static constexpr int VertexShaderCount = 8; - static constexpr int PixelShaderCount = 12; + static constexpr int PixelShaderCount = 12; static const ShaderBytecode VertexShaderBytecode[VertexShaderCount]; static const ShaderBytecode PixelShaderBytecode[PixelShaderCount]; }; -} - +} // namespace #pragma region Shaders // Include the precompiled shader code. @@ -180,11 +179,9 @@ namespace #include "DGSLLambert_mainTxTk.inc" #include "DGSLPhong_mainTxTk.inc" #endif -} - +} // namespace -const ShaderBytecode DGSLEffectTraits::VertexShaderBytecode[] = -{ +const ShaderBytecode DGSLEffectTraits::VertexShaderBytecode[] = { { DGSLEffect_main, sizeof(DGSLEffect_main) }, { DGSLEffect_mainVc, sizeof(DGSLEffect_mainVc) }, { DGSLEffect_main1Bones, sizeof(DGSLEffect_main1Bones) }, @@ -195,9 +192,7 @@ const ShaderBytecode DGSLEffectTraits::VertexShaderBytecode[] = { DGSLEffect_main4BonesVc, sizeof(DGSLEffect_main4BonesVc) }, }; - -const ShaderBytecode DGSLEffectTraits::PixelShaderBytecode[] = -{ +const ShaderBytecode DGSLEffectTraits::PixelShaderBytecode[] = { { DGSLUnlit_main, sizeof(DGSLUnlit_main) }, // UNLIT (no texture) { DGSLLambert_main, sizeof(DGSLLambert_main) }, // LAMBERT (no texture) { DGSLPhong_main, sizeof(DGSLPhong_main) }, // PHONG (no texture) @@ -216,63 +211,64 @@ const ShaderBytecode DGSLEffectTraits::PixelShaderBytecode[] = }; #pragma endregion - class DGSLEffect::Impl : public AlignedNew { public: - Impl(_In_ ID3D11Device* device, _In_opt_ ID3D11PixelShader* pixelShader) : - constants{}, - world{}, - view{}, - projection{}, - lightEnabled{}, - lightDiffuseColor{}, - lightSpecularColor{}, - dirtyFlags(INT_MAX), - vertexColorEnabled(false), - textureEnabled(false), - specularEnabled(false), - alphaDiscardEnabled(false), - weightsPerVertex(0), - mCBMaterial(device), - mCBLight(device), - mCBObject(device), - mCBMisc(device), - mPixelShader(pixelShader), - mDeviceResources(deviceResourcesPool.DemandCreate(device)) - { - static_assert(static_cast(std::size(DGSLEffectTraits::VertexShaderBytecode)) == DGSLEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(static_cast(std::size(DGSLEffectTraits::PixelShaderBytecode)) == DGSLEffectTraits::PixelShaderCount, "array/max mismatch"); + Impl(_In_ ID3D11Device* device, _In_opt_ ID3D11PixelShader* pixelShader) + : constants{}, + world{}, + view{}, + projection{}, + lightEnabled{}, + lightDiffuseColor{}, + lightSpecularColor{}, + dirtyFlags(INT_MAX), + vertexColorEnabled(false), + textureEnabled(false), + specularEnabled(false), + alphaDiscardEnabled(false), + weightsPerVertex(0), + mCBMaterial(device), + mCBLight(device), + mCBObject(device), + mCBMisc(device), + mPixelShader(pixelShader), + mDeviceResources(deviceResourcesPool.DemandCreate(device)) + { + static_assert(static_cast(std::size(DGSLEffectTraits::VertexShaderBytecode)) == DGSLEffectTraits::VertexShaderCount, + "array/max mismatch"); + static_assert(static_cast(std::size(DGSLEffectTraits::PixelShaderBytecode)) == DGSLEffectTraits::PixelShaderCount, + "array/max mismatch"); static_assert(MaxDirectionalLights == 4, "Mismatch with DGSL pipline"); } - 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_ ID3D11Device* device, bool enableSkinning) { weightsPerVertex = enableSkinning ? 4 : 0; - const XMMATRIX id = XMMatrixIdentity(); - world = id; - view = id; - projection = id; - constants.material.Diffuse = g_XMOne; - constants.material.Specular = g_XMOne; + const XMMATRIX id = XMMatrixIdentity(); + world = id; + view = id; + projection = id; + constants.material.Diffuse = g_XMOne; + constants.material.Specular = g_XMOne; constants.material.SpecularPower = 16; - constants.object.UvTransform4x4 = id; + constants.object.UvTransform4x4 = id; for (int i = 0; i < MaxDirectionalLights; ++i) { - lightEnabled[i] = (i == 0); - lightDiffuseColor[i] = g_XMZero; + lightEnabled[i] = (i == 0); + lightDiffuseColor[i] = g_XMZero; lightSpecularColor[i] = g_XMOne; - constants.light.LightDirection[i] = g_XMNegIdentityR1; - constants.light.LightColor[i] = lightEnabled[i] ? lightDiffuseColor[i] : g_XMZero; + constants.light.LightDirection[i] = g_XMNegIdentityR1; + constants.light.LightColor[i] = lightEnabled[i] ? lightDiffuseColor[i] : g_XMZero; constants.light.LightSpecularIntensity[i] = lightEnabled[i] ? lightSpecularColor[i] : g_XMZero; } @@ -300,7 +296,7 @@ class DGSLEffect::Impl : public AlignedNew XMMATRIX view; XMMATRIX projection; - bool lightEnabled[MaxDirectionalLights]; + bool lightEnabled[MaxDirectionalLights]; XMVECTOR lightDiffuseColor[MaxDirectionalLights]; XMVECTOR lightSpecularColor[MaxDirectionalLights]; @@ -312,15 +308,15 @@ class DGSLEffect::Impl : public AlignedNew bool textureEnabled; bool specularEnabled; bool alphaDiscardEnabled; - int weightsPerVertex; + int weightsPerVertex; private: - ConstantBuffer mCBMaterial; - ConstantBuffer mCBLight; - ConstantBuffer mCBObject; - ConstantBuffer mCBMisc; - ConstantBuffer mCBBone; - ComPtr mPixelShader; + ConstantBuffer mCBMaterial; + ConstantBuffer mCBLight; + ConstantBuffer mCBObject; + ConstantBuffer mCBMisc; + ConstantBuffer mCBBone; + ComPtr mPixelShader; int GetCurrentVSPermutation() const noexcept; int GetCurrentPSPermutation() const noexcept; @@ -331,8 +327,8 @@ class DGSLEffect::Impl : public AlignedNew public: DeviceResources(_In_ ID3D11Device* device) noexcept : EffectDeviceResources(device), - mVertexShaders{}, - mPixelShaders{} + mVertexShaders{}, + mPixelShaders{} {} // Gets or lazily creates the vertex shader. @@ -354,10 +350,9 @@ class DGSLEffect::Impl : public AlignedNew // Gets or lazily creates the default texture ID3D11ShaderResourceView* GetDefaultTexture() { return EffectDeviceResources::GetDefaultTexture(); } - private: ComPtr mVertexShaders[DGSLEffectTraits::VertexShaderCount]; - ComPtr mPixelShaders[DGSLEffectTraits::PixelShaderCount]; + ComPtr mPixelShaders[DGSLEffectTraits::PixelShaderCount]; }; // Per-device resources. @@ -366,17 +361,15 @@ class DGSLEffect::Impl : public AlignedNew static SharedResourcePool deviceResourcesPool; }; - // Global pool of per-device DGSLEffect resources. SharedResourcePool DGSLEffect::Impl::deviceResourcesPool; - void DGSLEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { assert(deviceContext != nullptr); auto vertexShader = mDeviceResources->GetVertexShader(GetCurrentVSPermutation()); - auto pixelShader = mPixelShader.Get(); + auto pixelShader = mPixelShader.Get(); if (!pixelShader) { pixelShader = mDeviceResources->GetPixelShader(GetCurrentPSPermutation()); @@ -389,7 +382,7 @@ void DGSLEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) if (dirtyFlags & EffectDirtyFlags::WorldViewProj) { constants.object.LocalToWorld4x4 = XMMatrixTranspose(world); - constants.object.WorldToView4x4 = XMMatrixTranspose(view); + constants.object.WorldToView4x4 = XMMatrixTranspose(view); const XMMATRIX worldView = XMMatrixMultiply(world, view); @@ -429,7 +422,7 @@ void DGSLEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) void* grfxMemoryObject; mCBObject.SetData(deviceContext, constants.object, &grfxMemoryObject); - void *grfxMemoryMisc; + void* grfxMemoryMisc; mCBMisc.SetData(deviceContext, constants.misc, &grfxMemoryMisc); ComPtr deviceContextX; @@ -497,22 +490,15 @@ void DGSLEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) dirtyFlags &= ~EffectDirtyFlags::ConstantBufferBones; } - ID3D11Buffer* buffers[5] = - { - mCBMaterial.GetBuffer(), mCBLight.GetBuffer(), mCBObject.GetBuffer(), - mCBMisc.GetBuffer(), mCBBone.GetBuffer() - }; + ID3D11Buffer* buffers[5] + = { mCBMaterial.GetBuffer(), mCBLight.GetBuffer(), mCBObject.GetBuffer(), mCBMisc.GetBuffer(), mCBBone.GetBuffer() }; deviceContext->VSSetConstantBuffers(0, 5, buffers); deviceContext->PSSetConstantBuffers(0, 4, buffers); } else { - ID3D11Buffer* buffers[5] = - { - mCBMaterial.GetBuffer(), mCBLight.GetBuffer(), mCBObject.GetBuffer(), - mCBMisc.GetBuffer(), nullptr - }; + ID3D11Buffer* buffers[5] = { mCBMaterial.GetBuffer(), mCBLight.GetBuffer(), mCBObject.GetBuffer(), mCBMisc.GetBuffer(), nullptr }; deviceContext->VSSetConstantBuffers(0, 5, buffers); deviceContext->PSSetConstantBuffers(0, 4, buffers); @@ -522,17 +508,14 @@ void DGSLEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) // Set the textures if (textureEnabled) { - ID3D11ShaderResourceView* txt[MaxTextures] = - { - textures[0].Get(), + ID3D11ShaderResourceView* txt[MaxTextures] = { textures[0].Get(), textures[1].Get(), textures[2].Get(), textures[3].Get(), textures[4].Get(), textures[5].Get(), textures[6].Get(), - textures[7].Get() - }; + textures[7].Get() }; deviceContext->PSSetShaderResources(0, MaxTextures, txt); } else @@ -542,7 +525,6 @@ void DGSLEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) } } - void DGSLEffect::Impl::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) noexcept { assert(pShaderByteCode != nullptr && pByteCodeLength != nullptr); @@ -551,12 +533,11 @@ void DGSLEffect::Impl::GetVertexShaderBytecode(_Out_ void const** pShaderByteCod assert(permutation < DGSLEffectTraits::VertexShaderCount); _Analysis_assume_(permutation < DGSLEffectTraits::VertexShaderCount); - auto shader = DGSLEffectTraits::VertexShaderBytecode[permutation]; + auto shader = DGSLEffectTraits::VertexShaderBytecode[permutation]; *pShaderByteCode = shader.code; *pByteCodeLength = shader.length; } - int DGSLEffect::Impl::GetCurrentVSPermutation() const noexcept { int permutation = (vertexColorEnabled) ? 1 : 0; @@ -579,7 +560,6 @@ int DGSLEffect::Impl::GetCurrentVSPermutation() const noexcept return permutation; } - int DGSLEffect::Impl::GetCurrentPSPermutation() const noexcept { int permutation = 0; @@ -598,8 +578,6 @@ int DGSLEffect::Impl::GetCurrentPSPermutation() const noexcept return permutation; } - - //-------------------------------------------------------------------------------------- // DGSLEffect //-------------------------------------------------------------------------------------- @@ -609,10 +587,9 @@ DGSLEffect::DGSLEffect(_In_ ID3D11Device* device, _In_opt_ ID3D11PixelShader* pi pImpl->Initialize(device, skinningEnabled); } -DGSLEffect::DGSLEffect(DGSLEffect&&) noexcept = default; -DGSLEffect& DGSLEffect::operator= (DGSLEffect&&) noexcept = default; -DGSLEffect::~DGSLEffect() = default; - +DGSLEffect::DGSLEffect(DGSLEffect&&) noexcept = default; +DGSLEffect& DGSLEffect::operator=(DGSLEffect&&) noexcept = default; +DGSLEffect::~DGSLEffect() = default; // IEffect methods. void DGSLEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) @@ -620,13 +597,11 @@ void DGSLEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void DGSLEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV DGSLEffect::SetWorld(FXMMATRIX value) { @@ -635,7 +610,6 @@ void XM_CALLCONV DGSLEffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose; } - void XM_CALLCONV DGSLEffect::SetView(FXMMATRIX value) { pImpl->view = value; @@ -643,7 +617,6 @@ void XM_CALLCONV DGSLEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition; } - void XM_CALLCONV DGSLEffect::SetProjection(FXMMATRIX value) { pImpl->projection = value; @@ -651,17 +624,15 @@ void XM_CALLCONV DGSLEffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV DGSLEffect::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { - pImpl->world = world; - pImpl->view = view; + pImpl->world = world; + pImpl->view = view; pImpl->projection = projection; pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose | EffectDirtyFlags::EyePosition; } - // Material settings. void XM_CALLCONV DGSLEffect::SetAmbientColor(FXMVECTOR value) { @@ -670,7 +641,6 @@ void XM_CALLCONV DGSLEffect::SetAmbientColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - void XM_CALLCONV DGSLEffect::SetDiffuseColor(FXMVECTOR value) { pImpl->constants.material.Diffuse = XMVectorSelect(pImpl->constants.material.Diffuse, value, g_XMSelect1110); @@ -678,7 +648,6 @@ void XM_CALLCONV DGSLEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - void XM_CALLCONV DGSLEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->constants.material.Emissive = value; @@ -686,35 +655,31 @@ void XM_CALLCONV DGSLEffect::SetEmissiveColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - void XM_CALLCONV DGSLEffect::SetSpecularColor(FXMVECTOR value) { - pImpl->specularEnabled = true; + pImpl->specularEnabled = true; pImpl->constants.material.Specular = value; pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - void DGSLEffect::SetSpecularPower(float value) { - pImpl->specularEnabled = true; + pImpl->specularEnabled = true; pImpl->constants.material.SpecularPower = value; pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - void DGSLEffect::DisableSpecular() { - pImpl->specularEnabled = false; - pImpl->constants.material.Specular = g_XMZero; + pImpl->specularEnabled = false; + pImpl->constants.material.Specular = g_XMZero; pImpl->constants.material.SpecularPower = 1.f; pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - void DGSLEffect::SetAlpha(float value) { // Set w to new value, but preserve existing xyz (diffuse color). @@ -723,7 +688,6 @@ void DGSLEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - void XM_CALLCONV DGSLEffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->constants.material.Diffuse = value; @@ -731,7 +695,6 @@ void XM_CALLCONV DGSLEffect::SetColorAndAlpha(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMaterial; } - // Additional settings. void XM_CALLCONV DGSLEffect::SetUVTransform(FXMMATRIX value) { @@ -740,16 +703,14 @@ void XM_CALLCONV DGSLEffect::SetUVTransform(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferObject; } - void DGSLEffect::SetViewport(float width, float height) { - pImpl->constants.misc.ViewportWidth = width; + pImpl->constants.misc.ViewportWidth = width; pImpl->constants.misc.ViewportHeight = height; pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMisc; } - void DGSLEffect::SetTime(float time) { pImpl->constants.misc.Time = time; @@ -757,13 +718,11 @@ void DGSLEffect::SetTime(float time) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferMisc; } - void DGSLEffect::SetAlphaDiscardEnable(bool value) { pImpl->alphaDiscardEnabled = value; } - // Light settings. void DGSLEffect::SetLightingEnabled(bool value) { @@ -780,13 +739,11 @@ void DGSLEffect::SetLightingEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferLight; } - void DGSLEffect::SetPerPixelLighting(bool) { // Unsupported interface method. } - void XM_CALLCONV DGSLEffect::SetAmbientLightColor(FXMVECTOR value) { pImpl->constants.light.Ambient = value; @@ -794,7 +751,6 @@ void XM_CALLCONV DGSLEffect::SetAmbientLightColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferLight; } - void DGSLEffect::SetLightEnabled(int whichLight, bool value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) @@ -810,19 +766,17 @@ void DGSLEffect::SetLightEnabled(int whichLight, bool value) if (whichLight >= static_cast(pImpl->constants.light.ActiveLights)) pImpl->constants.light.ActiveLights = static_cast(whichLight + 1); - pImpl->constants.light.LightColor[whichLight] = pImpl->lightDiffuseColor[whichLight]; + pImpl->constants.light.LightColor[whichLight] = pImpl->lightDiffuseColor[whichLight]; pImpl->constants.light.LightSpecularIntensity[whichLight] = pImpl->lightSpecularColor[whichLight]; } else { - pImpl->constants.light.LightColor[whichLight] = - pImpl->constants.light.LightSpecularIntensity[whichLight] = g_XMZero; + pImpl->constants.light.LightColor[whichLight] = pImpl->constants.light.LightSpecularIntensity[whichLight] = g_XMZero; } pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferLight; } - void XM_CALLCONV DGSLEffect::SetLightDirection(int whichLight, FXMVECTOR value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) @@ -834,7 +788,6 @@ void XM_CALLCONV DGSLEffect::SetLightDirection(int whichLight, FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBufferLight; } - void XM_CALLCONV DGSLEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) @@ -850,7 +803,6 @@ void XM_CALLCONV DGSLEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR valu } } - void XM_CALLCONV DGSLEffect::SetLightSpecularColor(int whichLight, FXMVECTOR value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) @@ -866,27 +818,23 @@ void XM_CALLCONV DGSLEffect::SetLightSpecularColor(int whichLight, FXMVECTOR val } } - void DGSLEffect::EnableDefaultLighting() { EffectLights::EnableDefaultLighting(this); } - // Vertex color setting. void DGSLEffect::SetVertexColorEnabled(bool value) { pImpl->vertexColorEnabled = value; } - // Texture settings. void DGSLEffect::SetTextureEnabled(bool value) { pImpl->textureEnabled = value; } - void DGSLEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->textures[0] = value; @@ -900,20 +848,16 @@ void DGSLEffect::SetTexture(int whichTexture, _In_opt_ ID3D11ShaderResourceView* pImpl->textures[whichTexture] = value; } - //-------------------------------------------------------------------------------------- // SkinnedDGSLEffect //-------------------------------------------------------------------------------------- -SkinnedDGSLEffect::~SkinnedDGSLEffect() -{} +SkinnedDGSLEffect::~SkinnedDGSLEffect() {} // Animation settings. void SkinnedDGSLEffect::SetWeightsPerVertex(int value) { - if ((value != 1) && - (value != 2) && - (value != 4)) + if ((value != 1) && (value != 2) && (value != 4)) { throw std::invalid_argument("WeightsPerVertex must be 1, 2, or 4"); } @@ -921,7 +865,6 @@ void SkinnedDGSLEffect::SetWeightsPerVertex(int value) pImpl->weightsPerVertex = value; } - void SkinnedDGSLEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (count > MaxBones) @@ -931,22 +874,21 @@ void SkinnedDGSLEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* valu 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 SkinnedDGSLEffect::ResetBoneTransforms() { auto boneConstant = pImpl->constants.bones.Bones; diff --git a/Src/DGSLEffectFactory.cpp b/Src/DGSLEffectFactory.cpp index cead24b5..231f8380 100644 --- a/Src/DGSLEffectFactory.cpp +++ b/Src/DGSLEffectFactory.cpp @@ -22,7 +22,9 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; -static_assert(DGSLEffect::MaxTextures == DGSLEffectFactory::DGSLEffectInfo::BaseTextureOffset + _countof(DGSLEffectFactory::DGSLEffectInfo::textures), "DGSL supports 8 textures"); +static_assert(DGSLEffect::MaxTextures + == DGSLEffectFactory::DGSLEffectInfo::BaseTextureOffset + _countof(DGSLEffectFactory::DGSLEffectInfo::textures), + "DGSL supports 8 textures"); // Internal DGSLEffectFactory implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing DGSLEffectFactory instances. @@ -31,23 +33,27 @@ class DGSLEffectFactory::Impl public: explicit Impl(_In_ ID3D11Device* device) : mPath{}, - mDevice(device), - mSharing(true), - mForceSRGB(false) + mDevice(device), + mSharing(true), + mForceSRGB(false) { if (!device) throw std::invalid_argument("Direct3D device is null"); } - 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(_In_ DGSLEffectFactory* factory, _In_ const IEffectFactory::EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); - std::shared_ptr CreateDGSLEffect(_In_ DGSLEffectFactory* factory, _In_ const DGSLEffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); - void CreateTexture(_In_z_ const wchar_t* texture, _In_opt_ ID3D11DeviceContext* deviceContext, _Outptr_ ID3D11ShaderResourceView** textureView); + std::shared_ptr + CreateEffect(_In_ DGSLEffectFactory* factory, _In_ const IEffectFactory::EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); + std::shared_ptr + CreateDGSLEffect(_In_ DGSLEffectFactory* factory, _In_ const DGSLEffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); + void CreateTexture(_In_z_ const wchar_t* texture, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView); void CreatePixelShader(_In_z_ const wchar_t* shader, _Outptr_ ID3D11PixelShader** pixelShader); void ReleaseCache(); @@ -62,9 +68,9 @@ class DGSLEffectFactory::Impl bool mForceSRGB; private: - using EffectCache = std::map< std::wstring, std::shared_ptr >; - using TextureCache = std::map< std::wstring, ComPtr >; - using ShaderCache = std::map< std::wstring, ComPtr >; + using EffectCache = std::map>; + using TextureCache = std::map>; + using ShaderCache = std::map>; EffectCache mEffectCache; EffectCache mEffectCacheSkinning; @@ -74,13 +80,12 @@ class DGSLEffectFactory::Impl std::mutex mutex; }; - // Global instance pool. SharedResourcePool DGSLEffectFactory::Impl::instancePool; - -_Use_decl_annotations_ -std::shared_ptr DGSLEffectFactory::Impl::CreateEffect(DGSLEffectFactory* factory, const DGSLEffectFactory::EffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr DGSLEffectFactory::Impl::CreateEffect(DGSLEffectFactory* factory, + const DGSLEffectFactory::EffectInfo& info, + ID3D11DeviceContext* deviceContext) { if (info.enableDualTexture) { @@ -159,7 +164,7 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateEffect(DGSLEffectFactory if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); if (info.enableSkinning) { mEffectCacheSkinning.insert(v); @@ -173,9 +178,9 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateEffect(DGSLEffectFactory return std::move(effect); } - -_Use_decl_annotations_ -std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFactory* factory, const DGSLEffectFactory::DGSLEffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFactory* factory, + const DGSLEffectFactory::DGSLEffectInfo& info, + ID3D11DeviceContext* deviceContext) { if (mSharing && info.name && *info.name) { @@ -199,7 +204,7 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFac std::shared_ptr effect; - bool lighting = true; + bool lighting = true; bool allowSpecular = true; if (!info.pixelShader || !*info.pixelShader) @@ -216,7 +221,7 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFac else { wchar_t root[MAX_PATH] = {}; - auto last = wcsrchr(info.pixelShader, '_'); + auto last = wcsrchr(info.pixelShader, '_'); if (last) { wcscpy_s(root, last + 1); @@ -279,8 +284,7 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFac effect->SetAlphaDiscardEnable(true); - if (allowSpecular - && (info.specularColor.x != 0 || info.specularColor.y != 0 || info.specularColor.z != 0)) + if (allowSpecular && (info.specularColor.x != 0 || info.specularColor.y != 0 || info.specularColor.z != 0)) { color = XMLoadFloat3(&info.specularColor); effect->SetSpecularColor(color); @@ -353,7 +357,7 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFac if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); if (info.enableSkinning) { mEffectCacheSkinning.insert(v); @@ -367,9 +371,8 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFac return std::move(effect); } - -_Use_decl_annotations_ -void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { if (!name || !textureView) throw std::invalid_argument("name and textureView parameters can't be null"); @@ -400,7 +403,8 @@ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCon if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: DGSLEffectFactory could not find texture file '%ls'\n", name); - throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "DGSLEffectFactory::CreateTexture"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), + "DGSLEffectFactory::CreateTexture"); } } @@ -410,43 +414,59 @@ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCon if (isdds) { - HRESULT hr = CreateDDSTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateDDSTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, + nullptr, + textureView); 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("DGSLEffectFactory::CreateDDSTextureFromFile"); } } - #if !defined(_XBOX_ONE) || !defined(_TITLE) +#if !defined(_XBOX_ONE) || !defined(_TITLE) else if (deviceContext) { std::lock_guard lock(mutex); - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), deviceContext, fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + deviceContext, + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("DGSLEffectFactory::CreateWICTextureFromFile"); } } - #endif +#endif else { - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("DGSLEffectFactory::CreateWICTextureFromFile"); } } @@ -454,15 +474,13 @@ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCon if (mSharing && *name && it == mTextureCache.end()) { std::lock_guard lock(mutex); - TextureCache::value_type v(name, *textureView); + TextureCache::value_type v(name, *textureView); mTextureCache.insert(v); } } } - -_Use_decl_annotations_ -void DGSLEffectFactory::Impl::CreatePixelShader(const wchar_t* name, ID3D11PixelShader** pixelShader) +_Use_decl_annotations_ void DGSLEffectFactory::Impl::CreatePixelShader(const wchar_t* name, ID3D11PixelShader** pixelShader) { if (!name || !pixelShader) throw std::invalid_argument("name and pixelShader parameters can't be null"); @@ -489,22 +507,21 @@ void DGSLEffectFactory::Impl::CreatePixelShader(const wchar_t* name, ID3D11Pixel if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: DGSLEffectFactory could not find shader file '%ls'\n", name); - throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "DGSLEffectFactory::CreatePixelShader"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), + "DGSLEffectFactory::CreatePixelShader"); } } - size_t dataSize = 0; + size_t dataSize = 0; std::unique_ptr data; - HRESULT hr = BinaryReader::ReadEntireFile(fullName, data, &dataSize); + HRESULT hr = BinaryReader::ReadEntireFile(fullName, data, &dataSize); if (FAILED(hr)) { - DebugTrace("ERROR: CreatePixelShader failed (%08X) to load shader file '%ls'\n", - static_cast(hr), fullName); + DebugTrace("ERROR: CreatePixelShader failed (%08X) to load shader file '%ls'\n", static_cast(hr), fullName); throw std::runtime_error("DGSLEffectFactory::CreatePixelShader"); } - ThrowIfFailed( - mDevice->CreatePixelShader(data.get(), dataSize, nullptr, pixelShader)); + ThrowIfFailed(mDevice->CreatePixelShader(data.get(), dataSize, nullptr, pixelShader)); assert(pixelShader != nullptr && *pixelShader != nullptr); _Analysis_assume_(pixelShader != nullptr && *pixelShader != nullptr); @@ -512,13 +529,12 @@ void DGSLEffectFactory::Impl::CreatePixelShader(const wchar_t* name, ID3D11Pixel if (mSharing && *name && it == mShaderCache.end()) { std::lock_guard lock(mutex); - ShaderCache::value_type v(name, *pixelShader); + ShaderCache::value_type v(name, *pixelShader); mShaderCache.insert(v); } } } - void DGSLEffectFactory::Impl::ReleaseCache() { std::lock_guard lock(mutex); @@ -528,8 +544,6 @@ void DGSLEffectFactory::Impl::ReleaseCache() mShaderCache.clear(); } - - //-------------------------------------------------------------------------------------- // DGSLEffectFactory //-------------------------------------------------------------------------------------- @@ -538,41 +552,34 @@ DGSLEffectFactory::DGSLEffectFactory(_In_ ID3D11Device* device) : pImpl(Impl::instancePool.DemandCreate(device)) {} - -DGSLEffectFactory::DGSLEffectFactory(DGSLEffectFactory&&) noexcept = default; -DGSLEffectFactory& DGSLEffectFactory::operator= (DGSLEffectFactory&&) noexcept = default; -DGSLEffectFactory::~DGSLEffectFactory() = default; - +DGSLEffectFactory::DGSLEffectFactory(DGSLEffectFactory&&) noexcept = default; +DGSLEffectFactory& DGSLEffectFactory::operator=(DGSLEffectFactory&&) noexcept = default; +DGSLEffectFactory::~DGSLEffectFactory() = default; // IEffectFactory methods -_Use_decl_annotations_ -std::shared_ptr DGSLEffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr DGSLEffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) { return pImpl->CreateEffect(this, info, deviceContext); } -_Use_decl_annotations_ -void DGSLEffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +DGSLEffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { return pImpl->CreateTexture(name, deviceContext, textureView); } - // DGSL methods. -_Use_decl_annotations_ -std::shared_ptr DGSLEffectFactory::CreateDGSLEffect(const DGSLEffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr DGSLEffectFactory::CreateDGSLEffect(const DGSLEffectInfo& info, + ID3D11DeviceContext* deviceContext) { return pImpl->CreateDGSLEffect(this, info, deviceContext); } - -_Use_decl_annotations_ -void DGSLEffectFactory::CreatePixelShader(const wchar_t* shader, ID3D11PixelShader** pixelShader) +_Use_decl_annotations_ void DGSLEffectFactory::CreatePixelShader(const wchar_t* shader, ID3D11PixelShader** pixelShader) { pImpl->CreatePixelShader(shader, pixelShader); } - // Settings void DGSLEffectFactory::ReleaseCache() { @@ -600,7 +607,7 @@ void DGSLEffectFactory::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; } } diff --git a/Src/DebugEffect.cpp b/Src/DebugEffect.cpp index 1b6fb1cc..845ccdbc 100644 --- a/Src/DebugEffect.cpp +++ b/Src/DebugEffect.cpp @@ -32,11 +32,11 @@ namespace { 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; }; -} +} // namespace // Internal DebugEffect implementation class. class DebugEffect::Impl : public EffectBase @@ -44,15 +44,15 @@ class DebugEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; - bool vertexColorEnabled; - bool biasedVertexNormals; - bool instancing; + bool vertexColorEnabled; + bool biasedVertexNormals; + bool instancing; DebugEffect::Mode debugMode; int GetCurrentShaderPermutation() const noexcept; @@ -60,7 +60,6 @@ class DebugEffect::Impl : public EffectBase void Apply(_In_ ID3D11DeviceContext* deviceContext); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -100,120 +99,112 @@ namespace #include "DebugEffect_PSRGBTangents.inc" #include "DebugEffect_PSRGBBiTangents.inc" #endif -} - +} // namespace template<> -const ShaderBytecode 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 ShaderBytecode 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 ShaderBytecode EffectBase::PixelShaderBytecode[] = -{ - { DebugEffect_PSHemiAmbient, sizeof(DebugEffect_PSHemiAmbient) }, - { DebugEffect_PSRGBNormals, sizeof(DebugEffect_PSRGBNormals) }, - { DebugEffect_PSRGBTangents, sizeof(DebugEffect_PSRGBTangents) }, - { DebugEffect_PSRGBBiTangents, sizeof(DebugEffect_PSRGBBiTangents) }, +const ShaderBytecode 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 @@ -221,27 +212,31 @@ const int EffectBase::PixelShaderIndices[] = template<> SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - // Constructor. DebugEffect::Impl::Impl(_In_ ID3D11Device* device) : EffectBase(device), - vertexColorEnabled(false), - biasedVertexNormals(false), - instancing(false), - debugMode(DebugEffect::Mode_Default) + vertexColorEnabled(false), + biasedVertexNormals(false), + instancing(false), + debugMode(DebugEffect::Mode_Default) { - 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; } - int DebugEffect::Impl::GetCurrentShaderPermutation() const noexcept { int permutation = static_cast(debugMode); @@ -267,7 +262,6 @@ int DebugEffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void DebugEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -275,28 +269,20 @@ void DebugEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) // 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); // Set shaders and constant buffers. ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - // Public constructor. DebugEffect::DebugEffect(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext) @@ -304,13 +290,11 @@ void DebugEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void DebugEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV DebugEffect::SetWorld(FXMMATRIX value) { @@ -319,7 +303,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; @@ -327,7 +310,6 @@ void XM_CALLCONV DebugEffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV DebugEffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -335,17 +317,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 DebugEffect::SetMode(Mode debugMode) { @@ -375,21 +355,18 @@ void DebugEffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Vertex color setting. void DebugEffect::SetVertexColorEnabled(bool value) { pImpl->vertexColorEnabled = value; } - // Normal compression settings. void DebugEffect::SetBiasedVertexNormals(bool value) { pImpl->biasedVertexNormals = value; } - // Instancing settings. void DebugEffect::SetInstancingEnabled(bool value) { 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/DirectXHelpers.cpp b/Src/DirectXHelpers.cpp index d041f5e1..97c47ea3 100644 --- a/Src/DirectXHelpers.cpp +++ b/Src/DirectXHelpers.cpp @@ -12,16 +12,13 @@ #include "Effects.h" #include "PlatformHelpers.h" - using namespace DirectX; -_Use_decl_annotations_ -HRESULT DirectX::CreateInputLayoutFromEffect( - ID3D11Device* device, - IEffect* effect, - const D3D11_INPUT_ELEMENT_DESC* desc, - size_t count, - ID3D11InputLayout** pInputLayout) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateInputLayoutFromEffect(ID3D11Device* device, + IEffect* effect, + const D3D11_INPUT_ELEMENT_DESC* desc, + size_t count, + ID3D11InputLayout** pInputLayout) noexcept { if (!pInputLayout) return E_INVALIDARG; @@ -32,7 +29,7 @@ HRESULT DirectX::CreateInputLayoutFromEffect( return E_INVALIDARG; void const* shaderByteCode; - size_t byteCodeLength; + size_t byteCodeLength; try { @@ -47,8 +44,5 @@ HRESULT DirectX::CreateInputLayoutFromEffect( return E_FAIL; } - return device->CreateInputLayout( - desc, static_cast(count), - shaderByteCode, byteCodeLength, - pInputLayout); + return device->CreateInputLayout(desc, static_cast(count), shaderByteCode, byteCodeLength, pInputLayout); } diff --git a/Src/DualPostProcess.cpp b/Src/DualPostProcess.cpp index 3f3e3913..bba7ba7e 100644 --- a/Src/DualPostProcess.cpp +++ b/Src/DualPostProcess.cpp @@ -26,7 +26,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 @@ -36,8 +36,7 @@ namespace }; static_assert((sizeof(PostProcessConstants) % 16) == 0, "CB size not padded correctly"); -} - +} // namespace #pragma region Shaders // Include the precompiled shader code. @@ -58,13 +57,12 @@ namespace struct ShaderBytecode { void const* code; - size_t length; + size_t length; }; - const ShaderBytecode pixelShaders[] = - { - { PostProcess_PSMerge, sizeof(PostProcess_PSMerge) }, - { PostProcess_PSBloomCombine, sizeof(PostProcess_PSBloomCombine) }, + const ShaderBytecode pixelShaders[] = { + { PostProcess_PSMerge, sizeof(PostProcess_PSMerge) }, + { PostProcess_PSBloomCombine, sizeof(PostProcess_PSBloomCombine) }, }; static_assert(static_cast(std::size(pixelShaders)) == DualPostProcess::Effect_Max, "array/max mismatch"); @@ -75,10 +73,10 @@ namespace public: DeviceResources(_In_ ID3D11Device* device) : stateObjects(device), - mDevice(device), - mVertexShader{}, - mPixelShaders{}, - mMutex{} + mDevice(device), + mVertexShader{}, + mPixelShaders{}, + mMutex{} { if (!device) { @@ -91,16 +89,18 @@ namespace } } - DeviceResources(const DeviceResources&) = delete; + DeviceResources(const DeviceResources&) = delete; DeviceResources& operator=(const DeviceResources&) = delete; - DeviceResources(DeviceResources&&) = delete; + DeviceResources(DeviceResources&&) = delete; DeviceResources& operator=(DeviceResources&&) = delete; // Gets or lazily creates the vertex shader. ID3D11VertexShader* GetVertexShader() { - return DemandCreate(mVertexShader, mMutex, [&](ID3D11VertexShader** pResult) -> HRESULT + return DemandCreate(mVertexShader, + mMutex, + [&](ID3D11VertexShader** pResult) -> HRESULT { HRESULT hr = mDevice->CreateVertexShader(PostProcess_VSQuad, sizeof(PostProcess_VSQuad), nullptr, pResult); @@ -117,9 +117,12 @@ namespace assert(shaderIndex < DualPostProcess::Effect_Max); _Analysis_assume_(shaderIndex < DualPostProcess::Effect_Max); - return DemandCreate(mPixelShaders[shaderIndex], mMutex, [&](ID3D11PixelShader** pResult) -> HRESULT + return DemandCreate(mPixelShaders[shaderIndex], + mMutex, + [&](ID3D11PixelShader** pResult) -> HRESULT { - HRESULT hr = mDevice->CreatePixelShader(pixelShaders[shaderIndex].code, pixelShaders[shaderIndex].length, nullptr, pResult); + HRESULT hr + = mDevice->CreatePixelShader(pixelShaders[shaderIndex].code, pixelShaders[shaderIndex].length, nullptr, pResult); if (SUCCEEDED(hr)) SetDebugObjectName(*pResult, "DualPostProcess"); @@ -128,27 +131,26 @@ namespace }); } - CommonStates stateObjects; + CommonStates stateObjects; protected: - ComPtr mDevice; - ComPtr mVertexShader; - ComPtr mPixelShaders[DualPostProcess::Effect_Max]; - std::mutex mMutex; + ComPtr mDevice; + ComPtr mVertexShader; + ComPtr mPixelShaders[DualPostProcess::Effect_Max]; + std::mutex mMutex; }; -} +} // namespace #pragma endregion - class DualPostProcess::Impl : public AlignedNew { public: explicit Impl(_In_ ID3D11Device* 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 Process(_In_ ID3D11DeviceContext* deviceContext, const std::function& setCustomState); @@ -156,55 +158,50 @@ class DualPostProcess::Impl : public AlignedNew void SetDirtyFlag() noexcept { mDirtyFlags = INT_MAX; } // Fields. - PostProcessConstants constants; - DualPostProcess::Effect fx; - ComPtr texture; - ComPtr texture2; - float mergeWeight1; - float mergeWeight2; - float bloomIntensity; - float bloomBaseIntensity; - float bloomSaturation; - float bloomBaseSaturation; + PostProcessConstants constants; + DualPostProcess::Effect fx; + ComPtr texture; + ComPtr texture2; + float mergeWeight1; + float mergeWeight2; + float bloomIntensity; + float bloomBaseIntensity; + float bloomSaturation; + float bloomBaseSaturation; private: - int mDirtyFlags; + int mDirtyFlags; - ConstantBuffer mConstantBuffer; + ConstantBuffer mConstantBuffer; // Per-device resources. - std::shared_ptr mDeviceResources; + std::shared_ptr mDeviceResources; static SharedResourcePool deviceResourcesPool; }; - // Global pool of per-device DualPostProcess resources. SharedResourcePool DualPostProcess::Impl::deviceResourcesPool; - // Constructor. DualPostProcess::Impl::Impl(_In_ ID3D11Device* device) : constants{}, - fx(DualPostProcess::Merge), - mergeWeight1(0.5f), - mergeWeight2(0.5f), - bloomIntensity(1.25f), - bloomBaseIntensity(1.f), - bloomSaturation(1.f), - bloomBaseSaturation(1.f), - mDirtyFlags(INT_MAX), - mConstantBuffer(device), - mDeviceResources(deviceResourcesPool.DemandCreate(device)) + fx(DualPostProcess::Merge), + mergeWeight1(0.5f), + mergeWeight2(0.5f), + bloomIntensity(1.25f), + bloomBaseIntensity(1.f), + bloomSaturation(1.f), + bloomBaseSaturation(1.f), + mDirtyFlags(INT_MAX), + mConstantBuffer(device), + mDeviceResources(deviceResourcesPool.DemandCreate(device)) { SetDebugObjectName(mConstantBuffer.GetBuffer(), "DualPostProcess"); } - // Sets our state onto the D3D device. -void DualPostProcess::Impl::Process( - _In_ ID3D11DeviceContext* deviceContext, - const std::function& setCustomState) +void DualPostProcess::Impl::Process(_In_ ID3D11DeviceContext* deviceContext, const std::function& setCustomState) { // Set the texture. ID3D11ShaderResourceView* textures[2] = { texture.Get(), texture2.Get() }; @@ -220,7 +217,7 @@ void DualPostProcess::Impl::Process( // Set shaders. auto vertexShader = mDeviceResources->GetVertexShader(); - auto pixelShader = mDeviceResources->GetPixelShader(fx); + auto pixelShader = mDeviceResources->GetPixelShader(fx); deviceContext->VSSetShader(vertexShader, nullptr, 0); deviceContext->PSSetShader(pixelShader, nullptr, 0); @@ -244,13 +241,12 @@ void DualPostProcess::Impl::Process( constants.sampleWeights[2] = XMVectorReplicate(bloomIntensity); break; - default: - break; + default: break; } } #if defined(_XBOX_ONE) && defined(_TITLE) - void *grfxMemory; + void* grfxMemory; mConstantBuffer.SetData(deviceContext, constants, &grfxMemory); ComPtr deviceContextX; @@ -284,27 +280,21 @@ void DualPostProcess::Impl::Process( deviceContext->Draw(3, 0); } - // Public constructor. DualPostProcess::DualPostProcess(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext, - _In_ std::function setCustomState) +void DualPostProcess::Process(_In_ ID3D11DeviceContext* deviceContext, _In_ std::function setCustomState) { pImpl->Process(deviceContext, setCustomState); } - // Shader control. void DualPostProcess::SetEffect(Effect fx) { @@ -315,20 +305,17 @@ void DualPostProcess::SetEffect(Effect fx) pImpl->SetDirtyFlag(); } - // Properties void DualPostProcess::SetSourceTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - void DualPostProcess::SetSourceTexture2(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture2 = value; } - void DualPostProcess::SetMergeParameters(float weight1, float weight2) { pImpl->mergeWeight1 = weight1; @@ -336,12 +323,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 c31c26be..5ba320df 100644 --- a/Src/DualTextureEffect.cpp +++ b/Src/DualTextureEffect.cpp @@ -31,11 +31,11 @@ namespace { 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; }; -} +} // namespace // Internal DualTextureEffect implementation class. class DualTextureEffect::Impl : public EffectBase @@ -43,10 +43,10 @@ class DualTextureEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; bool vertexColorEnabled; @@ -60,7 +60,6 @@ class DualTextureEffect::Impl : public EffectBase void Apply(_In_ ID3D11DeviceContext* deviceContext); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -82,66 +81,65 @@ namespace #include "DualTextureEffect_PSDualTexture.inc" #include "DualTextureEffect_PSDualTextureNoFog.inc" #endif -} - +} // namespace template<> -const ShaderBytecode EffectBase::VertexShaderBytecode[] = -{ - { DualTextureEffect_VSDualTexture, sizeof(DualTextureEffect_VSDualTexture) }, - { DualTextureEffect_VSDualTextureNoFog, sizeof(DualTextureEffect_VSDualTextureNoFog) }, - { DualTextureEffect_VSDualTextureVc, sizeof(DualTextureEffect_VSDualTextureVc) }, +const ShaderBytecode 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 ShaderBytecode EffectBase::PixelShaderBytecode[] = -{ - { DualTextureEffect_PSDualTexture, sizeof(DualTextureEffect_PSDualTexture) }, - { DualTextureEffect_PSDualTextureNoFog, sizeof(DualTextureEffect_PSDualTextureNoFog) }, +const ShaderBytecode 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_ ID3D11Device* device) : EffectBase(device), - vertexColorEnabled(false) + vertexColorEnabled(false) { - 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"); } - int DualTextureEffect::Impl::GetCurrentShaderPermutation() const noexcept { int permutation = 0; @@ -161,7 +159,6 @@ int DualTextureEffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void DualTextureEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -175,8 +172,7 @@ void DualTextureEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) color.SetConstants(dirtyFlags, constants.diffuseColor); // Set the textures. - ID3D11ShaderResourceView* textures[2] = - { + ID3D11ShaderResourceView* textures[2] = { texture.Get(), texture2.Get(), }; @@ -187,17 +183,14 @@ void DualTextureEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - // Public constructor. DualTextureEffect::DualTextureEffect(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext) @@ -205,13 +198,11 @@ void DualTextureEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void DualTextureEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV DualTextureEffect::SetWorld(FXMMATRIX value) { @@ -220,7 +211,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; @@ -228,7 +218,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; @@ -236,17 +225,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) { @@ -255,7 +243,6 @@ void XM_CALLCONV DualTextureEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void DualTextureEffect::SetAlpha(float value) { pImpl->color.alpha = value; @@ -263,16 +250,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::SetFogEnabled(bool value) { @@ -281,7 +266,6 @@ void DualTextureEffect::SetFogEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::FogEnable; } - void DualTextureEffect::SetFogStart(float value) { pImpl->fog.start = value; @@ -289,7 +273,6 @@ void DualTextureEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void DualTextureEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -297,7 +280,6 @@ void DualTextureEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV DualTextureEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -305,21 +287,18 @@ void XM_CALLCONV DualTextureEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Vertex color setting. void DualTextureEffect::SetVertexColorEnabled(bool value) { pImpl->vertexColorEnabled = value; } - // Texture settings. void DualTextureEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - void DualTextureEffect::SetTexture2(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture2 = value; diff --git a/Src/EffectCommon.cpp b/Src/EffectCommon.cpp index efbc4808..9b77fa91 100644 --- a/Src/EffectCommon.cpp +++ b/Src/EffectCommon.cpp @@ -14,7 +14,6 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - // IEffectMatrices default method void XM_CALLCONV IEffectMatrices::SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) { @@ -23,21 +22,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) { @@ -50,16 +46,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) @@ -91,25 +84,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) { @@ -130,9 +120,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)); @@ -158,14 +147,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) { @@ -181,37 +168,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; @@ -220,7 +203,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; } } @@ -229,18 +212,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) { @@ -294,7 +274,7 @@ void EffectLights::SetConstants( if (dirtyFlags & EffectDirtyFlags::MaterialColor) { - XMVECTOR diffuse = diffuseColor; + XMVECTOR diffuse = diffuseColor; const XMVECTOR alphaVector = XMVectorReplicate(alpha); if (lightingEnabled) @@ -317,19 +297,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); @@ -341,23 +316,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); @@ -375,10 +348,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); @@ -400,7 +371,6 @@ int XM_CALLCONV EffectLights::SetLightSpecularColor(int whichLight, FXMVECTOR va #pragma prefast(pop) #endif - // Parameter validation helper. void EffectLights::ValidateLightIndex(int whichLight) { @@ -410,29 +380,25 @@ 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] = - { - { { { 1.0000000f, 0.9607844f, 0.8078432f, 0 } } }, - { { { 0.9647059f, 0.7607844f, 0.4078432f, 0 } } }, - { { { 0.3231373f, 0.3607844f, 0.3937255f, 0 } } }, + 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] = - { - { { { 1.0000000f, 0.9607844f, 0.8078432f, 0 } } }, - { { { 0.0000000f, 0.0000000f, 0.0000000f, 0 } } }, - { { { 0.3231373f, 0.3607844f, 0.3937255f, 0 } } }, + 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 } } }, }; static const XMVECTORF32 defaultAmbient = { { { 0.05333332f, 0.09882354f, 0.1819608f, 0 } } }; @@ -449,11 +415,13 @@ void EffectLights::EnableDefaultLighting(_In_ IEffectLights* effect) } } - // Gets or lazily creates the specified vertex shader permutation. -ID3D11VertexShader* EffectDeviceResources::DemandCreateVertexShader(_Inout_ ComPtr& vertexShader, ShaderBytecode const& bytecode) +ID3D11VertexShader* EffectDeviceResources::DemandCreateVertexShader(_Inout_ ComPtr& vertexShader, + ShaderBytecode const& bytecode) { - return DemandCreate(vertexShader, mMutex, [&](ID3D11VertexShader** pResult) -> HRESULT + return DemandCreate(vertexShader, + mMutex, + [&](ID3D11VertexShader** pResult) -> HRESULT { HRESULT hr = mDevice->CreateVertexShader(bytecode.code, bytecode.length, nullptr, pResult); @@ -464,11 +432,13 @@ ID3D11VertexShader* EffectDeviceResources::DemandCreateVertexShader(_Inout_ ComP }); } - // Gets or lazily creates the specified pixel shader permutation. -ID3D11PixelShader* EffectDeviceResources::DemandCreatePixelShader(_Inout_ ComPtr& pixelShader, ShaderBytecode const& bytecode) +ID3D11PixelShader* EffectDeviceResources::DemandCreatePixelShader(_Inout_ ComPtr& pixelShader, + ShaderBytecode const& bytecode) { - return DemandCreate(pixelShader, mMutex, [&](ID3D11PixelShader** pResult) -> HRESULT + return DemandCreate(pixelShader, + mMutex, + [&](ID3D11PixelShader** pResult) -> HRESULT { HRESULT hr = mDevice->CreatePixelShader(bytecode.code, bytecode.length, nullptr, pResult); @@ -479,11 +449,12 @@ ID3D11PixelShader* EffectDeviceResources::DemandCreatePixelShader(_Inout_ ComPtr }); } - // Gets or lazily creates the default texture ID3D11ShaderResourceView* EffectDeviceResources::GetDefaultTexture() { - return DemandCreate(mDefaultTexture, mMutex, [&](ID3D11ShaderResourceView** pResult) -> HRESULT + return DemandCreate(mDefaultTexture, + mMutex, + [&](ID3D11ShaderResourceView** pResult) -> HRESULT { static const uint32_t s_pixel = 0xffffffff; @@ -491,22 +462,22 @@ ID3D11ShaderResourceView* EffectDeviceResources::GetDefaultTexture() D3D11_TEXTURE2D_DESC desc = {}; desc.Width = desc.Height = desc.MipLevels = desc.ArraySize = 1; - desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.SampleDesc.Count = 1; - desc.Usage = D3D11_USAGE_IMMUTABLE; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_IMMUTABLE; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; ComPtr tex; - HRESULT hr = mDevice->CreateTexture2D(&desc, &initData, tex.GetAddressOf()); + HRESULT hr = mDevice->CreateTexture2D(&desc, &initData, tex.GetAddressOf()); if (SUCCEEDED(hr)) { SetDebugObjectName(tex.Get(), "DirectXTK:Effect"); D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Texture2D.MipLevels = 1; + SRVDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = 1; hr = mDevice->CreateShaderResourceView(tex.Get(), &SRVDesc, pResult); if (SUCCEEDED(hr)) @@ -519,7 +490,9 @@ ID3D11ShaderResourceView* EffectDeviceResources::GetDefaultTexture() ID3D11ShaderResourceView* EffectDeviceResources::GetDefaultNormalTexture() { - return DemandCreate(mDefaultNormalTexture, mMutex, [&](ID3D11ShaderResourceView** pResult) -> HRESULT + return DemandCreate(mDefaultNormalTexture, + mMutex, + [&](ID3D11ShaderResourceView** pResult) -> HRESULT { static const uint16_t s_pixel = 0x7f7f; @@ -527,22 +500,22 @@ ID3D11ShaderResourceView* EffectDeviceResources::GetDefaultNormalTexture() D3D11_TEXTURE2D_DESC desc = {}; desc.Width = desc.Height = desc.MipLevels = desc.ArraySize = 1; - desc.Format = DXGI_FORMAT_R8G8_UNORM; - desc.SampleDesc.Count = 1; - desc.Usage = D3D11_USAGE_IMMUTABLE; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.Format = DXGI_FORMAT_R8G8_UNORM; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_IMMUTABLE; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; ComPtr tex; - HRESULT hr = mDevice->CreateTexture2D(&desc, &initData, tex.GetAddressOf()); + HRESULT hr = mDevice->CreateTexture2D(&desc, &initData, tex.GetAddressOf()); if (SUCCEEDED(hr)) { SetDebugObjectName(tex.Get(), "DirectXTK:Effect"); D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = DXGI_FORMAT_R8G8_UNORM; - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Texture2D.MipLevels = 1; + SRVDesc.Format = DXGI_FORMAT_R8G8_UNORM; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = 1; hr = mDevice->CreateShaderResourceView(tex.Get(), &SRVDesc, pResult); if (SUCCEEDED(hr)) diff --git a/Src/EffectCommon.h b/Src/EffectCommon.h index 77fa13a8..4d0242e3 100644 --- a/Src/EffectCommon.h +++ b/Src/EffectCommon.h @@ -18,28 +18,25 @@ #include "PlatformHelpers.h" #include "SharedResourcePool.h" - // BasicEffect, SkinnedEffect, et al, have many things in common, but also significant // differences (for instance, not all the effects support lighting). This header breaks // 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 { // 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 @@ -54,43 +51,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 { @@ -98,59 +88,50 @@ 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); static void EnableDefaultLighting(_In_ IEffectLights* effect); }; - // Points to a precompiled vertex or pixel shader program. struct ShaderBytecode { void const* code; - size_t length; + size_t length; }; - // Factory for lazily instantiating shaders. BasicEffect supports many different // shader permutations, so we only bother creating the ones that are actually used. class EffectDeviceResources @@ -170,21 +151,22 @@ namespace DirectX } } - ID3D11VertexShader* DemandCreateVertexShader(_Inout_ Microsoft::WRL::ComPtr& vertexShader, ShaderBytecode const& bytecode); - ID3D11PixelShader * DemandCreatePixelShader(_Inout_ Microsoft::WRL::ComPtr & pixelShader, ShaderBytecode const& bytecode); + ID3D11VertexShader* DemandCreateVertexShader(_Inout_ Microsoft::WRL::ComPtr& vertexShader, + ShaderBytecode const& bytecode); + ID3D11PixelShader* DemandCreatePixelShader(_Inout_ Microsoft::WRL::ComPtr& pixelShader, + ShaderBytecode const& bytecode); ID3D11ShaderResourceView* GetDefaultTexture(); ID3D11ShaderResourceView* GetDefaultNormalTexture(); - D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const; + D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const; protected: - Microsoft::WRL::ComPtr mDevice; + Microsoft::WRL::ComPtr mDevice; Microsoft::WRL::ComPtr mDefaultTexture; Microsoft::WRL::ComPtr mDefaultNormalTexture; std::mutex mMutex; }; - // Templated base class provides functionality common to all the built-in effects. template class EffectBase : public AlignedNew @@ -193,30 +175,29 @@ namespace DirectX // Constructor. EffectBase(_In_ ID3D11Device* device) : constants{}, - dirtyFlags(INT_MAX), - mConstantBuffer(device), - mDeviceResources(deviceResourcesPool.DemandCreate(device)) + dirtyFlags(INT_MAX), + mConstantBuffer(device), + mDeviceResources(deviceResourcesPool.DemandCreate(device)) { SetDebugObjectName(mConstantBuffer.GetBuffer(), "Effect"); } - EffectBase(EffectBase&&) = default; - EffectBase& operator= (EffectBase&&) = default; + EffectBase(EffectBase&&) = default; + EffectBase& operator=(EffectBase&&) = default; - EffectBase(EffectBase const&) = delete; - EffectBase& operator= (EffectBase const&) = delete; + EffectBase(EffectBase const&) = delete; + EffectBase& operator=(EffectBase const&) = delete; // Fields. typename Traits::ConstantBufferType constants; EffectMatrices matrices; - EffectFog fog; + EffectFog fog; Microsoft::WRL::ComPtr texture; int dirtyFlags; - // Helper looks up the bytecode for the specified vertex shader permutation. // Client code needs this in order to create matching input layouts. void GetVertexShaderBytecode(int permutation, _Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) noexcept @@ -234,19 +215,18 @@ namespace DirectX *pByteCodeLength = bytecode.length; } - // Helper sets our shaders and constant buffers onto the D3D device. void ApplyShaders(_In_ ID3D11DeviceContext* deviceContext, int permutation) { // Set shaders. auto vertexShader = mDeviceResources->GetVertexShader(permutation); - auto pixelShader = mDeviceResources->GetPixelShader(permutation); + auto pixelShader = mDeviceResources->GetPixelShader(permutation); deviceContext->VSSetShader(vertexShader, nullptr, 0); deviceContext->PSSetShader(pixelShader, nullptr, 0); - #if defined(_XBOX_ONE) && defined(_TITLE) - void *grfxMemory; +#if defined(_XBOX_ONE) && defined(_TITLE) + void* grfxMemory; mConstantBuffer.SetData(deviceContext, constants, &grfxMemory); Microsoft::WRL::ComPtr deviceContextX; @@ -256,8 +236,8 @@ namespace DirectX deviceContextX->VSSetPlacementConstantBuffer(0, buffer, grfxMemory); deviceContextX->PSSetPlacementConstantBuffer(0, buffer, grfxMemory); - #else - // Make sure the constant buffer is up to date. +#else + // Make sure the constant buffer is up to date. if (dirtyFlags & EffectDirtyFlags::ConstantBuffer) { mConstantBuffer.SetData(deviceContext, constants); @@ -270,15 +250,13 @@ namespace DirectX deviceContext->VSSetConstantBuffers(0, 1, &buffer); deviceContext->PSSetConstantBuffers(0, 1, &buffer); - #endif +#endif } - // Helpers ID3D11ShaderResourceView* GetDefaultTexture() { return mDeviceResources->GetDefaultTexture(); } ID3D11ShaderResourceView* GetDefaultNormalTexture() { return mDeviceResources->GetDefaultNormalTexture(); } - D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return mDeviceResources->GetDeviceFeatureLevel(); } - + D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return mDeviceResources->GetDeviceFeatureLevel(); } protected: // Static arrays hold all the precompiled shader permutations. @@ -298,11 +276,10 @@ namespace DirectX public: DeviceResources(_In_ ID3D11Device* device) : EffectDeviceResources(device), - mVertexShaders{}, - mPixelShaders{} + mVertexShaders{}, + mPixelShaders{} {} - // Gets or lazily creates the specified vertex shader permutation. ID3D11VertexShader* GetVertexShader(int permutation) { @@ -315,7 +292,6 @@ namespace DirectX return DemandCreateVertexShader(mVertexShaders[shaderIndex], VertexShaderBytecode[shaderIndex]); } - // Gets or lazily creates the specified pixel shader permutation. ID3D11PixelShader* GetPixelShader(int permutation) { @@ -328,21 +304,19 @@ namespace DirectX return DemandCreatePixelShader(mPixelShaders[shaderIndex], PixelShaderBytecode[shaderIndex]); } - // Helpers ID3D11ShaderResourceView* GetDefaultTexture() { return EffectDeviceResources::GetDefaultTexture(); } ID3D11ShaderResourceView* GetDefaultNormalTexture() { return EffectDeviceResources::GetDefaultNormalTexture(); } - D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return EffectDeviceResources::GetDeviceFeatureLevel(); } + D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return EffectDeviceResources::GetDeviceFeatureLevel(); } private: Microsoft::WRL::ComPtr mVertexShaders[Traits::VertexShaderCount]; - Microsoft::WRL::ComPtr mPixelShaders[Traits::PixelShaderCount]; + Microsoft::WRL::ComPtr mPixelShaders[Traits::PixelShaderCount]; }; - // Per-device resources. std::shared_ptr mDeviceResources; static SharedResourcePool deviceResourcesPool; }; -} +} // namespace DirectX diff --git a/Src/EffectFactory.cpp b/Src/EffectFactory.cpp index 0f667b81..0c43332e 100644 --- a/Src/EffectFactory.cpp +++ b/Src/EffectFactory.cpp @@ -54,7 +54,7 @@ namespace effect->SetBiasedVertexNormals(true); } } -} +} // namespace // Internal EffectFactory implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing EffectFactory instances. @@ -63,23 +63,26 @@ class EffectFactory::Impl public: explicit Impl(_In_ ID3D11Device* device) : mPath{}, - mDevice(device), - mSharing(true), - mUseNormalMapEffect(true), - mForceSRGB(false) + mDevice(device), + mSharing(true), + mUseNormalMapEffect(true), + mForceSRGB(false) { if (!device) throw std::invalid_argument("Direct3D device is null"); } - 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(_In_ IEffectFactory* factory, _In_ const IEffectFactory::EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); - void CreateTexture(_In_z_ const wchar_t* texture, _In_opt_ ID3D11DeviceContext* deviceContext, _Outptr_ ID3D11ShaderResourceView** textureView); + std::shared_ptr + CreateEffect(_In_ IEffectFactory* factory, _In_ const IEffectFactory::EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); + void CreateTexture(_In_z_ const wchar_t* texture, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView); void ReleaseCache(); @@ -94,8 +97,8 @@ class EffectFactory::Impl bool mForceSRGB; private: - using EffectCache = std::map< std::wstring, std::shared_ptr >; - using TextureCache = std::map< std::wstring, ComPtr >; + using EffectCache = std::map>; + using TextureCache = std::map>; EffectCache mEffectCache; EffectCache mEffectCacheSkinning; @@ -107,13 +110,11 @@ class EffectFactory::Impl std::mutex mutex; }; - // Global instance pool. SharedResourcePool EffectFactory::Impl::instancePool; - -_Use_decl_annotations_ -std::shared_ptr EffectFactory::Impl::CreateEffect(IEffectFactory* factory, const IEffectFactory::EffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr +EffectFactory::Impl::CreateEffect(IEffectFactory* factory, const IEffectFactory::EffectInfo& info, ID3D11DeviceContext* deviceContext) { if (info.enableSkinning) { @@ -163,7 +164,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect(IEffectFactory* facto if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectNormalMapSkinned.insert(v); } @@ -197,7 +198,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect(IEffectFactory* facto if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCacheSkinning.insert(v); } @@ -260,7 +261,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect(IEffectFactory* facto if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCacheDualTexture.insert(v); } @@ -317,7 +318,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect(IEffectFactory* facto if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectNormalMap.insert(v); } @@ -359,7 +360,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect(IEffectFactory* facto if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCache.insert(v); } @@ -367,8 +368,8 @@ std::shared_ptr EffectFactory::Impl::CreateEffect(IEffectFactory* facto } } -_Use_decl_annotations_ -void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { if (!name || !textureView) throw std::invalid_argument("name and textureView parameters can't be null"); @@ -399,7 +400,8 @@ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: EffectFactory could not find texture file '%ls'\n", name); - throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "EffectFactory::CreateTexture"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), + "EffectFactory::CreateTexture"); } } @@ -409,43 +411,59 @@ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext if (isdds) { - HRESULT hr = CreateDDSTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateDDSTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, + nullptr, + textureView); 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("EffectFactory::CreateDDSTextureFromFile"); } } - #if !defined(_XBOX_ONE) || !defined(_TITLE) +#if !defined(_XBOX_ONE) || !defined(_TITLE) else if (deviceContext) { std::lock_guard lock(mutex); - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), deviceContext, fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + deviceContext, + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("EffectFactory::CreateWICTextureFromFile"); } } - #endif +#endif else { - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("EffectFactory::CreateWICTextureFromFile"); } } @@ -453,7 +471,7 @@ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext if (mSharing && *name && it == mTextureCache.end()) { std::lock_guard lock(mutex); - TextureCache::value_type v(name, *textureView); + TextureCache::value_type v(name, *textureView); mTextureCache.insert(v); } } @@ -470,8 +488,6 @@ void EffectFactory::Impl::ReleaseCache() mTextureCache.clear(); } - - //-------------------------------------------------------------------------------------- // EffectFactory //-------------------------------------------------------------------------------------- @@ -480,20 +496,17 @@ EffectFactory::EffectFactory(_In_ ID3D11Device* device) : pImpl(Impl::instancePool.DemandCreate(device)) {} +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; - - -_Use_decl_annotations_ -std::shared_ptr EffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr EffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) { return pImpl->CreateEffect(this, info, deviceContext); } -_Use_decl_annotations_ -void EffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +EffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { return pImpl->CreateTexture(name, deviceContext, textureView); } @@ -529,7 +542,7 @@ void EffectFactory::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; } } diff --git a/Src/EnvironmentMapEffect.cpp b/Src/EnvironmentMapEffect.cpp index 6a3c67e5..251457a0 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; @@ -46,13 +46,13 @@ namespace { using ConstantBufferType = EnvironmentMapEffectConstants; - static constexpr int VertexShaderCount = 12; - static constexpr int PixelShaderCount = 16; + static constexpr int VertexShaderCount = 12; + static constexpr int PixelShaderCount = 16; static constexpr int ShaderPermutationCount = 56; static constexpr int MappingCount = 3; }; -} +} // namespace // Internal EnvironmentMapEffect implementation class. class EnvironmentMapEffect::Impl : public EffectBase @@ -60,16 +60,16 @@ class EnvironmentMapEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; - bool preferPerPixelLighting; - bool fresnelEnabled; - bool specularEnabled; - bool biasedVertexNormals; + bool preferPerPixelLighting; + bool fresnelEnabled; + bool specularEnabled; + bool biasedVertexNormals; EnvironmentMapEffect::Mapping mapping; EffectLights lights; @@ -81,7 +81,6 @@ class EnvironmentMapEffect::Impl : public EffectBase void Apply(_In_ ID3D11DeviceContext* deviceContext); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -149,220 +148,221 @@ namespace #include "EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnel.inc" #include "EnvironmentMapEffect_PSEnvMapDualParabolaPixelLightingFresnelNoFog.inc" #endif -} - +} // namespace template<> -const ShaderBytecode EffectBase::VertexShaderBytecode[] = -{ - { EnvironmentMapEffect_VSEnvMap, sizeof(EnvironmentMapEffect_VSEnvMap) }, - { EnvironmentMapEffect_VSEnvMapFresnel, sizeof(EnvironmentMapEffect_VSEnvMapFresnel) }, - { EnvironmentMapEffect_VSEnvMapOneLight, sizeof(EnvironmentMapEffect_VSEnvMapOneLight) }, - { EnvironmentMapEffect_VSEnvMapOneLightFresnel, sizeof(EnvironmentMapEffect_VSEnvMapOneLightFresnel) }, - { EnvironmentMapEffect_VSEnvMapPixelLighting, sizeof(EnvironmentMapEffect_VSEnvMapPixelLighting) }, - - { EnvironmentMapEffect_VSEnvMapBn, sizeof(EnvironmentMapEffect_VSEnvMapBn) }, - { EnvironmentMapEffect_VSEnvMapFresnelBn, sizeof(EnvironmentMapEffect_VSEnvMapFresnelBn) }, - { EnvironmentMapEffect_VSEnvMapOneLightBn, sizeof(EnvironmentMapEffect_VSEnvMapOneLightBn) }, - { EnvironmentMapEffect_VSEnvMapOneLightFresnelBn, sizeof(EnvironmentMapEffect_VSEnvMapOneLightFresnelBn) }, - { EnvironmentMapEffect_VSEnvMapPixelLightingBn, sizeof(EnvironmentMapEffect_VSEnvMapPixelLightingBn) }, +const ShaderBytecode EffectBase::VertexShaderBytecode[] = { + { EnvironmentMapEffect_VSEnvMap, sizeof(EnvironmentMapEffect_VSEnvMap) }, + { EnvironmentMapEffect_VSEnvMapFresnel, sizeof(EnvironmentMapEffect_VSEnvMapFresnel) }, + { EnvironmentMapEffect_VSEnvMapOneLight, sizeof(EnvironmentMapEffect_VSEnvMapOneLight) }, + { EnvironmentMapEffect_VSEnvMapOneLightFresnel, sizeof(EnvironmentMapEffect_VSEnvMapOneLightFresnel) }, + { EnvironmentMapEffect_VSEnvMapPixelLighting, sizeof(EnvironmentMapEffect_VSEnvMapPixelLighting) }, + + { EnvironmentMapEffect_VSEnvMapBn, sizeof(EnvironmentMapEffect_VSEnvMapBn) }, + { EnvironmentMapEffect_VSEnvMapFresnelBn, sizeof(EnvironmentMapEffect_VSEnvMapFresnelBn) }, + { EnvironmentMapEffect_VSEnvMapOneLightBn, sizeof(EnvironmentMapEffect_VSEnvMapOneLightBn) }, + { EnvironmentMapEffect_VSEnvMapOneLightFresnelBn, sizeof(EnvironmentMapEffect_VSEnvMapOneLightFresnelBn) }, + { 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, // one light - 2, // one light, no fog - 3, // one light, fresnel - 3, // one light, fresnel, no fog - 2, // one light, specular - 2, // one light, specular, no fog - 3, // one light, fresnel + specular - 3, // one light, fresnel + specular, no fog - - 4, // pixel lighting - 4, // pixel lighting, no fog - 4, // pixel lighting, fresnel - 4, // pixel lighting, fresnel, no fog - - 5, // basic (biased vertex normals) - 5, // basic (biased vertex normals), no fog - 6, // fresnel (biased vertex normals) - 6, // fresnel (biased vertex normals), no fog - 5, // specular (biased vertex normals) - 5, // specular (biased vertex normals), no fog - 6, // fresnel + specular (biased vertex normals) - 6, // fresnel + specular (biased vertex normals), no fog - - 7, // one light (biased vertex normals) - 7, // one light (biased vertex normals), no fog - 8, // one light (biased vertex normals), fresnel - 8, // one light (biased vertex normals), fresnel, no fog - 7, // one light (biased vertex normals), specular - 7, // one light (biased vertex normals), specular, no fog - 8, // one light (biased vertex normals), fresnel + specular - 8, // one light (biased vertex normals), fresnel + specular, no fog - - 9, // pixel lighting (biased vertex normals) - 9, // pixel lighting (biased vertex normals), no fog - 9, // pixel lighting (biased vertex normals), fresnel - 9, // pixel lighting (biased vertex normals), fresnel, no fog - - 4, // spheremap pixel lighting - 4, // spheremap pixel lighting, no fog - 4, // spheremap pixel lighting, fresnel - 4, // spheremap pixel lighting, fresnel, no fog - - 9, // spheremap pixel lighting (biased vertex normals) - 9, // spheremap pixel lighting (biased vertex normals), no fog - 9, // spheremap pixel lighting (biased vertex normals), fresnel - 9, // spheremap pixel lighting (biased vertex normals), fresnel, no fog - - 4, // dual-parabola pixel lighting - 4, // dual-parabola pixel lighting, no fog - 4, // dual-parabola pixel lighting, fresnel - 4, // dual-parabola pixel lighting, fresnel, no fog - - 9, // dual-parabola pixel lighting (biased vertex normals) - 9, // dual-parabola pixel lighting (biased vertex normals), no fog - 9, // dual-parabola pixel lighting (biased vertex normals), fresnel - 9, // 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, // one light + 2, // one light, no fog + 3, // one light, fresnel + 3, // one light, fresnel, no fog + 2, // one light, specular + 2, // one light, specular, no fog + 3, // one light, fresnel + specular + 3, // one light, fresnel + specular, no fog + + 4, // pixel lighting + 4, // pixel lighting, no fog + 4, // pixel lighting, fresnel + 4, // pixel lighting, fresnel, no fog + + 5, // basic (biased vertex normals) + 5, // basic (biased vertex normals), no fog + 6, // fresnel (biased vertex normals) + 6, // fresnel (biased vertex normals), no fog + 5, // specular (biased vertex normals) + 5, // specular (biased vertex normals), no fog + 6, // fresnel + specular (biased vertex normals) + 6, // fresnel + specular (biased vertex normals), no fog + + 7, // one light (biased vertex normals) + 7, // one light (biased vertex normals), no fog + 8, // one light (biased vertex normals), fresnel + 8, // one light (biased vertex normals), fresnel, no fog + 7, // one light (biased vertex normals), specular + 7, // one light (biased vertex normals), specular, no fog + 8, // one light (biased vertex normals), fresnel + specular + 8, // one light (biased vertex normals), fresnel + specular, no fog + + 9, // pixel lighting (biased vertex normals) + 9, // pixel lighting (biased vertex normals), no fog + 9, // pixel lighting (biased vertex normals), fresnel + 9, // pixel lighting (biased vertex normals), fresnel, no fog + + 4, // spheremap pixel lighting + 4, // spheremap pixel lighting, no fog + 4, // spheremap pixel lighting, fresnel + 4, // spheremap pixel lighting, fresnel, no fog + + 9, // spheremap pixel lighting (biased vertex normals) + 9, // spheremap pixel lighting (biased vertex normals), no fog + 9, // spheremap pixel lighting (biased vertex normals), fresnel + 9, // spheremap pixel lighting (biased vertex normals), fresnel, no fog + + 4, // dual-parabola pixel lighting + 4, // dual-parabola pixel lighting, no fog + 4, // dual-parabola pixel lighting, fresnel + 4, // dual-parabola pixel lighting, fresnel, no fog + + 9, // dual-parabola pixel lighting (biased vertex normals) + 9, // dual-parabola pixel lighting (biased vertex normals), no fog + 9, // dual-parabola pixel lighting (biased vertex normals), fresnel + 9, // dual-parabola pixel lighting (biased vertex normals), fresnel, no fog }; - template<> -const ShaderBytecode 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 ShaderBytecode 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 - - 0, // one light - 1, // one light, no fog - 0, // one light, fresnel - 1, // one light, fresnel, no fog - 2, // one light, specular - 3, // one light, specular, no fog - 2, // one light, fresnel + specular - 3, // one light, 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 - - 0, // one light (biased vertex normals) - 1, // one light (biased vertex normals), no fog - 0, // one light (biased vertex normals), fresnel - 1, // one light (biased vertex normals), fresnel, no fog - 2, // one light (biased vertex normals), specular - 3, // one light (biased vertex normals), specular, no fog - 2, // one light (biased vertex normals), fresnel + specular - 3, // one light (biased vertex normals), fresnel + specular, 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 + + 0, // one light + 1, // one light, no fog + 0, // one light, fresnel + 1, // one light, fresnel, no fog + 2, // one light, specular + 3, // one light, specular, no fog + 2, // one light, fresnel + specular + 3, // one light, 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 + + 0, // one light (biased vertex normals) + 1, // one light (biased vertex normals), no fog + 0, // one light (biased vertex normals), fresnel + 1, // one light (biased vertex normals), fresnel, no fog + 2, // one light (biased vertex normals), specular + 3, // one light (biased vertex normals), specular, no fog + 2, // one light (biased vertex normals), fresnel + specular + 3, // one light (biased vertex normals), fresnel + specular, 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_ ID3D11Device* device) : EffectBase(device), - preferPerPixelLighting(false), - fresnelEnabled(true), - specularEnabled(false), - biasedVertexNormals(false), - mapping(Mapping_Cube) -{ - 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"); + preferPerPixelLighting(false), + fresnelEnabled(true), + specularEnabled(false), + biasedVertexNormals(false), + mapping(Mapping_Cube) +{ + 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"); constants.environmentMapAmount = 1; - constants.fresnelFactor = 1; + constants.fresnelFactor = 1; XMVECTOR unwantedOutput[MaxDirectionalLights]; lights.InitializeConstants(unwantedOutput[0], constants.lightDirection, constants.lightDiffuseColor, unwantedOutput); } - int EnvironmentMapEffect::Impl::GetCurrentShaderPermutation() const noexcept { int permutation = 0; @@ -428,7 +428,6 @@ int EnvironmentMapEffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void EnvironmentMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -439,11 +438,17 @@ void EnvironmentMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) 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); // Set the textures. - ID3D11ShaderResourceView* textures[2] = - { + ID3D11ShaderResourceView* textures[2] = { (texture) ? texture.Get() : GetDefaultTexture(), environmentMap.Get(), }; @@ -454,17 +459,14 @@ void EnvironmentMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - // Public constructor. EnvironmentMapEffect::EnvironmentMapEffect(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext) @@ -472,13 +474,11 @@ void EnvironmentMapEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void EnvironmentMapEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV EnvironmentMapEffect::SetWorld(FXMMATRIX value) { @@ -487,7 +487,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; @@ -495,7 +494,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; @@ -503,17 +501,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) { @@ -522,7 +519,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV EnvironmentMapEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -530,7 +526,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetEmissiveColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void EnvironmentMapEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -538,16 +533,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 EnvironmentMapEffect::SetLightingEnabled(bool value) { @@ -557,13 +550,11 @@ void EnvironmentMapEffect::SetLightingEnabled(bool value) } } - void EnvironmentMapEffect::SetPerPixelLighting(bool value) { pImpl->preferPerPixelLighting = value; } - void XM_CALLCONV EnvironmentMapEffect::SetAmbientLightColor(FXMVECTOR value) { pImpl->lights.ambientLightColor = value; @@ -571,7 +562,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetAmbientLightColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void EnvironmentMapEffect::SetLightEnabled(int whichLight, bool value) { XMVECTOR unwantedOutput[MaxDirectionalLights] = {}; @@ -579,7 +569,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); @@ -589,25 +578,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::SetFogEnabled(bool value) { @@ -616,7 +601,6 @@ void EnvironmentMapEffect::SetFogEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::FogEnable; } - void EnvironmentMapEffect::SetFogStart(float value) { pImpl->fog.start = value; @@ -624,7 +608,6 @@ void EnvironmentMapEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void EnvironmentMapEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -632,7 +615,6 @@ void EnvironmentMapEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV EnvironmentMapEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -640,20 +622,17 @@ void XM_CALLCONV EnvironmentMapEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void EnvironmentMapEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - void EnvironmentMapEffect::SetEnvironmentMap(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->environmentMap = value; } - // Additional settings. void EnvironmentMapEffect::SetMode(EnvironmentMapEffect::Mapping mapping) { @@ -665,7 +644,6 @@ void EnvironmentMapEffect::SetMode(EnvironmentMapEffect::Mapping mapping) pImpl->mapping = mapping; } - void EnvironmentMapEffect::SetEnvironmentMapAmount(float value) { pImpl->constants.environmentMapAmount = value; @@ -673,7 +651,6 @@ void EnvironmentMapEffect::SetEnvironmentMapAmount(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV EnvironmentMapEffect::SetEnvironmentMapSpecular(FXMVECTOR value) { pImpl->constants.environmentMapSpecular = value; @@ -683,7 +660,6 @@ void XM_CALLCONV EnvironmentMapEffect::SetEnvironmentMapSpecular(FXMVECTOR value pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void EnvironmentMapEffect::SetFresnelFactor(float value) { pImpl->constants.fresnelFactor = value; @@ -693,7 +669,6 @@ void EnvironmentMapEffect::SetFresnelFactor(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Normal compression settings. void EnvironmentMapEffect::SetBiasedVertexNormals(bool 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 13bc7db4..2c2c53a5 100644 --- a/Src/GeometricPrimitive.cpp +++ b/Src/GeometricPrimitive.cpp @@ -19,37 +19,42 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - // Internal GeometricPrimitive implementation class. class GeometricPrimitive::Impl { public: - Impl() noexcept : mIndexCount(0) {} + Impl() noexcept + : mIndexCount(0) + {} - 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_ ID3D11DeviceContext* deviceContext, const VertexCollection& vertices, const IndexCollection& indices); - void XM_CALLCONV Draw(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection, - FXMVECTOR color, + void XM_CALLCONV Draw(FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + FXMVECTOR color, _In_opt_ ID3D11ShaderResourceView* texture, - bool wireframe, - const std::function& setCustomState) const; + bool wireframe, + const std::function& setCustomState) const; - void Draw(_In_ IEffect* effect, - _In_ ID3D11InputLayout* inputLayout, - bool alpha, bool wireframe, + void Draw(_In_ IEffect* effect, + _In_ ID3D11InputLayout* inputLayout, + bool alpha, + bool wireframe, const std::function& setCustomState) const; void DrawInstanced(_In_ IEffect* effect, - _In_ ID3D11InputLayout* inputLayout, - uint32_t instanceCount, - bool alpha, bool wireframe, - uint32_t startInstanceLocation, + _In_ ID3D11InputLayout* inputLayout, + uint32_t instanceCount, + bool alpha, + bool wireframe, + uint32_t startInstanceLocation, const std::function& setCustomState) const; void CreateInputLayout(_In_ IEffect* effect, _Outptr_ ID3D11InputLayout** inputLayout) const; @@ -68,7 +73,7 @@ class GeometricPrimitive::Impl void PrepareForRendering(bool alpha, bool wireframe) const; - ComPtr mDeviceContext; + ComPtr mDeviceContext; std::unique_ptr effect; ComPtr inputLayoutTextured; @@ -77,18 +82,15 @@ class GeometricPrimitive::Impl std::unique_ptr stateObjects; }; - // Per-device-context data. std::shared_ptr mResources; static SharedResourcePool sharedResourcesPool; }; - // Global pool of per-device-context GeometricPrimitive resources. SharedResourcePool GeometricPrimitive::Impl::sharedResourcesPool; - // Per-device-context constructor. GeometricPrimitive::Impl::SharedResources::SharedResources(_In_ ID3D11DeviceContext* deviceContext) : mDeviceContext(deviceContext) @@ -106,38 +108,33 @@ GeometricPrimitive::Impl::SharedResources::SharedResources(_In_ ID3D11DeviceCont // Create input layouts. effect->SetTextureEnabled(true); - ThrowIfFailed( - CreateInputLayoutFromEffect(device.Get(), effect.get(), &inputLayoutTextured) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(device.Get(), effect.get(), &inputLayoutTextured)); SetDebugObjectName(inputLayoutTextured.Get(), "DirectXTK:GeometricPrimitive"); effect->SetTextureEnabled(false); - ThrowIfFailed( - CreateInputLayoutFromEffect(device.Get(), effect.get(), &inputLayoutUntextured) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(device.Get(), effect.get(), &inputLayoutUntextured)); SetDebugObjectName(inputLayoutUntextured.Get(), "DirectXTK:GeometricPrimitive"); } - // Sets up D3D device state ready for drawing a primitive. void GeometricPrimitive::Impl::SharedResources::PrepareForRendering(bool alpha, bool wireframe) const { // Set the blend and depth stencil state. - ID3D11BlendState* blendState; + ID3D11BlendState* blendState; ID3D11DepthStencilState* depthStencilState; if (alpha) { // Alpha blended rendering. - blendState = stateObjects->AlphaBlend(); + blendState = stateObjects->AlphaBlend(); depthStencilState = s_reversez ? stateObjects->DepthReadReverseZ() : stateObjects->DepthRead(); } else { // Opaque rendering. - blendState = stateObjects->Opaque(); + blendState = stateObjects->Opaque(); depthStencilState = s_reversez ? stateObjects->DepthReverseZ() : stateObjects->DepthDefault(); } @@ -155,10 +152,9 @@ void GeometricPrimitive::Impl::SharedResources::PrepareForRendering(bool alpha, mDeviceContext->PSSetSamplers(0, 1, &samplerState); } - // Initializes a geometric primitive instance that will draw the specified vertex and index data. -_Use_decl_annotations_ -void GeometricPrimitive::Impl::Initialize(ID3D11DeviceContext* deviceContext, const VertexCollection& vertices, const IndexCollection& indices) +_Use_decl_annotations_ void +GeometricPrimitive::Impl::Initialize(ID3D11DeviceContext* deviceContext, const VertexCollection& vertices, const IndexCollection& indices) { if (!deviceContext) throw std::invalid_argument("Direct3D device context is null"); @@ -174,13 +170,9 @@ void GeometricPrimitive::Impl::Initialize(ID3D11DeviceContext* deviceContext, co ComPtr device; deviceContext->GetDevice(&device); - ThrowIfFailed( - CreateStaticBuffer(device.Get(), vertices, D3D11_BIND_VERTEX_BUFFER, mVertexBuffer.ReleaseAndGetAddressOf()) - ); + ThrowIfFailed(CreateStaticBuffer(device.Get(), vertices, D3D11_BIND_VERTEX_BUFFER, mVertexBuffer.ReleaseAndGetAddressOf())); - ThrowIfFailed( - CreateStaticBuffer(device.Get(), indices, D3D11_BIND_INDEX_BUFFER, mIndexBuffer.ReleaseAndGetAddressOf()) - ); + ThrowIfFailed(CreateStaticBuffer(device.Get(), indices, D3D11_BIND_INDEX_BUFFER, mIndexBuffer.ReleaseAndGetAddressOf())); SetDebugObjectName(mVertexBuffer.Get(), "DirectXTK:GeometricPrimitive"); SetDebugObjectName(mIndexBuffer.Get(), "DirectXTK:GeometricPrimitive"); @@ -188,23 +180,20 @@ void GeometricPrimitive::Impl::Initialize(ID3D11DeviceContext* deviceContext, co mIndexCount = static_cast(indices.size()); } - // Draws the primitive. -_Use_decl_annotations_ -void XM_CALLCONV GeometricPrimitive::Impl::Draw( - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - FXMVECTOR color, - ID3D11ShaderResourceView* texture, - bool wireframe, - const std::function& setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV GeometricPrimitive::Impl::Draw(FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + FXMVECTOR color, + ID3D11ShaderResourceView* texture, + bool wireframe, + const std::function& setCustomState) const { assert(mResources); auto effect = mResources->effect.get(); assert(effect != nullptr); - ID3D11InputLayout *inputLayout; + ID3D11InputLayout* inputLayout; if (texture) { effect->SetTextureEnabled(true); @@ -228,15 +217,12 @@ void XM_CALLCONV GeometricPrimitive::Impl::Draw( Draw(effect, inputLayout, (alpha < 1.f), wireframe, setCustomState); } - // Draw the primitive using a custom effect. -_Use_decl_annotations_ -void GeometricPrimitive::Impl::Draw( - IEffect* effect, - ID3D11InputLayout* inputLayout, - bool alpha, - bool wireframe, - const std::function& setCustomState) const +_Use_decl_annotations_ void GeometricPrimitive::Impl::Draw(IEffect* effect, + ID3D11InputLayout* inputLayout, + bool alpha, + bool wireframe, + const std::function& setCustomState) const { assert(mResources); auto deviceContext = mResources->mDeviceContext.Get(); @@ -254,7 +240,7 @@ void GeometricPrimitive::Impl::Draw( effect->Apply(deviceContext); // Set the vertex and index buffer. - auto vertexBuffer = mVertexBuffer.Get(); + auto vertexBuffer = mVertexBuffer.Get(); constexpr UINT vertexStride = sizeof(VertexType); constexpr UINT vertexOffset = 0; @@ -274,15 +260,13 @@ void GeometricPrimitive::Impl::Draw( deviceContext->DrawIndexed(mIndexCount, 0, 0); } -_Use_decl_annotations_ -void GeometricPrimitive::Impl::DrawInstanced( - IEffect* effect, - ID3D11InputLayout* inputLayout, - uint32_t instanceCount, - bool alpha, - bool wireframe, - uint32_t startInstanceLocation, - const std::function& setCustomState) const +_Use_decl_annotations_ void GeometricPrimitive::Impl::DrawInstanced(IEffect* effect, + ID3D11InputLayout* inputLayout, + uint32_t instanceCount, + bool alpha, + bool wireframe, + uint32_t startInstanceLocation, + const std::function& setCustomState) const { assert(mResources); auto deviceContext = mResources->mDeviceContext.Get(); @@ -300,7 +284,7 @@ void GeometricPrimitive::Impl::DrawInstanced( effect->Apply(deviceContext); // Set the vertex and index buffer. - auto vertexBuffer = mVertexBuffer.Get(); + auto vertexBuffer = mVertexBuffer.Get(); constexpr UINT vertexStride = sizeof(VertexType); constexpr UINT vertexOffset = 0; @@ -320,10 +304,8 @@ void GeometricPrimitive::Impl::DrawInstanced( deviceContext->DrawIndexedInstanced(mIndexCount, instanceCount, 0, 0, startInstanceLocation); } - // Create input layout for drawing with a custom effect. -_Use_decl_annotations_ -void GeometricPrimitive::Impl::CreateInputLayout(IEffect* effect, ID3D11InputLayout** inputLayout) const +_Use_decl_annotations_ void GeometricPrimitive::Impl::CreateInputLayout(IEffect* effect, ID3D11InputLayout** inputLayout) const { assert(effect != nullptr); assert(inputLayout != nullptr); @@ -335,9 +317,7 @@ void GeometricPrimitive::Impl::CreateInputLayout(IEffect* effect, ID3D11InputLay ComPtr device; deviceContext->GetDevice(&device); - ThrowIfFailed( - CreateInputLayoutFromEffect(device.Get(), effect, inputLayout) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(device.Get(), effect, inputLayout)); assert(inputLayout != nullptr && *inputLayout != nullptr); _Analysis_assume_(inputLayout != nullptr && *inputLayout != nullptr); @@ -345,7 +325,6 @@ void GeometricPrimitive::Impl::CreateInputLayout(IEffect* effect, ID3D11InputLay SetDebugObjectName(*inputLayout, "DirectXTK:GeometricPrimitive"); } - //-------------------------------------------------------------------------------------- // GeometricPrimitive //-------------------------------------------------------------------------------------- @@ -357,72 +336,55 @@ GeometricPrimitive::GeometricPrimitive() noexcept(false) : pImpl(std::make_unique()) {} - // Destructor. -GeometricPrimitive::~GeometricPrimitive() -{} - +GeometricPrimitive::~GeometricPrimitive() {} // Public entrypoints. -_Use_decl_annotations_ -void XM_CALLCONV GeometricPrimitive::Draw( - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - FXMVECTOR color, - ID3D11ShaderResourceView* texture, - bool wireframe, - std::function setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV GeometricPrimitive::Draw(FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + FXMVECTOR color, + ID3D11ShaderResourceView* texture, + bool wireframe, + std::function setCustomState) const { pImpl->Draw(world, view, projection, color, texture, wireframe, setCustomState); } - -_Use_decl_annotations_ -void GeometricPrimitive::Draw( - IEffect* effect, - ID3D11InputLayout* inputLayout, - bool alpha, - bool wireframe, - std::function setCustomState) const +_Use_decl_annotations_ void GeometricPrimitive::Draw(IEffect* effect, + ID3D11InputLayout* inputLayout, + bool alpha, + bool wireframe, + std::function setCustomState) const { pImpl->Draw(effect, inputLayout, alpha, wireframe, setCustomState); } - -_Use_decl_annotations_ -void GeometricPrimitive::DrawInstanced( - IEffect* effect, - ID3D11InputLayout* inputLayout, - uint32_t instanceCount, - bool alpha, - bool wireframe, - uint32_t startInstanceLocation, - std::function setCustomState) const +_Use_decl_annotations_ void GeometricPrimitive::DrawInstanced(IEffect* effect, + ID3D11InputLayout* inputLayout, + uint32_t instanceCount, + bool alpha, + bool wireframe, + uint32_t startInstanceLocation, + std::function setCustomState) const { pImpl->DrawInstanced(effect, inputLayout, instanceCount, alpha, wireframe, startInstanceLocation, setCustomState); } - -_Use_decl_annotations_ -void GeometricPrimitive::CreateInputLayout(IEffect* effect, ID3D11InputLayout** inputLayout) const +_Use_decl_annotations_ void GeometricPrimitive::CreateInputLayout(IEffect* effect, ID3D11InputLayout** inputLayout) const { pImpl->CreateInputLayout(effect, inputLayout); } - //-------------------------------------------------------------------------------------- // Cube (aka a Hexahedron) or Box //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateCube( - ID3D11DeviceContext* deviceContext, - float size, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr + GeometricPrimitive::CreateCube(ID3D11DeviceContext* deviceContext, float size, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeBox(vertices, indices, XMFLOAT3(size, size, size), rhcoords, false); // Create the primitive object. @@ -433,26 +395,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. -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateBox( - ID3D11DeviceContext* deviceContext, - const XMFLOAT3& size, - bool rhcoords, - bool invertn) +_Use_decl_annotations_ std::unique_ptr + GeometricPrimitive::CreateBox(ID3D11DeviceContext* deviceContext, const XMFLOAT3& size, bool rhcoords, bool invertn) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeBox(vertices, indices, size, rhcoords, invertn); // Create the primitive object. @@ -463,31 +416,20 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateSphere( - ID3D11DeviceContext* deviceContext, - float diameter, - size_t tessellation, - bool rhcoords, - bool invertn) +_Use_decl_annotations_ std::unique_ptr +GeometricPrimitive::CreateSphere(ID3D11DeviceContext* deviceContext, float diameter, size_t tessellation, bool rhcoords, bool invertn) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeSphere(vertices, indices, diameter, tessellation, rhcoords, invertn); // Create the primitive object. @@ -498,31 +440,25 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateGeoSphere( - ID3D11DeviceContext* deviceContext, - float diameter, - size_t tessellation, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr +GeometricPrimitive::CreateGeoSphere(ID3D11DeviceContext* deviceContext, float diameter, size_t tessellation, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeGeoSphere(vertices, indices, diameter, tessellation, rhcoords); // Create the primitive object. @@ -533,31 +469,25 @@ 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. -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateCylinder( - ID3D11DeviceContext* deviceContext, - float height, - float diameter, - size_t tessellation, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr +GeometricPrimitive::CreateCylinder(ID3D11DeviceContext* deviceContext, float height, float diameter, size_t tessellation, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeCylinder(vertices, indices, height, diameter, tessellation, rhcoords); // Create the primitive object. @@ -568,29 +498,22 @@ 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. -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateCone( - ID3D11DeviceContext* deviceContext, - float diameter, - float height, - size_t tessellation, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr +GeometricPrimitive::CreateCone(ID3D11DeviceContext* deviceContext, float diameter, float height, size_t tessellation, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeCone(vertices, indices, diameter, height, tessellation, rhcoords); // Create the primitive object. @@ -601,32 +524,25 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateTorus( - ID3D11DeviceContext* deviceContext, - float diameter, - float thickness, - size_t tessellation, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr +GeometricPrimitive::CreateTorus(ID3D11DeviceContext* deviceContext, float diameter, float thickness, size_t tessellation, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeTorus(vertices, indices, diameter, thickness, tessellation, rhcoords); // Create the primitive object. @@ -637,30 +553,25 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateTetrahedron( - ID3D11DeviceContext* deviceContext, - float size, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr + GeometricPrimitive::CreateTetrahedron(ID3D11DeviceContext* deviceContext, float size, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeTetrahedron(vertices, indices, size, rhcoords); // Create the primitive object. @@ -671,28 +582,20 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateOctahedron( - ID3D11DeviceContext* deviceContext, - float size, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr + GeometricPrimitive::CreateOctahedron(ID3D11DeviceContext* deviceContext, float size, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeOctahedron(vertices, indices, size, rhcoords); // Create the primitive object. @@ -703,28 +606,20 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateDodecahedron( - ID3D11DeviceContext* deviceContext, - float size, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr + GeometricPrimitive::CreateDodecahedron(ID3D11DeviceContext* deviceContext, float size, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeDodecahedron(vertices, indices, size, rhcoords); // Create the primitive object. @@ -735,28 +630,20 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateIcosahedron( - ID3D11DeviceContext* deviceContext, - float size, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr + GeometricPrimitive::CreateIcosahedron(ID3D11DeviceContext* deviceContext, float size, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeIcosahedron(vertices, indices, size, rhcoords); // Create the primitive object. @@ -767,29 +654,20 @@ 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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateTeapot( - ID3D11DeviceContext* deviceContext, - float size, - size_t tessellation, - bool rhcoords) +_Use_decl_annotations_ std::unique_ptr + GeometricPrimitive::CreateTeapot(ID3D11DeviceContext* deviceContext, float size, size_t tessellation, bool rhcoords) { VertexCollection vertices; - IndexCollection indices; + IndexCollection indices; ComputeTeapot(vertices, indices, size, tessellation, rhcoords); // Create the primitive object. @@ -800,26 +678,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 //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr GeometricPrimitive::CreateCustom( - ID3D11DeviceContext* deviceContext, - const VertexCollection& vertices, - const IndexCollection& indices) +_Use_decl_annotations_ std::unique_ptr +GeometricPrimitive::CreateCustom(ID3D11DeviceContext* deviceContext, const VertexCollection& vertices, const IndexCollection& indices) { // Extra validation if (vertices.empty() || indices.empty()) diff --git a/Src/Geometry.cpp b/Src/Geometry.cpp index 7e9067f7..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,29 +236,26 @@ 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 @@ -302,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); @@ -359,8 +356,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // 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 @@ -379,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; @@ -409,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()); @@ -421,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 @@ -459,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); @@ -475,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); @@ -541,7 +536,6 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi ReverseWinding(indices, vertices); } - //-------------------------------------------------------------------------------------- // Cylinder / Cone //-------------------------------------------------------------------------------------- @@ -551,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); @@ -562,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); @@ -570,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++) @@ -592,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); } @@ -613,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(); @@ -627,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. @@ -642,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)); @@ -662,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(); @@ -676,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. @@ -692,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)); @@ -714,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(); @@ -745,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)); @@ -778,7 +784,6 @@ void DirectX::ComputeTorus(VertexCollection& vertices, IndexCollection& indices, ReverseWinding(indices, vertices); } - //-------------------------------------------------------------------------------------- // Tetrahedron //-------------------------------------------------------------------------------------- @@ -787,8 +792,7 @@ 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 } } }, @@ -797,8 +801,7 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in // 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, @@ -813,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); @@ -842,7 +843,6 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in assert(indices.size() == 4 * 3); } - //-------------------------------------------------------------------------------------- // Octahedron //-------------------------------------------------------------------------------------- @@ -851,18 +851,14 @@ 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, @@ -881,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); @@ -910,7 +904,6 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind assert(indices.size() == 8 * 3); } - //-------------------------------------------------------------------------------------- // Dodecahedron //-------------------------------------------------------------------------------------- @@ -923,8 +916,7 @@ 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 } } }, @@ -949,8 +941,7 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i // 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, @@ -967,8 +958,7 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i // 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 } } }, @@ -978,8 +968,7 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i // 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 }, @@ -1005,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(); @@ -1049,7 +1036,6 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i assert(indices.size() == 12 * 3 * 3); } - //-------------------------------------------------------------------------------------- // Icosahedron //-------------------------------------------------------------------------------------- @@ -1058,11 +1044,10 @@ 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 } } }, @@ -1079,8 +1064,7 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in // 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, @@ -1111,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); @@ -1140,7 +1122,6 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in assert(indices.size() == 20 * 3); } - //-------------------------------------------------------------------------------------- // Teapot //-------------------------------------------------------------------------------------- @@ -1151,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] = {}; @@ -1163,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) @@ -1188,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 04bf7de5..6b063c40 100644 --- a/Src/GraphicsMemory.cpp +++ b/Src/GraphicsMemory.cpp @@ -16,7 +16,6 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - #if defined(_XBOX_ONE) && defined(_TITLE) //====================================================================================== @@ -26,9 +25,9 @@ using Microsoft::WRL::ComPtr; class GraphicsMemory::Impl { public: - Impl(GraphicsMemory* owner) : - mOwner(owner), - mCurrentFrame(0) + Impl(GraphicsMemory* owner) + : mOwner(owner), + mCurrentFrame(0) { if (s_graphicsMemory) { @@ -56,10 +55,10 @@ class GraphicsMemory::Impl s_graphicsMemory = nullptr; } - 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_ ID3D11DeviceX* device, unsigned int backBufferCount) @@ -101,13 +100,16 @@ class GraphicsMemory::Impl mFrames[mCurrentFrame].Clear(); } - GraphicsMemory* mOwner; + GraphicsMemory* mOwner; std::mutex mGuard; struct MemoryPage { - MemoryPage() noexcept : mPageSize(0), mGrfxMemory(nullptr) {} + MemoryPage() noexcept + : mPageSize(0), + mGrfxMemory(nullptr) + {} void Initialize(size_t reqSize) { @@ -117,7 +119,8 @@ class GraphicsMemory::Impl mPageSize = AlignUp(reqSize, 65536); } - mGrfxMemory = VirtualAlloc(nullptr, mPageSize, + mGrfxMemory = VirtualAlloc(nullptr, + mPageSize, MEM_LARGE_PAGES | MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT, PAGE_WRITECOMBINE | PAGE_READWRITE | PAGE_GPU_READONLY); if (!mGrfxMemory) @@ -125,12 +128,15 @@ class GraphicsMemory::Impl } size_t mPageSize; - void* mGrfxMemory; + void* mGrfxMemory; }; struct MemoryFrame { - MemoryFrame() noexcept : mCurOffset(0), mFence(0) {} + MemoryFrame() noexcept + : mCurOffset(0), + mFence(0) + {} ~MemoryFrame() { Clear(); } @@ -205,10 +211,10 @@ class GraphicsMemory::Impl std::list mPages; }; - UINT mCurrentFrame; + UINT mCurrentFrame; std::vector mFrames; - ComPtr mDevice; + ComPtr mDevice; ComPtr mDeviceContext; static GraphicsMemory::Impl* s_graphicsMemory; @@ -225,8 +231,8 @@ GraphicsMemory::Impl* GraphicsMemory::Impl::s_graphicsMemory = nullptr; class GraphicsMemory::Impl { public: - Impl(GraphicsMemory* owner) : - mOwner(owner) + Impl(GraphicsMemory* owner) + : mOwner(owner) { if (s_graphicsMemory) { @@ -236,16 +242,13 @@ class GraphicsMemory::Impl s_graphicsMemory = 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_graphicsMemory = nullptr; - } + ~Impl() { s_graphicsMemory = nullptr; } void Initialize(_In_ ID3D11Device* device, unsigned int backBufferCount) { @@ -270,10 +273,9 @@ class GraphicsMemory::Impl return nullptr; } - void Commit() noexcept - {} + void Commit() noexcept {} - GraphicsMemory* mOwner; + GraphicsMemory* mOwner; static GraphicsMemory::Impl* s_graphicsMemory; }; @@ -282,11 +284,10 @@ GraphicsMemory::Impl* GraphicsMemory::Impl::s_graphicsMemory = nullptr; #endif - //-------------------------------------------------------------------------------------- #ifdef _MSC_VER -#pragma warning( disable : 4355 ) +#pragma warning(disable : 4355) #endif // Public constructor. @@ -300,7 +301,6 @@ GraphicsMemory::GraphicsMemory(_In_ ID3D11Device* device, unsigned int backBuffe pImpl->Initialize(device, backBufferCount); } - // Move constructor. GraphicsMemory::GraphicsMemory(GraphicsMemory&& moveFrom) noexcept : pImpl(std::move(moveFrom.pImpl)) @@ -308,32 +308,27 @@ 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; - void* GraphicsMemory::Allocate(_In_opt_ ID3D11DeviceContext* context, size_t size, int alignment) { return pImpl->Allocate(context, size, alignment); } - void GraphicsMemory::Commit() { pImpl->Commit(); } - GraphicsMemory& GraphicsMemory::Get() { if (!Impl::s_graphicsMemory || !Impl::s_graphicsMemory->mOwner) 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/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 5d904090..55fb83cd 100644 --- a/Src/Model.cpp +++ b/Src/Model.cpp @@ -24,33 +24,28 @@ using namespace DirectX; // ModelMeshPart //-------------------------------------------------------------------------------------- -ModelMeshPart::ModelMeshPart() noexcept : - indexCount(0), - startIndex(0), - vertexOffset(0), - vertexStride(0), - primitiveType(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST), - indexFormat(DXGI_FORMAT_R16_UINT), - isAlpha(false) -{} - - -ModelMeshPart::~ModelMeshPart() +ModelMeshPart::ModelMeshPart() noexcept + : indexCount(0), + startIndex(0), + vertexOffset(0), + vertexStride(0), + primitiveType(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST), + indexFormat(DXGI_FORMAT_R16_UINT), + isAlpha(false) {} +ModelMeshPart::~ModelMeshPart() {} // Draws using a custom override effect. -_Use_decl_annotations_ -void ModelMeshPart::Draw( - ID3D11DeviceContext* deviceContext, - IEffect* ieffect, - ID3D11InputLayout* iinputLayout, - std::function setCustomState) const +_Use_decl_annotations_ void ModelMeshPart::Draw(ID3D11DeviceContext* deviceContext, + IEffect* ieffect, + ID3D11InputLayout* iinputLayout, + std::function setCustomState) const { deviceContext->IASetInputLayout(iinputLayout); - auto vb = vertexBuffer.Get(); - const UINT vbStride = vertexStride; + auto vb = vertexBuffer.Get(); + const UINT vbStride = vertexStride; constexpr UINT vbOffset = 0; deviceContext->IASetVertexBuffers(0, 1, &vb, &vbStride, &vbOffset); @@ -72,20 +67,18 @@ void ModelMeshPart::Draw( deviceContext->DrawIndexed(indexCount, startIndex, vertexOffset); } - // Draws using a custom override effect w/ instancing. -_Use_decl_annotations_ -void ModelMeshPart::DrawInstanced( - ID3D11DeviceContext* deviceContext, - IEffect* ieffect, - ID3D11InputLayout* iinputLayout, - uint32_t instanceCount, uint32_t startInstanceLocation, - std::function setCustomState) const +_Use_decl_annotations_ void ModelMeshPart::DrawInstanced(ID3D11DeviceContext* deviceContext, + IEffect* ieffect, + ID3D11InputLayout* iinputLayout, + uint32_t instanceCount, + uint32_t startInstanceLocation, + std::function setCustomState) const { deviceContext->IASetInputLayout(iinputLayout); - auto vb = vertexBuffer.Get(); - const UINT vbStride = vertexStride; + auto vb = vertexBuffer.Get(); + const UINT vbStride = vertexStride; constexpr UINT vbOffset = 0; deviceContext->IASetVertexBuffers(0, 1, &vb, &vbStride, &vbOffset); @@ -104,16 +97,12 @@ void ModelMeshPart::DrawInstanced( // Draw the primitive. deviceContext->IASetPrimitiveTopology(primitiveType); - deviceContext->DrawIndexedInstanced( - indexCount, instanceCount, startIndex, - vertexOffset, - startInstanceLocation); + deviceContext->DrawIndexedInstanced(indexCount, instanceCount, startIndex, vertexOffset, startInstanceLocation); } - // Creates input layout for use with custom override effects. -_Use_decl_annotations_ -void ModelMeshPart::CreateInputLayout(ID3D11Device* d3dDevice, IEffect* ieffect, ID3D11InputLayout** iinputLayout) const +_Use_decl_annotations_ void +ModelMeshPart::CreateInputLayout(ID3D11Device* d3dDevice, IEffect* ieffect, ID3D11InputLayout** iinputLayout) const { if (iinputLayout) { @@ -126,18 +115,14 @@ void ModelMeshPart::CreateInputLayout(ID3D11Device* d3dDevice, IEffect* ieffect, if (vbDecl->size() > 32 /* D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT */) throw std::runtime_error("Model mesh part input layout size is too large for DirectX 11"); - ThrowIfFailed( - CreateInputLayoutFromEffect(d3dDevice, ieffect, vbDecl->data(), vbDecl->size(), iinputLayout) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(d3dDevice, ieffect, vbDecl->data(), vbDecl->size(), iinputLayout)); assert(iinputLayout != nullptr && *iinputLayout != nullptr); _Analysis_assume_(iinputLayout != nullptr && *iinputLayout != nullptr); } - // Assigns a new effect and re-generates input layout. -_Use_decl_annotations_ -void ModelMeshPart::ModifyEffect(ID3D11Device* d3dDevice, const std::shared_ptr& ieffect, bool isalpha) +_Use_decl_annotations_ void ModelMeshPart::ModifyEffect(ID3D11Device* d3dDevice, const std::shared_ptr& ieffect, bool isalpha) { if (!vbDecl || vbDecl->empty()) throw std::runtime_error("Model mesh part missing vertex buffer input elements data"); @@ -146,46 +131,37 @@ void ModelMeshPart::ModifyEffect(ID3D11Device* d3dDevice, const std::shared_ptr< throw std::runtime_error("Model mesh part input layout size is too large for DirectX 11"); assert(ieffect != nullptr); - this->effect = ieffect; + this->effect = ieffect; this->isAlpha = isalpha; assert(d3dDevice != nullptr); ThrowIfFailed( - CreateInputLayoutFromEffect(d3dDevice, effect.get(), vbDecl->data(), vbDecl->size(), inputLayout.ReleaseAndGetAddressOf()) - ); + CreateInputLayoutFromEffect(d3dDevice, effect.get(), vbDecl->data(), vbDecl->size(), inputLayout.ReleaseAndGetAddressOf())); } - //-------------------------------------------------------------------------------------- // ModelMesh //-------------------------------------------------------------------------------------- bool ModelMesh::s_reversez = false; -ModelMesh::ModelMesh() noexcept : - boneIndex(ModelBone::c_Invalid), - ccw(true), - pmalpha(true) -{} - - -ModelMesh::~ModelMesh() +ModelMesh::ModelMesh() noexcept + : boneIndex(ModelBone::c_Invalid), + ccw(true), + pmalpha(true) {} +ModelMesh::~ModelMesh() {} // Set render state for mesh part rendering. -_Use_decl_annotations_ -void ModelMesh::PrepareForRendering( - ID3D11DeviceContext* deviceContext, - const CommonStates& states, - bool alpha, - bool wireframe) const +_Use_decl_annotations_ void +ModelMesh::PrepareForRendering(ID3D11DeviceContext* deviceContext, const CommonStates& states, bool alpha, bool wireframe) const { assert(deviceContext != nullptr); // Set the blend and depth stencil state. - ID3D11BlendState* blendState; + ID3D11BlendState* blendState; ID3D11DepthStencilState* depthStencilState; if (alpha) @@ -202,7 +178,7 @@ void ModelMesh::PrepareForRendering( } else { - blendState = states.Opaque(); + blendState = states.Opaque(); depthStencilState = (s_reversez) ? states.DepthReverseZ() : states.DepthDefault(); } @@ -216,8 +192,7 @@ void ModelMesh::PrepareForRendering( deviceContext->RSSetState(ccw ? states.CullCounterClockwise() : states.CullClockwise()); // Set sampler state. - ID3D11SamplerState* samplers[] = - { + ID3D11SamplerState* samplers[] = { states.LinearWrap(), states.LinearWrap(), }; @@ -225,16 +200,13 @@ void ModelMesh::PrepareForRendering( deviceContext->PSSetSamplers(0, 2, samplers); } - // Draw mesh given worldViewProjection matrices. -_Use_decl_annotations_ -void XM_CALLCONV ModelMesh::Draw( - ID3D11DeviceContext* deviceContext, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - bool alpha, - std::function setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV ModelMesh::Draw(ID3D11DeviceContext* deviceContext, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool alpha, + std::function setCustomState) const { assert(deviceContext != nullptr); @@ -259,17 +231,15 @@ void XM_CALLCONV ModelMesh::Draw( } } - // Draw the mesh using model bones. -_Use_decl_annotations_ -void XM_CALLCONV ModelMesh::Draw( - ID3D11DeviceContext* deviceContext, - size_t nbones, const XMMATRIX* boneTransforms, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - bool alpha, - std::function setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV ModelMesh::Draw(ID3D11DeviceContext* deviceContext, + size_t nbones, + const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool alpha, + std::function setCustomState) const { assert(deviceContext != nullptr); @@ -309,18 +279,15 @@ void XM_CALLCONV ModelMesh::Draw( } } - // Draw mesh using skinning given bone transform array. -_Use_decl_annotations_ -void XM_CALLCONV ModelMesh::DrawSkinned( - ID3D11DeviceContext* deviceContext, - size_t nbones, - const XMMATRIX* boneTransforms, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - bool alpha, - std::function setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV ModelMesh::DrawSkinned(ID3D11DeviceContext* deviceContext, + size_t nbones, + const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool alpha, + std::function setCustomState) const { assert(deviceContext != nullptr); @@ -389,8 +356,7 @@ void XM_CALLCONV ModelMesh::DrawSkinned( else if (imatrices) { // Fallback for if we encounter a non-skinning effect in the model - const XMMATRIX bm = (boneIndex != ModelBone::c_Invalid && boneIndex < nbones) - ? boneTransforms[boneIndex] : XMMatrixIdentity(); + const XMMATRIX bm = (boneIndex != ModelBone::c_Invalid && boneIndex < nbones) ? boneTransforms[boneIndex] : XMMatrixIdentity(); imatrices->SetWorld(XMMatrixMultiply(bm, world)); } @@ -399,19 +365,17 @@ void XM_CALLCONV ModelMesh::DrawSkinned( } } - //-------------------------------------------------------------------------------------- // Model //-------------------------------------------------------------------------------------- -Model::~Model() -{} +Model::~Model() {} -Model::Model(Model const& other) : - meshes(other.meshes), - bones(other.bones), - name(other.name), - mEffectCache(other.mEffectCache) +Model::Model(Model const& other) + : meshes(other.meshes), + bones(other.bones), + name(other.name), + mEffectCache(other.mEffectCache) { const size_t nbones = other.bones.size(); if (nbones > 0) @@ -429,7 +393,7 @@ Model::Model(Model const& other) : } } -Model& Model::operator= (Model const& rhs) +Model& Model::operator=(Model const& rhs) { if (this != &rhs) { @@ -444,24 +408,21 @@ Model& Model::operator= (Model const& rhs) return *this; } - // Draw all meshes in model given worldViewProjection matrices. -_Use_decl_annotations_ -void XM_CALLCONV Model::Draw( - ID3D11DeviceContext* deviceContext, - const CommonStates& states, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - bool wireframe, - std::function setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV Model::Draw(ID3D11DeviceContext* deviceContext, + const CommonStates& states, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool wireframe, + std::function setCustomState) const { assert(deviceContext != nullptr); // Draw opaque parts for (const auto& it : meshes) { - const auto *mesh = it.get(); + const auto* mesh = it.get(); assert(mesh != nullptr); mesh->PrepareForRendering(deviceContext, states, false, wireframe); @@ -472,7 +433,7 @@ void XM_CALLCONV Model::Draw( // Draw alpha parts for (const auto& it : meshes) { - const auto *mesh = it.get(); + const auto* mesh = it.get(); assert(mesh != nullptr); mesh->PrepareForRendering(deviceContext, states, true, wireframe); @@ -481,26 +442,23 @@ void XM_CALLCONV Model::Draw( } } - // Draw all meshes in model using rigid-body animation given bone transform array. -_Use_decl_annotations_ -void XM_CALLCONV Model::Draw( - ID3D11DeviceContext* deviceContext, - const CommonStates& states, - size_t nbones, - const XMMATRIX* boneTransforms, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - bool wireframe, - std::function setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV Model::Draw(ID3D11DeviceContext* deviceContext, + const CommonStates& states, + size_t nbones, + const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool wireframe, + std::function setCustomState) const { assert(deviceContext != nullptr); // Draw opaque parts for (const auto& it : meshes) { - const auto *mesh = it.get(); + const auto* mesh = it.get(); assert(mesh != nullptr); mesh->PrepareForRendering(deviceContext, states, false, wireframe); @@ -511,7 +469,7 @@ void XM_CALLCONV Model::Draw( // Draw alpha parts for (const auto& it : meshes) { - const auto *mesh = it.get(); + const auto* mesh = it.get(); assert(mesh != nullptr); mesh->PrepareForRendering(deviceContext, states, true, wireframe); @@ -520,26 +478,23 @@ void XM_CALLCONV Model::Draw( } } - // Draw all meshes in model using skinning given bone transform array. -_Use_decl_annotations_ -void XM_CALLCONV Model::DrawSkinned( - ID3D11DeviceContext* deviceContext, - const CommonStates& states, - size_t nbones, - const XMMATRIX* boneTransforms, - FXMMATRIX world, - CXMMATRIX view, - CXMMATRIX projection, - bool wireframe, - std::function setCustomState) const +_Use_decl_annotations_ void XM_CALLCONV Model::DrawSkinned(ID3D11DeviceContext* deviceContext, + const CommonStates& states, + size_t nbones, + const XMMATRIX* boneTransforms, + FXMMATRIX world, + CXMMATRIX view, + CXMMATRIX projection, + bool wireframe, + std::function setCustomState) const { assert(deviceContext != nullptr); // Draw opaque parts for (const auto& it : meshes) { - const auto *mesh = it.get(); + const auto* mesh = it.get(); assert(mesh != nullptr); mesh->PrepareForRendering(deviceContext, states, false, wireframe); @@ -550,7 +505,7 @@ void XM_CALLCONV Model::DrawSkinned( // Draw alpha parts for (const auto& it : meshes) { - const auto *mesh = it.get(); + const auto* mesh = it.get(); assert(mesh != nullptr); mesh->PrepareForRendering(deviceContext, states, true, wireframe); @@ -559,12 +514,8 @@ void XM_CALLCONV Model::DrawSkinned( } } - // 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) { @@ -583,18 +534,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) { @@ -613,21 +560,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; @@ -641,27 +585,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) { @@ -686,10 +626,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) { @@ -709,7 +647,6 @@ void Model::CopyBoneTransformsTo(size_t nbones, XMMATRIX* boneTransforms) const memcpy(boneTransforms, boneMatrices.get(), bones.size() * sizeof(XMMATRIX)); } - // Iterate through unique effect instances. void Model::UpdateEffects(_In_ std::function setEffect) { diff --git a/Src/ModelLoadCMO.cpp b/Src/ModelLoadCMO.cpp index 706d077a..6376c15a 100644 --- a/Src/ModelLoadCMO.cpp +++ b/Src/ModelLoadCMO.cpp @@ -22,22 +22,21 @@ using Microsoft::WRL::ComPtr; static_assert(sizeof(VertexPositionNormalTangentColorTexture) == sizeof(VSD3DStarter::Vertex), "mismatch with CMO vertex type"); - namespace { //---------------------------------------------------------------------------------- struct MaterialRecordCMO { - const VSD3DStarter::Material* pMaterial; - std::wstring name; - std::wstring pixelShader; - std::wstring texture[VSD3DStarter::MAX_TEXTURE]; - std::shared_ptr effect; - ComPtr il; - - MaterialRecordCMO() noexcept : - pMaterial(nullptr), - texture{} + const VSD3DStarter::Material* pMaterial; + std::wstring name; + std::wstring pixelShader; + std::wstring texture[VSD3DStarter::MAX_TEXTURE]; + std::shared_ptr effect; + ComPtr il; + + MaterialRecordCMO() noexcept + : pMaterial(nullptr), + texture{} {} }; @@ -46,15 +45,11 @@ namespace { if (skinning) { - ThrowIfFailed( - CreateInputLayoutFromEffect(device, effect, pInputLayout) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(device, effect, pInputLayout)); } else { - ThrowIfFailed( - CreateInputLayoutFromEffect(device, effect, pInputLayout) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(device, effect, pInputLayout)); } assert(pInputLayout != nullptr && *pInputLayout != nullptr); @@ -64,23 +59,23 @@ 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; 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); UNREFERENCED_PARAMETER(lpContext); - g_vbdecl = std::make_shared( - VertexPositionNormalTangentColorTexture::InputElements, + g_vbdecl = std::make_shared(VertexPositionNormalTangentColorTexture::InputElements, VertexPositionNormalTangentColorTexture::InputElements + VertexPositionNormalTangentColorTexture::InputElementCount); - g_vbdeclSkinning = std::make_shared( - VertexPositionNormalTangentColorTextureSkinning::InputElements, - VertexPositionNormalTangentColorTextureSkinning::InputElements + VertexPositionNormalTangentColorTextureSkinning::InputElementCount); + g_vbdeclSkinning + = std::make_shared(VertexPositionNormalTangentColorTextureSkinning::InputElements, + VertexPositionNormalTangentColorTextureSkinning::InputElements + + VertexPositionNormalTangentColorTextureSkinning::InputElementCount); return TRUE; } @@ -89,7 +84,7 @@ namespace if (srgb) { XMVECTOR v = XMVectorSet(r, g, b, 1.f); - v = XMColorSRGBToRGB(v); + v = XMColorSRGBToRGB(v); XMFLOAT3 result; XMStoreFloat3(&result, v); @@ -100,20 +95,18 @@ namespace return XMFLOAT3(r, g, b); } } -} - +} // namespace //====================================================================================== // Model Loader //====================================================================================== -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromCMO( - ID3D11Device* device, - const uint8_t* meshData, size_t dataSize, - IEffectFactory& fxFactory, - ModelLoaderFlags flags, - size_t* animsOffset) +_Use_decl_annotations_ std::unique_ptr Model::CreateFromCMO(ID3D11Device* device, + const uint8_t* meshData, + size_t dataSize, + IEffectFactory& fxFactory, + ModelLoaderFlags flags, + size_t* animsOffset) { if (animsOffset) { @@ -129,7 +122,7 @@ std::unique_ptr Model::CreateFromCMO( auto fxFactoryDGSL = dynamic_cast(&fxFactory); // 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"); @@ -150,15 +143,16 @@ 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"); auto mesh = std::make_shared(); mesh->name.assign(meshName, *nName); - mesh->ccw = (flags & ModelLoader_CounterClockwise) != 0; + mesh->ccw = (flags & ModelLoader_CounterClockwise) != 0; mesh->pmalpha = (flags & ModelLoader_PremultipledAlpha) != 0; // Materials @@ -182,9 +176,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"); @@ -204,9 +199,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"); @@ -219,9 +215,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"); @@ -238,7 +235,7 @@ std::unique_ptr Model::CreateFromCMO( // Add default material if none defined MaterialRecordCMO m; m.pMaterial = &VSD3DStarter::s_defMaterial; - m.name = L"Default"; + m.name = L"Default"; materials.emplace_back(m); } @@ -316,19 +313,17 @@ std::unique_ptr Model::CreateFromCMO( IBData ib; ib.nIndices = *nIndexes; - ib.ptr = indexes; + ib.ptr = indexes; ibData.emplace_back(ib); D3D11_BUFFER_DESC desc = {}; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.ByteWidth = static_cast(ibBytes); - desc.BindFlags = D3D11_BIND_INDEX_BUFFER; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.ByteWidth = static_cast(ibBytes); + desc.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA initData = { indexes, 0, 0 }; - ThrowIfFailed( - device->CreateBuffer(&desc, &initData, &ibs[j]) - ); + ThrowIfFailed(device->CreateBuffer(&desc, &initData, &ibs[j])); SetDebugObjectName(ibs[j].Get(), "ModelCMO"); } @@ -350,9 +345,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; @@ -375,8 +370,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); } @@ -427,7 +422,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); @@ -447,7 +442,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) @@ -458,7 +453,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) @@ -472,7 +468,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) @@ -572,8 +568,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) { @@ -593,18 +589,16 @@ std::unique_ptr Model::CreateFromCMO( const size_t bytes = static_cast(sizeInBytes); D3D11_BUFFER_DESC desc = {}; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.ByteWidth = static_cast(bytes); - desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.ByteWidth = static_cast(bytes); + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; if (fxFactoryDGSL && !enableSkinning) { // Can use CMO vertex data directly D3D11_SUBRESOURCE_DATA initData = { vbData[j].ptr, 0, 0 }; - ThrowIfFailed( - device->CreateBuffer(&desc, &initData, &vbs[j]) - ); + ThrowIfFailed(device->CreateBuffer(&desc, &initData, &vbs[j])); } else { @@ -651,8 +645,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); @@ -683,17 +676,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 } } } @@ -702,9 +696,7 @@ std::unique_ptr Model::CreateFromCMO( // Create vertex buffer from temporary buffer D3D11_SUBRESOURCE_DATA initData = { temp.get(), 0, 0 }; - ThrowIfFailed( - device->CreateBuffer(&desc, &initData, &vbs[j]) - ); + ThrowIfFailed(device->CreateBuffer(&desc, &initData, &vbs[j])); } SetDebugObjectName(vbs[j].Get(), "ModelCMO"); @@ -722,20 +714,20 @@ std::unique_ptr Model::CreateFromCMO( if (fxFactoryDGSL) { DGSLEffectFactory::DGSLEffectInfo info; - info.name = m.name.c_str(); - info.specularPower = m.pMaterial->SpecularPower; - info.perVertexColor = true; - info.enableSkinning = enableSkinning; - info.alpha = 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.diffuseTexture = m.texture[0].empty() ? nullptr : m.texture[0].c_str(); + info.name = m.name.c_str(); + info.specularPower = m.pMaterial->SpecularPower; + info.perVertexColor = true; + info.enableSkinning = enableSkinning; + info.alpha = 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.diffuseTexture = m.texture[0].empty() ? nullptr : m.texture[0].c_str(); info.specularTexture = m.texture[1].empty() ? nullptr : m.texture[1].c_str(); - info.normalTexture = m.texture[2].empty() ? nullptr : m.texture[2].c_str(); + info.normalTexture = m.texture[2].empty() ? nullptr : m.texture[2].c_str(); info.emissiveTexture = m.texture[3].empty() ? nullptr : m.texture[3].c_str(); - info.pixelShader = m.pixelShader.c_str(); + info.pixelShader = m.pixelShader.c_str(); constexpr int offset = DGSLEffectFactory::DGSLEffectInfo::BaseTextureOffset; for (int i = 0; i < (DGSLEffect::MaxTextures - offset); ++i) @@ -751,15 +743,15 @@ std::unique_ptr Model::CreateFromCMO( else { EffectFactory::EffectInfo info; - info.name = m.name.c_str(); - info.specularPower = m.pMaterial->SpecularPower; + info.name = m.name.c_str(); + info.specularPower = m.pMaterial->SpecularPower; info.perVertexColor = true; info.enableSkinning = enableSkinning; - info.alpha = 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.alpha = 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.diffuseTexture = m.texture[0].c_str(); m.effect = fxFactory.CreateEffect(info, nullptr); @@ -773,9 +765,7 @@ 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]; @@ -785,14 +775,14 @@ std::unique_ptr Model::CreateFromCMO( if (mat.pMaterial->Diffuse.w < 1) part->isAlpha = true; - part->indexCount = sm.PrimCount * 3; - part->startIndex = sm.StartIndex; + part->indexCount = sm.PrimCount * 3; + part->startIndex = sm.StartIndex; part->vertexStride = static_cast(stride); - part->inputLayout = mat.il; - part->indexBuffer = ibs[sm.IndexBufferIndex]; + part->inputLayout = mat.il; + part->indexBuffer = ibs[sm.IndexBufferIndex]; part->vertexBuffer = vbs[sm.VertexBufferIndex]; - part->effect = mat.effect; - part->vbDecl = enableSkinning ? g_vbdeclSkinning : g_vbdecl; + part->effect = mat.effect; + part->vbDecl = enableSkinning ? g_vbdeclSkinning : g_vbdecl; mesh->meshParts.emplace_back(std::move(part)); } @@ -803,28 +793,24 @@ std::unique_ptr Model::CreateFromCMO( return model; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromCMO( - ID3D11Device* device, - const wchar_t* szFileName, - IEffectFactory& fxFactory, - ModelLoaderFlags flags, - size_t* animsOffset) +_Use_decl_annotations_ std::unique_ptr Model::CreateFromCMO(ID3D11Device* device, + const wchar_t* szFileName, + IEffectFactory& fxFactory, + 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"); } @@ -835,19 +821,16 @@ 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( - ID3D11Device* device, - const __wchar_t* szFileName, - IEffectFactory& fxFactory, - ModelLoaderFlags flags, - size_t* animsOffset) +_Use_decl_annotations_ std::unique_ptr Model::CreateFromCMO(ID3D11Device* device, + const __wchar_t* szFileName, + IEffectFactory& fxFactory, + ModelLoaderFlags flags, + size_t* animsOffset) { return CreateFromCMO(device, reinterpret_cast(szFileName), fxFactory, flags, animsOffset); } diff --git a/Src/ModelLoadSDKMESH.cpp b/Src/ModelLoadSDKMESH.cpp index 50d4814e..3062a2d4 100644 --- a/Src/ModelLoadSDKMESH.cpp +++ b/Src/ModelLoadSDKMESH.cpp @@ -23,20 +23,22 @@ 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, }; struct MaterialRecordSDKMESH { std::shared_ptr effect; - bool alpha; + bool alpha; - MaterialRecordSDKMESH() noexcept : alpha(false) {} + MaterialRecordSDKMESH() noexcept + : alpha(false) + {} }; inline XMFLOAT3 GetMaterialColor(float r, float g, float b, bool srgb) @@ -44,7 +46,7 @@ namespace if (srgb) { XMVECTOR v = XMVectorSet(r, g, b, 1.f); - v = XMColorSRGBToRGB(v); + v = XMColorSRGBToRGB(v); XMFLOAT3 result; XMStoreFloat3(&result, v); @@ -57,21 +59,17 @@ namespace } template - inline void ASCIIToWChar(wchar_t(&buffer)[sizeOfBuffer], const char *ascii) + inline void ASCIIToWChar(wchar_t (&buffer)[sizeOfBuffer], const char* ascii) { - #ifdef _WIN32 +#ifdef _WIN32 MultiByteToWideChar(CP_UTF8, 0, ascii, -1, buffer, sizeOfBuffer); - #else +#else mbtowc(nullptr, nullptr, 0); mbtowc(buffer, ascii, sizeOfBuffer); - #endif +#endif } - void LoadMaterial(const DXUT::SDKMESH_MATERIAL& mh, - unsigned int flags, - IEffectFactory& fxFactory, - MaterialRecordSDKMESH& m, - bool srgb) + void LoadMaterial(const DXUT::SDKMESH_MATERIAL& mh, unsigned int flags, IEffectFactory& fxFactory, MaterialRecordSDKMESH& m, bool srgb) { wchar_t matName[DXUT::MAX_MATERIAL_NAME] = {}; ASCIIToWChar(matName, mh.Name); @@ -97,24 +95,24 @@ namespace } EffectFactory::EffectInfo info; - info.name = matName; - info.perVertexColor = (flags & PER_VERTEX_COLOR) != 0; - info.enableSkinning = (flags & SKINNING) != 0; - info.enableDualTexture = (flags & DUAL_TEXTURE) != 0; - info.enableNormalMaps = (flags & NORMAL_MAPS) != 0; + info.name = matName; + info.perVertexColor = (flags & PER_VERTEX_COLOR) != 0; + info.enableSkinning = (flags & SKINNING) != 0; + info.enableDualTexture = (flags & DUAL_TEXTURE) != 0; + info.enableNormalMaps = (flags & NORMAL_MAPS) != 0; info.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 info.diffuseColor = XMFLOAT3(1.f, 1.f, 1.f); - info.alpha = 1.f; + info.alpha = 1.f; } else { - info.ambientColor = GetMaterialColor(mh.Ambient.x, mh.Ambient.y, mh.Ambient.z, srgb); - info.diffuseColor = GetMaterialColor(mh.Diffuse.x, mh.Diffuse.y, mh.Diffuse.z, srgb); + info.ambientColor = GetMaterialColor(mh.Ambient.x, mh.Ambient.y, mh.Ambient.z, srgb); + info.diffuseColor = GetMaterialColor(mh.Diffuse.x, mh.Diffuse.y, mh.Diffuse.z, srgb); info.emissiveColor = GetMaterialColor(mh.Emissive.x, mh.Emissive.y, mh.Emissive.z, srgb); if (mh.Diffuse.w != 1.f && mh.Diffuse.w != 0.f) @@ -131,18 +129,15 @@ namespace } } - info.diffuseTexture = diffuseName; + info.diffuseTexture = diffuseName; info.specularTexture = specularName; - info.normalTexture = normalName; + info.normalTexture = normalName; m.effect = fxFactory.CreateEffect(info, nullptr); - m.alpha = (info.alpha < 1.f); + m.alpha = (info.alpha < 1.f); } - void LoadMaterial(const DXUT::SDKMESH_MATERIAL_V2& mh, - unsigned int flags, - IEffectFactory& fxFactory, - MaterialRecordSDKMESH& m) + void LoadMaterial(const DXUT::SDKMESH_MATERIAL_V2& mh, unsigned int flags, IEffectFactory& fxFactory, MaterialRecordSDKMESH& m) { wchar_t matName[DXUT::MAX_MATERIAL_NAME] = {}; ASCIIToWChar(matName, mh.Name); @@ -160,53 +155,48 @@ namespace ASCIIToWChar(emissiveName, mh.EmissiveTexture); EffectFactory::EffectInfo info; - info.name = matName; - info.perVertexColor = false; - info.enableSkinning = (flags & SKINNING) != 0; - info.enableDualTexture = false; - info.enableNormalMaps = true; + info.name = matName; + info.perVertexColor = false; + info.enableSkinning = (flags & SKINNING) != 0; + info.enableDualTexture = false; + info.enableNormalMaps = true; info.biasedVertexNormals = (flags & BIASED_VERTEX_NORMALS) != 0; - info.alpha = (mh.Alpha == 0.f) ? 1.f : mh.Alpha; + info.alpha = (mh.Alpha == 0.f) ? 1.f : mh.Alpha; - info.diffuseTexture = albedoTexture; + info.diffuseTexture = albedoTexture; info.specularTexture = rmaName; - info.normalTexture = normalName; + info.normalTexture = normalName; info.emissiveTexture = emissiveName; m.effect = fxFactory.CreateEffect(info, nullptr); - m.alpha = (info.alpha < 1.f); + m.alpha = (info.alpha < 1.f); } - //-------------------------------------------------------------------------------------- // Direct3D 9 Vertex Declaration to Direct3D 11 Input Layout mapping - #ifndef __MINGW32__ static_assert(D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT >= 32, "SDKMESH supports decls up to 32 entries"); #endif - 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 D3D11_INPUT_ELEMENT_DESC s_elements[] = - { - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "BINORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "BLENDINDICES", 0, DXGI_FORMAT_R8G8B8A8_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "BLENDWEIGHT", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + static const D3D11_INPUT_ELEMENT_DESC s_elements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "BINORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "BLENDINDICES", 0, DXGI_FORMAT_R8G8B8A8_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "BLENDWEIGHT", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_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; @@ -232,9 +222,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) @@ -247,24 +236,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) - 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) + 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) @@ -279,16 +300,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) @@ -301,21 +338,37 @@ namespace else if (decl[index].Usage == D3DDECLUSAGE_TEXCOORD) { D3D11_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) @@ -361,20 +414,17 @@ namespace return flags; } -} - +} // namespace //====================================================================================== // Model Loader //====================================================================================== -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromSDKMESH( - ID3D11Device* d3dDevice, - const uint8_t* meshData, - size_t idataSize, - IEffectFactory& fxFactory, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr Model::CreateFromSDKMESH(ID3D11Device* d3dDevice, + const uint8_t* meshData, + size_t idataSize, + IEffectFactory& fxFactory, + ModelLoaderFlags flags) { if (!d3dDevice || !meshData) throw std::invalid_argument("Device and meshData cannot be null"); @@ -387,8 +437,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"); @@ -421,8 +471,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); @@ -430,8 +479,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); @@ -439,8 +487,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); @@ -448,8 +495,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); @@ -460,8 +506,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) @@ -474,11 +519,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) { @@ -491,8 +535,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; @@ -520,11 +563,10 @@ std::unique_ptr Model::CreateFromSDKMESH( throw std::runtime_error("VB too large for DirectX 11"); } - 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) @@ -546,22 +588,21 @@ std::unique_ptr Model::CreateFromSDKMESH( auto verts = bufferData + (vh.DataOffset - bufferDataOffset); D3D11_BUFFER_DESC desc = {}; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.ByteWidth = static_cast(vh.SizeBytes); - desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.ByteWidth = static_cast(vh.SizeBytes); + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA initData = { verts, 0, 0 }; - ThrowIfFailed( - d3dDevice->CreateBuffer(&desc, &initData, &vbs[j]) - ); + ThrowIfFailed(d3dDevice->CreateBuffer(&desc, &initData, &vbs[j])); SetDebugObjectName(vbs[j].Get(), "ModelSDKMESH"); } 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"); } @@ -582,8 +623,7 @@ std::unique_ptr Model::CreateFromSDKMESH( throw std::runtime_error("IB too large for DirectX 11"); } - 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) @@ -592,15 +632,13 @@ std::unique_ptr Model::CreateFromSDKMESH( auto indices = bufferData + (ih.DataOffset - bufferDataOffset); D3D11_BUFFER_DESC desc = {}; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.ByteWidth = static_cast(ih.SizeBytes); - desc.BindFlags = D3D11_BIND_INDEX_BUFFER; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.ByteWidth = static_cast(ih.SizeBytes); + desc.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA initData = { indices, 0, 0 }; - ThrowIfFailed( - d3dDevice->CreateBuffer(&desc, &initData, &ibs[j]) - ); + ThrowIfFailed(d3dDevice->CreateBuffer(&desc, &initData, &ibs[j])); SetDebugObjectName(ibs[j].Get(), "ModelSDKMESH"); } @@ -616,9 +654,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"); @@ -628,8 +664,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); @@ -641,8 +676,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) @@ -651,15 +685,15 @@ 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; - mesh->ccw = (flags & ModelLoader_CounterClockwise) != 0; + mesh->name = meshName; + mesh->ccw = (flags & ModelLoader_CounterClockwise) != 0; mesh->pmalpha = (flags & ModelLoader_PremultipledAlpha) != 0; // Extents - mesh->boundingBox.Center = mh.BoundingBoxCenter; + mesh->boundingBox.Center = mh.BoundingBoxCenter; mesh->boundingBox.Extents = mh.BoundingBoxExtents; BoundingSphere::CreateFromBoundingBox(mesh->boundingSphere, mesh->boundingBox); @@ -682,22 +716,20 @@ std::unique_ptr Model::CreateFromSDKMESH( D3D11_PRIMITIVE_TOPOLOGY primType; switch (subset.PrimitiveType) { - case DXUT::PT_TRIANGLE_LIST: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; - case DXUT::PT_TRIANGLE_STRIP: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; - case DXUT::PT_LINE_LIST: primType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST; break; - case DXUT::PT_LINE_STRIP: primType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP; break; - case DXUT::PT_POINT_LIST: primType = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; break; - case DXUT::PT_TRIANGLE_LIST_ADJ: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; break; - case DXUT::PT_TRIANGLE_STRIP_ADJ: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; break; - case DXUT::PT_LINE_LIST_ADJ: primType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; break; - case DXUT::PT_LINE_STRIP_ADJ: primType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; break; + case DXUT::PT_TRIANGLE_LIST: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; + case DXUT::PT_TRIANGLE_STRIP: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; + case DXUT::PT_LINE_LIST: primType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST; break; + case DXUT::PT_LINE_STRIP: primType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP; break; + case DXUT::PT_POINT_LIST: primType = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; break; + case DXUT::PT_TRIANGLE_LIST_ADJ: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; break; + case DXUT::PT_TRIANGLE_STRIP_ADJ: primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; break; + case DXUT::PT_LINE_LIST_ADJ: primType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; break; + case DXUT::PT_LINE_STRIP_ADJ: primType = D3D11_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) @@ -711,16 +743,11 @@ std::unique_ptr Model::CreateFromSDKMESH( if (materialArray_v2) { - LoadMaterial( - materialArray_v2[subset.MaterialID], - materialFlags[vi], - fxFactory, - mat); + LoadMaterial(materialArray_v2[subset.MaterialID], materialFlags[vi], fxFactory, mat); } else { - LoadMaterial( - materialArray[subset.MaterialID], + LoadMaterial(materialArray[subset.MaterialID], materialFlags[vi], fxFactory, mat, @@ -729,27 +756,28 @@ std::unique_ptr Model::CreateFromSDKMESH( } ComPtr il; - ThrowIfFailed( - CreateInputLayoutFromEffect(d3dDevice, mat.effect.get(), - vbDecls[mh.VertexBuffers[0]]->data(), vbDecls[mh.VertexBuffers[0]]->size(), il.GetAddressOf()) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(d3dDevice, + mat.effect.get(), + vbDecls[mh.VertexBuffers[0]]->data(), + vbDecls[mh.VertexBuffers[0]]->size(), + il.GetAddressOf())); SetDebugObjectName(il.Get(), "ModelSDKMESH"); - auto part = std::make_unique(); + auto part = std::make_unique(); part->isAlpha = mat.alpha; - part->indexCount = static_cast(subset.IndexCount); - part->startIndex = static_cast(subset.IndexStart); - part->vertexOffset = static_cast(subset.VertexStart); - part->vertexStride = static_cast(vbArray[mh.VertexBuffers[0]].StrideBytes); - part->indexFormat = (ibArray[mh.IndexBuffer].IndexType == DXUT::IT_32BIT) ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; + part->indexCount = static_cast(subset.IndexCount); + part->startIndex = static_cast(subset.IndexStart); + part->vertexOffset = static_cast(subset.VertexStart); + part->vertexStride = static_cast(vbArray[mh.VertexBuffers[0]].StrideBytes); + part->indexFormat = (ibArray[mh.IndexBuffer].IndexType == DXUT::IT_32BIT) ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; part->primitiveType = primType; - part->inputLayout = il; - part->indexBuffer = ibs[mh.IndexBuffer]; - part->vertexBuffer = vbs[mh.VertexBuffers[0]]; - part->effect = mat.effect; - part->vbDecl = vbDecls[mh.VertexBuffers[0]]; + part->inputLayout = il; + part->indexBuffer = ibs[mh.IndexBuffer]; + part->vertexBuffer = vbs[mh.VertexBuffers[0]]; + part->effect = mat.effect; + part->vbDecl = vbDecls[mh.VertexBuffers[0]]; mesh->meshParts.emplace_back(std::move(part)); } @@ -768,10 +796,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); @@ -815,22 +840,16 @@ std::unique_ptr Model::CreateFromSDKMESH( return model; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromSDKMESH( - ID3D11Device* device, - const wchar_t* szFileName, - IEffectFactory& fxFactory, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr +Model::CreateFromSDKMESH(ID3D11Device* device, const wchar_t* szFileName, IEffectFactory& fxFactory, 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"); } @@ -841,19 +860,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( - ID3D11Device* device, - const __wchar_t* szFileName, - IEffectFactory& fxFactory, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr +Model::CreateFromSDKMESH(ID3D11Device* device, const __wchar_t* szFileName, IEffectFactory& fxFactory, ModelLoaderFlags flags) { return CreateFromSDKMESH(device, reinterpret_cast(szFileName), fxFactory, flags); } diff --git a/Src/ModelLoadVBO.cpp b/Src/ModelLoadVBO.cpp index ee240262..0f4b254d 100644 --- a/Src/ModelLoadVBO.cpp +++ b/Src/ModelLoadVBO.cpp @@ -26,31 +26,28 @@ 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); UNREFERENCED_PARAMETER(lpContext); - g_vbdecl = std::make_shared( - VertexPositionNormalTexture::InputElements, + g_vbdecl = std::make_shared(VertexPositionNormalTexture::InputElements, VertexPositionNormalTexture::InputElements + VertexPositionNormalTexture::InputElementCount); return TRUE; } -} - +} // namespace //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromVBO( - ID3D11Device* device, - const uint8_t* meshData, size_t dataSize, - std::shared_ptr ieffect, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr Model::CreateFromVBO(ID3D11Device* device, + const uint8_t* meshData, + size_t dataSize, + std::shared_ptr ieffect, + ModelLoaderFlags flags) { if (!InitOnceExecuteOnce(&g_InitOnce, InitializeDecl, nullptr, nullptr)) throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "InitOnceExecuteOnce"); @@ -104,15 +101,13 @@ std::unique_ptr Model::CreateFromVBO( ComPtr vb; { D3D11_BUFFER_DESC desc = {}; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.ByteWidth = static_cast(vertSize); - desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.ByteWidth = static_cast(vertSize); + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA initData = { verts, 0, 0 }; - ThrowIfFailed( - device->CreateBuffer(&desc, &initData, vb.GetAddressOf()) - ); + ThrowIfFailed(device->CreateBuffer(&desc, &initData, vb.GetAddressOf())); SetDebugObjectName(vb.Get(), "ModelVBO"); } @@ -121,15 +116,13 @@ std::unique_ptr Model::CreateFromVBO( ComPtr ib; { D3D11_BUFFER_DESC desc = {}; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.ByteWidth = static_cast(indexSize); - desc.BindFlags = D3D11_BIND_INDEX_BUFFER; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.ByteWidth = static_cast(indexSize); + desc.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA initData = { indices, 0, 0 }; - ThrowIfFailed( - device->CreateBuffer(&desc, &initData, ib.GetAddressOf()) - ); + ThrowIfFailed(device->CreateBuffer(&desc, &initData, ib.GetAddressOf())); SetDebugObjectName(ib.Get(), "ModelVBO"); } @@ -146,24 +139,22 @@ std::unique_ptr Model::CreateFromVBO( ComPtr il; - ThrowIfFailed( - CreateInputLayoutFromEffect(device, ieffect.get(), il.GetAddressOf()) - ); + ThrowIfFailed(CreateInputLayoutFromEffect(device, ieffect.get(), il.GetAddressOf())); SetDebugObjectName(il.Get(), "ModelVBO"); - auto part = std::make_unique(); - part->indexCount = header->numIndices; - part->startIndex = 0; + auto part = std::make_unique(); + part->indexCount = header->numIndices; + part->startIndex = 0; part->vertexStride = static_cast(sizeof(VertexPositionNormalTexture)); - part->inputLayout = il; - part->indexBuffer = ib; + part->inputLayout = il; + part->indexBuffer = ib; part->vertexBuffer = vb; - part->effect = ieffect; - part->vbDecl = g_vbdecl; + part->effect = ieffect; + part->vbDecl = g_vbdecl; - auto mesh = std::make_shared(); - mesh->ccw = (flags & ModelLoader_CounterClockwise) != 0; + auto mesh = std::make_shared(); + mesh->ccw = (flags & ModelLoader_CounterClockwise) != 0; mesh->pmalpha = (flags & ModelLoader_PremultipledAlpha) != 0; BoundingSphere::CreateFromPoints(mesh->boundingSphere, header->numVertices, &verts->position, sizeof(VertexPositionNormalTexture)); BoundingBox::CreateFromPoints(mesh->boundingBox, header->numVertices, &verts->position, sizeof(VertexPositionNormalTexture)); @@ -177,22 +168,16 @@ std::unique_ptr Model::CreateFromVBO( return model; } - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -std::unique_ptr Model::CreateFromVBO( - ID3D11Device* device, - const wchar_t* szFileName, - std::shared_ptr ieffect, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr +Model::CreateFromVBO(ID3D11Device* device, const wchar_t* szFileName, std::shared_ptr ieffect, 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"); } @@ -203,18 +188,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( - ID3D11Device* device, - const __wchar_t* szFileName, - std::shared_ptr ieffect, - ModelLoaderFlags flags) +_Use_decl_annotations_ std::unique_ptr +Model::CreateFromVBO(ID3D11Device* device, const __wchar_t* szFileName, std::shared_ptr ieffect, ModelLoaderFlags flags) { return CreateFromVBO(device, reinterpret_cast(szFileName), ieffect, 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 d6bcd610..7f55995d 100644 --- a/Src/NPREffect.cpp +++ b/Src/NPREffect.cpp @@ -16,7 +16,7 @@ namespace DirectX { constexpr int ConstantBufferBones = 0x100000; } -} +} // namespace DirectX using namespace DirectX; @@ -52,23 +52,22 @@ namespace { using ConstantBufferType = NPREffectConstants; - static constexpr int VertexShaderCount = 18; - static constexpr int PixelShaderCount = 6; + static constexpr int VertexShaderCount = 18; + static constexpr int PixelShaderCount = 6; static constexpr int ShaderPermutationCount = 54; static constexpr int ModeCount = 3; }; - // 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 @@ -76,10 +75,10 @@ class NPREffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* 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_ ID3D11Device* device, bool enableSkinning); @@ -88,9 +87,9 @@ class NPREffect::Impl : public EffectBase bool biasedVertexNormals; bool instancing; bool textureEnabled; - int weightsPerVertex; + int weightsPerVertex; - NPREffect::Mode nprMode; + NPREffect::Mode nprMode; Microsoft::WRL::ComPtr matcap; int GetCurrentShaderPermutation() const noexcept; @@ -103,7 +102,6 @@ class NPREffect::Impl : public EffectBase ConstantBuffer mBones; }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -181,196 +179,188 @@ namespace #include "NPREffect_PSMatCapShading.inc" #include "NPREffect_PSMatCapShadingTx.inc" #endif -} - +} // namespace template<> -const ShaderBytecode 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_VSSkinnedNPREffectTx, sizeof(NPREffect_VSSkinnedNPREffectTx) }, +const ShaderBytecode 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_VSSkinnedNPREffectTx, sizeof(NPREffect_VSSkinnedNPREffectTx) }, { NPREffect_VSSkinnedNPREffectTxBn, sizeof(NPREffect_VSSkinnedNPREffectTxBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // cel shading - 0, // gooch shading - 0, // matcap shading - - 1, // vertex color + cel shading - 1, // vertex color + gooch shading - 1, // vertex color + matcap shading - - 2, // cel shading (biased vertex normal) - 2, // gooch shading (biased vertex normal) - 2, // matcap shading (biased vertex normal) - - 3, // vertex color (biased vertex normal) + cel shading - 3, // vertex color (biased vertex normal) + gooch shading - 3, // vertex color (biased vertex normal) + matcap shading - - 4, // instancing + cel shading - 4, // instancing + gooch shading - 4, // instancing + matcap shading - - 5, // instancing + vertex color + cel shading - 5, // instancing + vertex color + gooch shading - 5, // instancing + vertex color + matcap shading - - 6, // instancing (biased vertex normal) + cel shading - 6, // instancing (biased vertex normal) + gooch shading - 6, // instancing (biased vertex normal) + matcap shading - - 7, // instancing + vertex color (biased vertex normal) + cel shading - 7, // instancing + vertex color (biased vertex normal) + gooch shading - 7, // instancing + vertex color (biased vertex normal) + matcap shading - - 8, // cel shading + texture - 8, // gooch shading + texture - 8, // matcap shading + texture - - 9, // vertex color + cel shading + texture - 9, // vertex color + gooch shading + texture - 9, // vertex color + matcap shading + texture - - 10, // cel shading (biased vertex normal) + texture - 10, // gooch shading (biased vertex normal) + texture - 10, // matcap shading (biased vertex normal) + texture - - 11, // vertex color (biased vertex normal) + cel shading + texture - 11, // vertex color (biased vertex normal) + gooch shading + texture - 11, // vertex color (biased vertex normal) + matcap shading + texture - - 12, // instancing + cel shading + texture - 12, // instancing + gooch shading + texture - 12, // instancing + matcap shading + texture - - 13, // instancing + vertex color + cel shading + texture - 13, // instancing + vertex color + gooch shading + texture - 13, // instancing + vertex color + matcap shading + texture - - 14, // instancing (biased vertex normal) + cel shading + texture - 14, // instancing (biased vertex normal) + gooch shading + texture - 14, // 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 - 15, // instancing + vertex color (biased vertex normal) + matcap shading + texture - - 16, // skinning + cel shading - 16, // skinning + gooch shading - 16, // skinning + matcap shading - - 17, // skinning (biased vertex normal) + cel shading - 17, // skinning (biased vertex normal) + gooch shading - 17, // skinning (biased vertex normal) + matcap shading +const int EffectBase::VertexShaderIndices[] = { + 0, // cel shading + 0, // gooch shading + 0, // matcap shading + + 1, // vertex color + cel shading + 1, // vertex color + gooch shading + 1, // vertex color + matcap shading + + 2, // cel shading (biased vertex normal) + 2, // gooch shading (biased vertex normal) + 2, // matcap shading (biased vertex normal) + + 3, // vertex color (biased vertex normal) + cel shading + 3, // vertex color (biased vertex normal) + gooch shading + 3, // vertex color (biased vertex normal) + matcap shading + + 4, // instancing + cel shading + 4, // instancing + gooch shading + 4, // instancing + matcap shading + + 5, // instancing + vertex color + cel shading + 5, // instancing + vertex color + gooch shading + 5, // instancing + vertex color + matcap shading + + 6, // instancing (biased vertex normal) + cel shading + 6, // instancing (biased vertex normal) + gooch shading + 6, // instancing (biased vertex normal) + matcap shading + + 7, // instancing + vertex color (biased vertex normal) + cel shading + 7, // instancing + vertex color (biased vertex normal) + gooch shading + 7, // instancing + vertex color (biased vertex normal) + matcap shading + + 8, // cel shading + texture + 8, // gooch shading + texture + 8, // matcap shading + texture + + 9, // vertex color + cel shading + texture + 9, // vertex color + gooch shading + texture + 9, // vertex color + matcap shading + texture + + 10, // cel shading (biased vertex normal) + texture + 10, // gooch shading (biased vertex normal) + texture + 10, // matcap shading (biased vertex normal) + texture + + 11, // vertex color (biased vertex normal) + cel shading + texture + 11, // vertex color (biased vertex normal) + gooch shading + texture + 11, // vertex color (biased vertex normal) + matcap shading + texture + + 12, // instancing + cel shading + texture + 12, // instancing + gooch shading + texture + 12, // instancing + matcap shading + texture + + 13, // instancing + vertex color + cel shading + texture + 13, // instancing + vertex color + gooch shading + texture + 13, // instancing + vertex color + matcap shading + texture + + 14, // instancing (biased vertex normal) + cel shading + texture + 14, // instancing (biased vertex normal) + gooch shading + texture + 14, // 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 + 15, // instancing + vertex color (biased vertex normal) + matcap shading + texture + + 16, // skinning + cel shading + 16, // skinning + gooch shading + 16, // skinning + matcap shading + + 17, // skinning (biased vertex normal) + cel shading + 17, // skinning (biased vertex normal) + gooch shading + 17, // skinning (biased vertex normal) + matcap shading }; - template<> -const ShaderBytecode 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) }, +const ShaderBytecode 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) }, }; - 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 - - 3, // skinning + cel shading - 4, // skinning + gooch shading - 5, // skinning + matcap shading - - 3, // skinning (biased vertex normal) + cel shading - 4, // skinning (biased vertex normal) + gooch shading - 5, // 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 + + 3, // skinning + cel shading + 4, // skinning + gooch shading + 5, // skinning + matcap shading + + 3, // skinning (biased vertex normal) + cel shading + 4, // skinning (biased vertex normal) + gooch shading + 5, // skinning (biased vertex normal) + matcap shading }; #pragma endregion @@ -378,37 +368,40 @@ const int EffectBase::PixelShaderIndices[] = template<> SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool = {}; - // Constructor. NPREffect::Impl::Impl(_In_ ID3D11Device* device) : EffectBase(device), - vertexColorEnabled(false), - biasedVertexNormals(false), - instancing(false), - textureEnabled(false), - weightsPerVertex(0), - nprMode(NPREffect::Mode_Cel) -{ - 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"); + vertexColorEnabled(false), + biasedVertexNormals(false), + instancing(false), + textureEnabled(false), + weightsPerVertex(0), + nprMode(NPREffect::Mode_Cel) +{ + 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_ ID3D11Device* device, bool enableSkinning) { - 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) { - textureEnabled = true; + textureEnabled = true; weightsPerVertex = 4; mBones.Create(device); @@ -467,23 +460,17 @@ int NPREffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void NPREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { assert(deviceContext != nullptr); // 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); if (weightsPerVertex > 0) { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) void* grfxMemoryBone; mBones.SetData(deviceContext, boneConstants, &grfxMemoryBone); @@ -491,7 +478,7 @@ void NPREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ThrowIfFailed(deviceContext->QueryInterface(IID_GRAPHICS_PPV_ARGS(deviceContextX.GetAddressOf()))); deviceContextX->VSSetPlacementConstantBuffer(1, mBones.GetBuffer(), grfxMemoryBone); - #else +#else if (dirtyFlags & EffectDirtyFlags::ConstantBufferBones) { mBones.SetData(deviceContext, boneConstants); @@ -500,7 +487,7 @@ void NPREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ID3D11Buffer* buffer = mBones.GetBuffer(); deviceContext->VSSetConstantBuffers(1, 1, &buffer); - #endif +#endif } // Set texture. @@ -532,7 +519,6 @@ void NPREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - // Public constructor. NPREffect::NPREffect(_In_ ID3D11Device* device, bool skinningEnabled) : pImpl(std::make_unique(device)) @@ -540,10 +526,9 @@ NPREffect::NPREffect(_In_ ID3D11Device* device, bool skinningEnabled) pImpl->Initialize(device, 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_ ID3D11DeviceContext* deviceContext) @@ -551,13 +536,11 @@ void NPREffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void NPREffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV NPREffect::SetWorld(FXMMATRIX value) { @@ -566,7 +549,6 @@ void XM_CALLCONV NPREffect::SetWorld(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::WorldInverseTranspose; } - void XM_CALLCONV NPREffect::SetView(FXMMATRIX value) { pImpl->matrices.view = value; @@ -574,7 +556,6 @@ void XM_CALLCONV NPREffect::SetView(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj | EffectDirtyFlags::EyePosition; } - void XM_CALLCONV NPREffect::SetProjection(FXMMATRIX value) { pImpl->matrices.projection = value; @@ -582,42 +563,36 @@ void XM_CALLCONV NPREffect::SetProjection(FXMMATRIX value) pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; } - void XM_CALLCONV 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::SetLightingEnabled(bool) { // Unsupported interface. } - void NPREffect::SetPerPixelLighting(bool) { // Unsupported interface. } - void NPREffect::SetAmbientLightColor(FXMVECTOR) { // Unsupported interface. } - void NPREffect::SetLightEnabled(int, bool) { // Unsupported interface. } - void NPREffect::SetLightDirection(int whichLight, FXMVECTOR value) { if (whichLight != 0) @@ -632,28 +607,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) { @@ -663,16 +635,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) @@ -694,7 +665,6 @@ void NPREffect::SetSpecularThreshold(float threshold, float smoothing) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::DisableSpecular() { // Set specular color to black, threshold to 1 @@ -703,7 +673,6 @@ void NPREffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetAlpha(float value) { // Set w of diffuseColorAndAlpha. @@ -712,7 +681,6 @@ void NPREffect::SetAlpha(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetColorAndAlpha(FXMVECTOR value) { pImpl->constants.diffuseColorAndAlpha = value; @@ -720,7 +688,6 @@ void NPREffect::SetColorAndAlpha(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void NPREffect::SetTextureEnabled(bool value) { @@ -732,13 +699,11 @@ void NPREffect::SetTextureEnabled(bool value) pImpl->textureEnabled = value; } - void NPREffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - // Shader mode setting. void NPREffect::SetMode(Mode mode) { @@ -750,7 +715,6 @@ void NPREffect::SetMode(Mode mode) pImpl->nprMode = mode; } - // Cel shading setting. void NPREffect::SetCelShaderBands(int bands) { @@ -765,7 +729,6 @@ void NPREffect::SetCelShaderBands(int bands) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Gooch shading settings. void NPREffect::SetGoochCoolColor(FXMVECTOR value, float alpha) { @@ -774,7 +737,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); @@ -782,14 +744,12 @@ void NPREffect::SetGoochWarmColor(FXMVECTOR value, float beta) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // MatCap shading setting. void NPREffect::SetMatCap(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->matcap = value; } - // Rim lighting settings. void NPREffect::SetRimLightingColor(FXMVECTOR value) { @@ -799,7 +759,6 @@ void NPREffect::SetRimLightingColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetRimLightingPower(float power) { // Set w of rimColorAndPower. @@ -808,7 +767,6 @@ void NPREffect::SetRimLightingPower(float power) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NPREffect::SetRimLightingIntensity(float strength) { if (strength < 0.f || strength > 1.f) @@ -822,7 +780,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) @@ -831,13 +788,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; @@ -856,14 +812,12 @@ void NPREffect::SetVertexColorEnabled(bool value) pImpl->vertexColorEnabled = value; } - // Normal compression settings. void NPREffect::SetBiasedVertexNormals(bool value) { pImpl->biasedVertexNormals = value; } - // Instancing settings. void NPREffect::SetInstancingEnabled(bool value) { @@ -875,20 +829,16 @@ void NPREffect::SetInstancingEnabled(bool value) pImpl->instancing = value; } - //-------------------------------------------------------------------------------------- // SkinnedNPREffect //-------------------------------------------------------------------------------------- -SkinnedNPREffect::~SkinnedNPREffect() -{} +SkinnedNPREffect::~SkinnedNPREffect() {} // Animation settings. void SkinnedNPREffect::SetWeightsPerVertex(int value) { - if ((value != 1) && - (value != 2) && - (value != 4)) + if ((value != 1) && (value != 2) && (value != 4)) { throw std::invalid_argument("WeightsPerVertex must be 1, 2, or 4"); } @@ -896,7 +846,6 @@ void SkinnedNPREffect::SetWeightsPerVertex(int value) pImpl->weightsPerVertex = value; } - void SkinnedNPREffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (count > MaxBones) @@ -906,22 +855,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 95139786..e15fc2a4 100644 --- a/Src/NPREffectFactory.cpp +++ b/Src/NPREffectFactory.cpp @@ -49,7 +49,7 @@ namespace effect->SetBiasedVertexNormals(true); } } -} +} // namespace // Internal NPREffectFactory implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing NPREffectFactory instances. @@ -58,24 +58,27 @@ class NPREffectFactory::Impl public: explicit Impl(_In_ ID3D11Device* device) : mPath{}, - mMode(NPREffect::Mode_Cel), - mDevice(device), - mSharing(true), - mForceSRGB(false), - mUseEmissiveForMatCap(true) + mMode(NPREffect::Mode_Cel), + mDevice(device), + mSharing(true), + mForceSRGB(false), + mUseEmissiveForMatCap(true) { if (!device) throw std::invalid_argument("Direct3D device is null"); } - 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(_In_ NPREffectFactory* factory, _In_ const EffectFactory::EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); - void CreateTexture(_In_z_ const wchar_t* texture, _In_opt_ ID3D11DeviceContext* deviceContext, _Outptr_ ID3D11ShaderResourceView** textureView); + std::shared_ptr + CreateEffect(_In_ NPREffectFactory* factory, _In_ const EffectFactory::EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); + void CreateTexture(_In_z_ const wchar_t* texture, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView); void ReleaseCache(); @@ -86,15 +89,15 @@ class NPREffectFactory::Impl NPREffect::Mode mMode; ComPtr mMatCap; - ComPtr mDevice; + ComPtr mDevice; bool mSharing; bool mForceSRGB; bool mUseEmissiveForMatCap; private: - using EffectCache = std::map< std::wstring, std::shared_ptr >; - using TextureCache = std::map< std::wstring, ComPtr >; + using EffectCache = std::map>; + using TextureCache = std::map>; EffectCache mEffectCache; EffectCache mEffectCacheSkinning; @@ -104,13 +107,11 @@ class NPREffectFactory::Impl std::mutex mutex; }; - // Global instance pool. SharedResourcePool NPREffectFactory::Impl::instancePool; - -_Use_decl_annotations_ -std::shared_ptr NPREffectFactory::Impl::CreateEffect(NPREffectFactory* factory, const EffectFactory::EffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr +NPREffectFactory::Impl::CreateEffect(NPREffectFactory* factory, const EffectFactory::EffectInfo& info, ID3D11DeviceContext* deviceContext) { if (info.enableSkinning) { @@ -152,7 +153,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect(NPREffectFactory* if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCacheSkinning.insert(v); } @@ -214,7 +215,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect(NPREffectFactory* if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCacheDualTexture.insert(v); } @@ -260,7 +261,7 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect(NPREffectFactory* if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCache.insert(v); } @@ -268,8 +269,8 @@ std::shared_ptr NPREffectFactory::Impl::CreateEffect(NPREffectFactory* } } -_Use_decl_annotations_ -void NPREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +NPREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { if (!name || !textureView) throw std::invalid_argument("name and textureView parameters can't be null"); @@ -300,7 +301,8 @@ void NPREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCont if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: NPREffectFactory could not find texture file '%ls'\n", name); - throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "NPREffectFactory::CreateTexture"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), + "NPREffectFactory::CreateTexture"); } } @@ -310,43 +312,59 @@ void NPREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCont if (isdds) { - HRESULT hr = CreateDDSTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateDDSTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, + nullptr, + textureView); 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("NPREffectFactory::CreateDDSTextureFromFile"); } } - #if !defined(_XBOX_ONE) || !defined(_TITLE) +#if !defined(_XBOX_ONE) || !defined(_TITLE) else if (deviceContext) { std::lock_guard lock(mutex); - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), deviceContext, fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + deviceContext, + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("NPREffectFactory::CreateWICTextureFromFile"); } } - #endif +#endif else { - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("NPREffectFactory::CreateWICTextureFromFile"); } } @@ -354,7 +372,7 @@ void NPREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCont if (mSharing && *name && it == mTextureCache.end()) { std::lock_guard lock(mutex); - TextureCache::value_type v(name, *textureView); + TextureCache::value_type v(name, *textureView); mTextureCache.insert(v); } } @@ -369,8 +387,6 @@ void NPREffectFactory::Impl::ReleaseCache() mTextureCache.clear(); } - - //-------------------------------------------------------------------------------------- // NPREffectFactory //-------------------------------------------------------------------------------------- @@ -379,20 +395,17 @@ NPREffectFactory::NPREffectFactory(_In_ ID3D11Device* device) : pImpl(Impl::instancePool.DemandCreate(device)) {} +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; - - -_Use_decl_annotations_ -std::shared_ptr NPREffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr NPREffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) { return pImpl->CreateEffect(this, info, deviceContext); } -_Use_decl_annotations_ -void NPREffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +NPREffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { return pImpl->CreateTexture(name, deviceContext, textureView); } @@ -423,7 +436,7 @@ void NPREffectFactory::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; } } @@ -442,13 +455,11 @@ void NPREffectFactory::SetDefaultMatCap(_In_opt_ ID3D11ShaderResourceView* textu pImpl->mMatCap = textureView; } - void NPREffectFactory::SetEmissiveAsMatCap(bool value) noexcept { pImpl->mUseEmissiveForMatCap = value; } - ID3D11Device* NPREffectFactory::GetDevice() const noexcept { return pImpl->mDevice.Get(); diff --git a/Src/NormalMapEffect.cpp b/Src/NormalMapEffect.cpp index e98dfb2f..d462de20 100644 --- a/Src/NormalMapEffect.cpp +++ b/Src/NormalMapEffect.cpp @@ -16,7 +16,7 @@ namespace DirectX { constexpr int ConstantBufferBones = 0x100000; } -} +} // namespace DirectX using namespace DirectX; using Microsoft::WRL::ComPtr; @@ -58,11 +58,11 @@ namespace { using ConstantBufferType = NormalMapEffectConstants; - static constexpr int VertexShaderCount = 10; - static constexpr int PixelShaderCount = 4; + static constexpr int VertexShaderCount = 10; + static constexpr int PixelShaderCount = 4; static constexpr int ShaderPermutationCount = 40; }; -} +} // namespace // Internal NormalMapEffect implementation class. class NormalMapEffect::Impl : public EffectBase @@ -70,10 +70,10 @@ class NormalMapEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* 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_ ID3D11Device* device, bool enableSkinning); @@ -84,7 +84,7 @@ class NormalMapEffect::Impl : public EffectBase bool vertexColorEnabled; bool biasedVertexNormals; bool instancing; - int weightsPerVertex; + int weightsPerVertex; EffectLights lights; @@ -98,7 +98,6 @@ class NormalMapEffect::Impl : public EffectBase ConstantBuffer mBones; }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -144,172 +143,175 @@ namespace #include "NormalMapEffect_PSNormalPixelLightingTxNoSpec.inc" #include "NormalMapEffect_PSNormalPixelLightingTxNoFogSpec.inc" #endif -} - +} // namespace template<> -const ShaderBytecode EffectBase::VertexShaderBytecode[] = -{ - { NormalMapEffect_VSNormalPixelLightingTx, sizeof(NormalMapEffect_VSNormalPixelLightingTx) }, - { NormalMapEffect_VSNormalPixelLightingTxVc, sizeof(NormalMapEffect_VSNormalPixelLightingTxVc) }, +const ShaderBytecode 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_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_VSNormalPixelLightingTxBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxBnInst) }, { NormalMapEffect_VSNormalPixelLightingTxVcBnInst, sizeof(NormalMapEffect_VSNormalPixelLightingTxVcBnInst) }, - { NormalMapEffect_VSSkinnedPixelLightingTx, sizeof(NormalMapEffect_VSSkinnedPixelLightingTx) }, - { NormalMapEffect_VSSkinnedPixelLightingTxBn, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxBn) }, + { NormalMapEffect_VSSkinnedPixelLightingTx, sizeof(NormalMapEffect_VSSkinnedPixelLightingTx) }, + { NormalMapEffect_VSSkinnedPixelLightingTxBn, sizeof(NormalMapEffect_VSSkinnedPixelLightingTxBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // pixel lighting + texture - 0, // pixel lighting + texture, no fog - 0, // pixel lighting + texture, no specular - 0, // pixel lighting + texture, no fog or specular - - 2, // pixel lighting (biased vertex normal) + texture - 2, // pixel lighting (biased vertex normal) + texture, no fog - 2, // pixel lighting (biased vertex normal) + texture, no specular - 2, // pixel lighting (biased vertex normal) + texture, no fog or specular - - 1, // pixel lighting + texture + vertex color - 1, // pixel lighting + texture + vertex color, no fog - 1, // pixel lighting + texture + vertex color, no specular - 1, // 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 - 3, // pixel lighting (biased vertex normal) + texture + vertex color, no specular - 3, // pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular - - 4, // instancing + pixel lighting + texture - 4, // instancing + pixel lighting + texture, no fog - 4, // instancing + pixel lighting + texture, no specular - 4, // instancing + pixel lighting + texture, no fog or specular - - 6, // instancing + pixel lighting (biased vertex normal) + texture - 6, // instancing + pixel lighting (biased vertex normal) + texture, no fog - 6, // instancing + pixel lighting (biased vertex normal) + texture, no specular - 6, // instancing + pixel lighting (biased vertex normal) + texture, no fog or specular - - 5, // instancing + pixel lighting + texture + vertex color - 5, // instancing + pixel lighting + texture + vertex color, no fog - 5, // instancing + pixel lighting + texture + vertex color, no specular - 5, // instancing + pixel lighting + texture + vertex color, no fog or specular - - 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color - 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog - 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no specular - 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular - - 8, // skinning + pixel lighting + texture - 8, // skinning + pixel lighting + texture, no fog - 8, // skinning + pixel lighting + texture, no specular - 8, // skinning + pixel lighting + texture, no fog or specular - - 9, // skinning + pixel lighting (biased vertex normal) + texture - 9, // skinning + pixel lighting (biased vertex normal) + texture, no fog - 9, // skinning + pixel lighting (biased vertex normal) + texture, no specular - 9, // 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 + 0, // pixel lighting + texture, no specular + 0, // pixel lighting + texture, no fog or specular + + 2, // pixel lighting (biased vertex normal) + texture + 2, // pixel lighting (biased vertex normal) + texture, no fog + 2, // pixel lighting (biased vertex normal) + texture, no specular + 2, // pixel lighting (biased vertex normal) + texture, no fog or specular + + 1, // pixel lighting + texture + vertex color + 1, // pixel lighting + texture + vertex color, no fog + 1, // pixel lighting + texture + vertex color, no specular + 1, // 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 + 3, // pixel lighting (biased vertex normal) + texture + vertex color, no specular + 3, // pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular + + 4, // instancing + pixel lighting + texture + 4, // instancing + pixel lighting + texture, no fog + 4, // instancing + pixel lighting + texture, no specular + 4, // instancing + pixel lighting + texture, no fog or specular + + 6, // instancing + pixel lighting (biased vertex normal) + texture + 6, // instancing + pixel lighting (biased vertex normal) + texture, no fog + 6, // instancing + pixel lighting (biased vertex normal) + texture, no specular + 6, // instancing + pixel lighting (biased vertex normal) + texture, no fog or specular + + 5, // instancing + pixel lighting + texture + vertex color + 5, // instancing + pixel lighting + texture + vertex color, no fog + 5, // instancing + pixel lighting + texture + vertex color, no specular + 5, // instancing + pixel lighting + texture + vertex color, no fog or specular + + 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color + 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog + 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no specular + 7, // instancing + pixel lighting (biased vertex normal) + texture + vertex color, no fog or specular + + 8, // skinning + pixel lighting + texture + 8, // skinning + pixel lighting + texture, no fog + 8, // skinning + pixel lighting + texture, no specular + 8, // skinning + pixel lighting + texture, no fog or specular + + 9, // skinning + pixel lighting (biased vertex normal) + texture + 9, // skinning + pixel lighting (biased vertex normal) + texture, no fog + 9, // skinning + pixel lighting (biased vertex normal) + texture, no specular + 9, // skinning + pixel lighting (biased vertex normal) + texture, no fog or specular }; - template<> -const ShaderBytecode EffectBase::PixelShaderBytecode[] = -{ - { NormalMapEffect_PSNormalPixelLightingTx, sizeof(NormalMapEffect_PSNormalPixelLightingTx) }, - { NormalMapEffect_PSNormalPixelLightingTxNoFog, sizeof(NormalMapEffect_PSNormalPixelLightingTxNoFog) }, - { NormalMapEffect_PSNormalPixelLightingTxNoSpec, sizeof(NormalMapEffect_PSNormalPixelLightingTxNoSpec) }, +const ShaderBytecode 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_ ID3D11Device* device) : EffectBase(device), - vertexColorEnabled(false), - biasedVertexNormals(false), - instancing(false), - weightsPerVertex(0), - 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"); + vertexColorEnabled(false), + biasedVertexNormals(false), + instancing(false), + weightsPerVertex(0), + 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_ ID3D11Device* device, bool enableSkinning) { - lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); + lights.InitializeConstants(constants.specularColorAndPower, + constants.lightDirection, + constants.lightDiffuseColor, + constants.lightSpecularColor); if (enableSkinning) { @@ -371,7 +373,6 @@ int NormalMapEffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void NormalMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -382,11 +383,18 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) 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); if (weightsPerVertex > 0) { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) void* grfxMemoryBone; mBones.SetData(deviceContext, boneConstants, &grfxMemoryBone); @@ -394,7 +402,7 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ThrowIfFailed(deviceContext->QueryInterface(IID_GRAPHICS_PPV_ARGS(deviceContextX.GetAddressOf()))); deviceContextX->VSSetPlacementConstantBuffer(1, mBones.GetBuffer(), grfxMemoryBone); - #else +#else if (dirtyFlags & EffectDirtyFlags::ConstantBufferBones) { mBones.SetData(deviceContext, boneConstants); @@ -403,23 +411,19 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ID3D11Buffer* buffer = mBones.GetBuffer(); deviceContext->VSSetConstantBuffers(1, 1, &buffer); - #endif +#endif } // Set the textures - ID3D11ShaderResourceView* textures[3] = - { - (texture) ? texture.Get() : GetDefaultTexture(), + ID3D11ShaderResourceView* textures[3] = { (texture) ? texture.Get() : GetDefaultTexture(), (normalTexture) ? normalTexture.Get() : GetDefaultNormalTexture(), - specularTexture.Get() - }; + specularTexture.Get() }; deviceContext->PSSetShaderResources(0, 3, textures); // Set shaders and constant buffers. ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - //-------------------------------------------------------------------------------------- // NormalMapEffect //-------------------------------------------------------------------------------------- @@ -430,10 +434,9 @@ NormalMapEffect::NormalMapEffect(_In_ ID3D11Device* device, bool skinningEnabled pImpl->Initialize(device, 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_ ID3D11DeviceContext* deviceContext) @@ -441,13 +444,11 @@ void NormalMapEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void NormalMapEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV NormalMapEffect::SetWorld(FXMMATRIX value) { @@ -456,7 +457,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; @@ -464,7 +464,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; @@ -472,17 +471,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) { @@ -491,7 +489,6 @@ void XM_CALLCONV NormalMapEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV NormalMapEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -499,7 +496,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). @@ -508,7 +504,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). @@ -517,7 +512,6 @@ void NormalMapEffect::SetSpecularPower(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NormalMapEffect::DisableSpecular() { // Set specular color to black, power to 1 @@ -528,7 +522,6 @@ void NormalMapEffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void NormalMapEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -536,16 +529,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 NormalMapEffect::SetLightingEnabled(bool value) { @@ -555,13 +546,11 @@ void NormalMapEffect::SetLightingEnabled(bool value) } } - void NormalMapEffect::SetPerPixelLighting(bool) { // Unsupported interface method. } - void XM_CALLCONV NormalMapEffect::SetAmbientLightColor(FXMVECTOR value) { pImpl->lights.ambientLightColor = value; @@ -569,13 +558,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); @@ -585,25 +573,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::SetFogEnabled(bool value) { @@ -612,7 +596,6 @@ void NormalMapEffect::SetFogEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::FogEnable; } - void NormalMapEffect::SetFogStart(float value) { pImpl->fog.start = value; @@ -620,7 +603,6 @@ void NormalMapEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void NormalMapEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -628,7 +610,6 @@ void NormalMapEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV NormalMapEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -636,7 +617,6 @@ void XM_CALLCONV NormalMapEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Vertex color setting. void NormalMapEffect::SetVertexColorEnabled(bool value) { @@ -648,33 +628,28 @@ void NormalMapEffect::SetVertexColorEnabled(bool value) pImpl->vertexColorEnabled = value; } - // Texture settings. void NormalMapEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - void NormalMapEffect::SetNormalTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->normalTexture = value; } - void NormalMapEffect::SetSpecularTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->specularTexture = value; } - // Normal compression settings. void NormalMapEffect::SetBiasedVertexNormals(bool value) { pImpl->biasedVertexNormals = value; } - // Instancing settings. void NormalMapEffect::SetInstancingEnabled(bool value) { @@ -686,20 +661,16 @@ void NormalMapEffect::SetInstancingEnabled(bool value) pImpl->instancing = value; } - //-------------------------------------------------------------------------------------- // SkinnedNormalMapEffect //-------------------------------------------------------------------------------------- -SkinnedNormalMapEffect::~SkinnedNormalMapEffect() -{} +SkinnedNormalMapEffect::~SkinnedNormalMapEffect() {} // Animation settings. void SkinnedNormalMapEffect::SetWeightsPerVertex(int value) { - if ((value != 1) && - (value != 2) && - (value != 4)) + if ((value != 1) && (value != 2) && (value != 4)) { throw std::invalid_argument("WeightsPerVertex must be 1, 2, or 4"); } @@ -707,7 +678,6 @@ void SkinnedNormalMapEffect::SetWeightsPerVertex(int value) pImpl->weightsPerVertex = value; } - void SkinnedNormalMapEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (count > MaxBones) @@ -717,22 +687,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 903e5b14..c112d541 100644 --- a/Src/PBREffect.cpp +++ b/Src/PBREffect.cpp @@ -16,7 +16,7 @@ namespace DirectX { constexpr int ConstantBufferBones = 0x100000; } -} +} // namespace DirectX using namespace DirectX; using Microsoft::WRL::ComPtr; @@ -42,8 +42,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"); @@ -60,12 +60,12 @@ namespace { 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,10 +73,10 @@ class PBREffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* 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_ ID3D11Device* device, bool enableSkinning); @@ -92,7 +92,7 @@ class PBREffect::Impl : public EffectBase bool biasedVertexNormals; bool velocityEnabled; bool instancing; - int weightsPerVertex; + int weightsPerVertex; XMVECTOR lightColor[MaxDirectionalLights]; @@ -106,7 +106,6 @@ class PBREffect::Impl : public EffectBase ConstantBuffer mBones; }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -148,103 +147,95 @@ namespace #include "PBREffect_PSTexturedVelocity.inc" #include "PBREffect_PSTexturedEmissiveVelocity.inc" #endif -} - +} // namespace template<> -const ShaderBytecode EffectBase::VertexShaderBytecode[] = -{ - { PBREffect_VSConstant, sizeof(PBREffect_VSConstant) }, - { PBREffect_VSConstantVelocity, sizeof(PBREffect_VSConstantVelocity) }, - { PBREffect_VSConstantBn, sizeof(PBREffect_VSConstantBn) }, +const ShaderBytecode 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 (biased vertex normals) + 3, // textured + velocity (biased vertex normals) + 3, // textured + emissive + velocity (biased vertex normals) }; - template<> -const ShaderBytecode EffectBase::PixelShaderBytecode[] = -{ - { PBREffect_PSConstant, sizeof(PBREffect_PSConstant) }, - { PBREffect_PSTextured, sizeof(PBREffect_PSTextured) }, - { PBREffect_PSTexturedEmissive, sizeof(PBREffect_PSTexturedEmissive) }, - { PBREffect_PSTexturedVelocity, sizeof(PBREffect_PSTexturedVelocity) }, +const ShaderBytecode 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 @@ -255,17 +246,21 @@ SharedResourcePool::DeviceResources> // Constructor. PBREffect::Impl::Impl(_In_ ID3D11Device* device) : EffectBase(device), - biasedVertexNormals(false), - velocityEnabled(false), - instancing(false), - weightsPerVertex(0), - 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"); + biasedVertexNormals(false), + velocityEnabled(false), + instancing(false), + weightsPerVertex(0), + 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_ ID3D11Device* device, bool enableSkinning) @@ -274,15 +269,15 @@ void PBREffect::Impl::Initialize(_In_ ID3D11Device* device, bool enableSkinning) 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; } // 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) @@ -341,7 +336,6 @@ int PBREffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -351,16 +345,11 @@ void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) 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); if (weightsPerVertex > 0) { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) void* grfxMemoryBone; mBones.SetData(deviceContext, boneConstants, &grfxMemoryBone); @@ -368,7 +357,7 @@ void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ThrowIfFailed(deviceContext->QueryInterface(IID_GRAPHICS_PPV_ARGS(deviceContextX.GetAddressOf()))); deviceContextX->VSSetPlacementConstantBuffer(1, mBones.GetBuffer(), grfxMemoryBone); - #else +#else if (dirtyFlags & EffectDirtyFlags::ConstantBufferBones) { mBones.SetData(deviceContext, boneConstants); @@ -377,28 +366,23 @@ void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ID3D11Buffer* buffer = mBones.GetBuffer(); deviceContext->VSSetConstantBuffers(1, 1, &buffer); - #endif +#endif } // Set the textures if (albedoTexture) { - ID3D11ShaderResourceView* textures[6] = - { - albedoTexture.Get(), normalTexture.Get(), rmaTexture.Get(), + ID3D11ShaderResourceView* textures[6] = { albedoTexture.Get(), + normalTexture.Get(), + rmaTexture.Get(), emissiveTexture.Get(), - radianceTexture.Get(), irradianceTexture.Get() - }; + radianceTexture.Get(), + irradianceTexture.Get() }; deviceContext->PSSetShaderResources(0, 6, textures); } else { - ID3D11ShaderResourceView* textures[6] = - { - nullptr, nullptr, nullptr, - nullptr, - radianceTexture.Get(), irradianceTexture.Get() - }; + ID3D11ShaderResourceView* textures[6] = { nullptr, nullptr, nullptr, nullptr, radianceTexture.Get(), irradianceTexture.Get() }; deviceContext->PSSetShaderResources(0, 6, textures); } @@ -406,7 +390,6 @@ void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - //-------------------------------------------------------------------------------------- // PBREffect //-------------------------------------------------------------------------------------- @@ -417,10 +400,9 @@ PBREffect::PBREffect(_In_ ID3D11Device* device, bool skinningEnabled) pImpl->Initialize(device, 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_ ID3D11DeviceContext* deviceContext) @@ -428,13 +410,11 @@ void PBREffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void PBREffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV PBREffect::SetWorld(FXMMATRIX value) { @@ -443,7 +423,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; @@ -451,7 +430,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; @@ -459,17 +437,15 @@ 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 PBREffect::SetLightingEnabled(bool value) { @@ -479,19 +455,16 @@ void PBREffect::SetLightingEnabled(bool value) } } - void PBREffect::SetPerPixelLighting(bool) { // Unsupported interface method. } - void XM_CALLCONV PBREffect::SetAmbientLightColor(FXMVECTOR) { // Unsupported interface. } - void PBREffect::SetLightEnabled(int whichLight, bool value) { EffectLights::ValidateLightIndex(whichLight); @@ -501,7 +474,6 @@ void PBREffect::SetLightEnabled(int whichLight, bool value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void XM_CALLCONV PBREffect::SetLightDirection(int whichLight, FXMVECTOR value) { EffectLights::ValidateLightIndex(whichLight); @@ -511,30 +483,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) { @@ -544,7 +512,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). @@ -553,7 +520,6 @@ void PBREffect::SetConstantAlbedo(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void PBREffect::SetConstantMetallic(float value) { pImpl->constants.Metallic = value; @@ -561,7 +527,6 @@ void PBREffect::SetConstantMetallic(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void PBREffect::SetConstantRoughness(float value) { pImpl->constants.Roughness = value; @@ -569,20 +534,17 @@ void PBREffect::SetConstantRoughness(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void PBREffect::SetAlbedoTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->albedoTexture = value; } - void PBREffect::SetNormalTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->normalTexture = value; } - void PBREffect::SetRMATexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->rmaTexture = value; @@ -593,38 +555,32 @@ void PBREffect::SetEmissiveTexture(_In_opt_ ID3D11ShaderResourceView* value) pImpl->emissiveTexture = value; } - -void PBREffect::SetSurfaceTextures( - _In_opt_ ID3D11ShaderResourceView* albedo, - _In_opt_ ID3D11ShaderResourceView* normal, - _In_opt_ ID3D11ShaderResourceView* roughnessMetallicAmbientOcclusion) +void PBREffect::SetSurfaceTextures(_In_opt_ ID3D11ShaderResourceView* albedo, + _In_opt_ ID3D11ShaderResourceView* normal, + _In_opt_ ID3D11ShaderResourceView* roughnessMetallicAmbientOcclusion) { pImpl->albedoTexture = albedo; pImpl->normalTexture = normal; - pImpl->rmaTexture = roughnessMetallicAmbientOcclusion; + pImpl->rmaTexture = roughnessMetallicAmbientOcclusion; } - -void PBREffect::SetIBLTextures( - _In_opt_ ID3D11ShaderResourceView* radiance, - int numRadianceMips, - _In_opt_ ID3D11ShaderResourceView* irradiance) +void PBREffect::SetIBLTextures(_In_opt_ ID3D11ShaderResourceView* radiance, + int numRadianceMips, + _In_opt_ ID3D11ShaderResourceView* irradiance) { - pImpl->radianceTexture = radiance; + pImpl->radianceTexture = radiance; pImpl->irradianceTexture = irradiance; pImpl->constants.numRadianceMipLevels = numRadianceMips; pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Normal compression settings. void PBREffect::SetBiasedVertexNormals(bool value) { pImpl->biasedVertexNormals = value; } - // Instancing settings. void PBREffect::SetInstancingEnabled(bool value) { @@ -636,7 +592,6 @@ void PBREffect::SetInstancingEnabled(bool value) pImpl->instancing = value; } - // Additional settings. void PBREffect::SetVelocityGeneration(bool value) { @@ -648,29 +603,24 @@ void PBREffect::SetVelocityGeneration(bool value) pImpl->velocityEnabled = value; } - 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::SetWeightsPerVertex(int value) { - if ((value != 1) && - (value != 2) && - (value != 4)) + if ((value != 1) && (value != 2) && (value != 4)) { throw std::invalid_argument("WeightsPerVertex must be 1, 2, or 4"); } @@ -678,7 +628,6 @@ void SkinnedPBREffect::SetWeightsPerVertex(int value) pImpl->weightsPerVertex = value; } - void SkinnedPBREffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (count > MaxBones) @@ -688,22 +637,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 a48bdd1b..f9293cff 100644 --- a/Src/PBREffectFactory.cpp +++ b/Src/PBREffectFactory.cpp @@ -21,11 +21,10 @@ using Microsoft::WRL::ComPtr; namespace { template - void SetPBRProperties( - _In_ T* effect, + void SetPBRProperties(_In_ T* effect, const EffectFactory::EffectInfo& info, - _In_ IEffectFactory* factory, - _In_opt_ ID3D11DeviceContext* deviceContext) + _In_ IEffectFactory* factory, + _In_opt_ ID3D11DeviceContext* deviceContext) { // We don't use EnableDefaultLighting generally for PBR as it uses Image-Based Lighting instead. @@ -83,7 +82,7 @@ namespace effect->SetBiasedVertexNormals(true); } } -} +} // namespace // Internal PBREffectFactory implementation class. Only one of these helpers is allocated // per D3D device, even if there are multiple public facing PBREffectFactory instances. @@ -92,28 +91,26 @@ class PBREffectFactory::Impl public: explicit Impl(_In_ ID3D11Device* device) : mPath{}, - mDevice(device), - mSharing(true), - mForceSRGB(false) + mDevice(device), + mSharing(true), + mForceSRGB(false) { if (!device) throw std::invalid_argument("Direct3D device is null"); } - 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( - _In_ IEffectFactory* factory, - _In_ const IEffectFactory::EffectInfo& info, - _In_opt_ ID3D11DeviceContext* deviceContext); + std::shared_ptr + CreateEffect(_In_ IEffectFactory* factory, _In_ const IEffectFactory::EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext); void CreateTexture(_In_z_ const wchar_t* texture, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView); + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView); void ReleaseCache(); @@ -127,8 +124,8 @@ class PBREffectFactory::Impl bool mForceSRGB; private: - using EffectCache = std::map< std::wstring, std::shared_ptr >; - using TextureCache = std::map< std::wstring, ComPtr >; + using EffectCache = std::map>; + using TextureCache = std::map>; EffectCache mEffectCache; EffectCache mEffectCacheSkinning; @@ -137,16 +134,11 @@ class PBREffectFactory::Impl std::mutex mutex; }; - // Global instance pool. SharedResourcePool PBREffectFactory::Impl::instancePool; - -_Use_decl_annotations_ -std::shared_ptr PBREffectFactory::Impl::CreateEffect( - IEffectFactory* factory, - const IEffectFactory::EffectInfo& info, - ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr +PBREffectFactory::Impl::CreateEffect(IEffectFactory* factory, const IEffectFactory::EffectInfo& info, ID3D11DeviceContext* deviceContext) { // info.perVertexColor and info.enableDualTexture are ignored by PBREffectFactory @@ -169,7 +161,7 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCacheSkinning.insert(v); } @@ -194,7 +186,7 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( if (mSharing && info.name && *info.name) { std::lock_guard lock(mutex); - EffectCache::value_type v(info.name, effect); + EffectCache::value_type v(info.name, effect); mEffectCache.insert(v); } @@ -202,11 +194,8 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( } } -_Use_decl_annotations_ -void PBREffectFactory::Impl::CreateTexture( - const wchar_t* name, - ID3D11DeviceContext* deviceContext, - ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +PBREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { if (!name || !textureView) throw std::invalid_argument("name and textureView parameters can't be null"); @@ -237,7 +226,8 @@ void PBREffectFactory::Impl::CreateTexture( if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: PBREffectFactory could not find texture file '%ls'\n", name); - throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "PBREffectFactory::CreateTexture"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), + "PBREffectFactory::CreateTexture"); } } @@ -247,43 +237,59 @@ void PBREffectFactory::Impl::CreateTexture( if (isdds) { - HRESULT hr = CreateDDSTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateDDSTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT, + nullptr, + textureView); 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("PBREffectFactory::CreateDDSTextureFromFile"); } } - #if !defined(_XBOX_ONE) || !defined(_TITLE) +#if !defined(_XBOX_ONE) || !defined(_TITLE) else if (deviceContext) { std::lock_guard lock(mutex); - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), deviceContext, fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + deviceContext, + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("PBREffectFactory::CreateWICTextureFromFile"); } } - #endif +#endif else { - HRESULT hr = CreateWICTextureFromFileEx( - mDevice.Get(), fullName, 0, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, - mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, nullptr, textureView); + HRESULT hr = CreateWICTextureFromFileEx(mDevice.Get(), + fullName, + 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, + mForceSRGB ? WIC_LOADER_FORCE_SRGB : WIC_LOADER_DEFAULT, + nullptr, + textureView); 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("PBREffectFactory::CreateWICTextureFromFile"); } } @@ -291,7 +297,7 @@ void PBREffectFactory::Impl::CreateTexture( if (mSharing && *name && it == mTextureCache.end()) { std::lock_guard lock(mutex); - TextureCache::value_type v(name, *textureView); + TextureCache::value_type v(name, *textureView); mTextureCache.insert(v); } } @@ -305,8 +311,6 @@ void PBREffectFactory::Impl::ReleaseCache() mTextureCache.clear(); } - - //-------------------------------------------------------------------------------------- // PBREffectFactory //-------------------------------------------------------------------------------------- @@ -315,19 +319,17 @@ PBREffectFactory::PBREffectFactory(_In_ ID3D11Device* device) : pImpl(Impl::instancePool.DemandCreate(device)) {} -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; -_Use_decl_annotations_ -std::shared_ptr PBREffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) +_Use_decl_annotations_ std::shared_ptr PBREffectFactory::CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext) { return pImpl->CreateEffect(this, info, deviceContext); } -_Use_decl_annotations_ -void PBREffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) +_Use_decl_annotations_ void +PBREffectFactory::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { return pImpl->CreateTexture(name, deviceContext, textureView); } @@ -358,7 +360,7 @@ void PBREffectFactory::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; } } 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 e28b72d1..685c634b 100644 --- a/Src/PrimitiveBatch.cpp +++ b/Src/PrimitiveBatch.cpp @@ -17,23 +17,27 @@ using namespace DirectX; using namespace DirectX::DX11::Private; using Microsoft::WRL::ComPtr; - // Internal PrimitiveBatch implementation class. class PrimitiveBatchBase::Impl { public: Impl(_In_ ID3D11DeviceContext* deviceContext, 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(); void End(); - void Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIndexed, _In_opt_count_(indexCount) uint16_t const* indices, size_t indexCount, size_t vertexCount, _Out_ void** pMappedVertices); + void Draw(D3D11_PRIMITIVE_TOPOLOGY topology, + bool isIndexed, + _In_opt_count_(indexCount) uint16_t const* indices, + size_t indexCount, + size_t vertexCount, + _Out_ void** pMappedVertices); private: void FlushBatch(); @@ -51,8 +55,8 @@ class PrimitiveBatchBase::Impl size_t mVertexSize; D3D11_PRIMITIVE_TOPOLOGY mCurrentTopology; - bool mInBeginEndPair; - bool mCurrentlyIndexed; + bool mInBeginEndPair; + bool mCurrentlyIndexed; size_t mCurrentIndex; size_t mCurrentVertex; @@ -61,15 +65,14 @@ class PrimitiveBatchBase::Impl size_t mBaseVertex; #if defined(_XBOX_ONE) && defined(_TITLE) - void *grfxMemoryIB; - void *grfxMemoryVB; + void* grfxMemoryIB; + void* grfxMemoryVB; #else D3D11_MAPPED_SUBRESOURCE mMappedIndices; D3D11_MAPPED_SUBRESOURCE mMappedVertices; #endif }; - namespace { // Helper for creating a D3D vertex or index buffer. @@ -78,14 +81,12 @@ namespace { D3D11_BUFFER_DESC desc = {}; - desc.ByteWidth = bufferSize; - desc.BindFlags = bindFlag; - desc.Usage = D3D11_USAGE_DEFAULT; + desc.ByteWidth = bufferSize; + desc.BindFlags = bindFlag; + desc.Usage = D3D11_USAGE_DEFAULT; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - ThrowIfFailed( - device->CreatePlacementBuffer(&desc, nullptr, pBuffer) - ); + ThrowIfFailed(device->CreatePlacementBuffer(&desc, nullptr, pBuffer)); SetDebugObjectName(*pBuffer, "DirectXTK:PrimitiveBatch"); } @@ -94,14 +95,12 @@ namespace { D3D11_BUFFER_DESC desc = {}; - desc.ByteWidth = bufferSize; - desc.BindFlags = bindFlag; - desc.Usage = D3D11_USAGE_DYNAMIC; + desc.ByteWidth = bufferSize; + desc.BindFlags = bindFlag; + desc.Usage = D3D11_USAGE_DYNAMIC; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - ThrowIfFailed( - device->CreateBuffer(&desc, nullptr, pBuffer) - ); + ThrowIfFailed(device->CreateBuffer(&desc, nullptr, pBuffer)); assert(pBuffer != nullptr && *pBuffer != nullptr); _Analysis_assume_(pBuffer != nullptr && *pBuffer != nullptr); @@ -109,27 +108,26 @@ namespace SetDebugObjectName(*pBuffer, "DirectXTK:PrimitiveBatch"); } #endif -} - +} // namespace // Constructor. PrimitiveBatchBase::Impl::Impl(_In_ ID3D11DeviceContext* deviceContext, size_t maxIndices, size_t maxVertices, size_t vertexSize) : mMaxIndices(maxIndices), - mMaxVertices(maxVertices), - mVertexSize(vertexSize), - mCurrentTopology(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED), - mInBeginEndPair(false), - mCurrentlyIndexed(false), - mCurrentIndex(0), - mCurrentVertex(0), - mBaseIndex(0), - mBaseVertex(0), + mMaxVertices(maxVertices), + mVertexSize(vertexSize), + mCurrentTopology(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED), + mInBeginEndPair(false), + mCurrentlyIndexed(false), + mCurrentIndex(0), + mCurrentVertex(0), + mBaseIndex(0), + mBaseVertex(0), #if defined(_XBOX_ONE) && defined(_TITLE) - grfxMemoryIB(nullptr), - grfxMemoryVB(nullptr) + grfxMemoryIB(nullptr), + grfxMemoryVB(nullptr) #else - mMappedIndices{}, - mMappedVertices{} + mMappedIndices{}, + mMappedVertices{} #endif { if (!deviceContext) @@ -145,13 +143,11 @@ PrimitiveBatchBase::Impl::Impl(_In_ ID3D11DeviceContext* deviceContext, size_t m throw std::invalid_argument("Vertex size is too large for DirectX 11"); const uint64_t ibBytes = uint64_t(maxIndices) * sizeof(uint16_t); - if (ibBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u) - || ibBytes > UINT32_MAX) + if (ibBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u) || ibBytes > UINT32_MAX) throw std::invalid_argument("IB too large for DirectX 11"); const uint64_t vbBytes = uint64_t(maxVertices) * uint64_t(vertexSize); - if (vbBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u) - || vbBytes > UINT32_MAX) + if (vbBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u) || vbBytes > UINT32_MAX) throw std::invalid_argument("VB too large for DirectX 11"); #if defined(_XBOX_ONE) && defined(_TITLE) @@ -184,7 +180,6 @@ PrimitiveBatchBase::Impl::Impl(_In_ ID3D11DeviceContext* deviceContext, size_t m #endif } - // Begins a batch of primitive drawing operations. void PrimitiveBatchBase::Impl::Begin() { @@ -201,8 +196,8 @@ void PrimitiveBatchBase::Impl::Begin() } // Bind the vertex buffer. - auto vertexBuffer = mVertexBuffer.Get(); - const UINT vertexStride = static_cast(mVertexSize); + auto vertexBuffer = mVertexBuffer.Get(); + const UINT vertexStride = static_cast(mVertexSize); constexpr UINT vertexOffset = 0; mDeviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &vertexStride, &vertexOffset); @@ -211,14 +206,13 @@ void PrimitiveBatchBase::Impl::Begin() // If this is a deferred D3D context, reset position so the first Map calls will use D3D11_MAP_WRITE_DISCARD. if (mDeviceContext->GetType() == D3D11_DEVICE_CONTEXT_DEFERRED) { - mCurrentIndex = 0; + mCurrentIndex = 0; mCurrentVertex = 0; } mInBeginEndPair = true; } - // Ends a batch of primitive drawing operations. void PrimitiveBatchBase::Impl::End() { @@ -230,7 +224,6 @@ void PrimitiveBatchBase::Impl::End() mInBeginEndPair = false; } - namespace { // Can we combine adjacent primitives using this topology into a single draw call? @@ -253,26 +246,30 @@ namespace // but that's not always a perf win, so let's keep things simple. } - #if !defined(_XBOX_ONE) || !defined(_TITLE) // Helper for locking a vertex or index buffer. - void LockBuffer(_In_ ID3D11DeviceContext* deviceContext, _In_ ID3D11Buffer* buffer, size_t currentPosition, _Out_ size_t* basePosition, _Out_ D3D11_MAPPED_SUBRESOURCE* mappedResource) + void LockBuffer(_In_ ID3D11DeviceContext* deviceContext, + _In_ ID3D11Buffer* buffer, + size_t currentPosition, + _Out_ size_t* basePosition, + _Out_ D3D11_MAPPED_SUBRESOURCE* mappedResource) { const D3D11_MAP mapType = (currentPosition == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE; - ThrowIfFailed( - deviceContext->Map(buffer, 0, mapType, 0, mappedResource) - ); + ThrowIfFailed(deviceContext->Map(buffer, 0, mapType, 0, mappedResource)); *basePosition = currentPosition; } #endif -} - +} // namespace // Adds new geometry to the batch. -_Use_decl_annotations_ -void PrimitiveBatchBase::Impl::Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIndexed, uint16_t const* indices, size_t indexCount, size_t vertexCount, void** pMappedVertices) +_Use_decl_annotations_ void PrimitiveBatchBase::Impl::Draw(D3D11_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"); @@ -287,13 +284,11 @@ void PrimitiveBatchBase::Impl::Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIn throw std::logic_error("Begin must be called before Draw"); // Can we merge this primitive in with an existing batch, or must we flush first? - const bool wrapIndexBuffer = (mCurrentIndex + indexCount > mMaxIndices); + const bool wrapIndexBuffer = (mCurrentIndex + indexCount > mMaxIndices); const bool wrapVertexBuffer = (mCurrentVertex + vertexCount > mMaxVertices); - if ((topology != mCurrentTopology) || - (isIndexed != mCurrentlyIndexed) || - !CanBatchPrimitives(topology) || - wrapIndexBuffer || wrapVertexBuffer) + if ((topology != mCurrentTopology) || (isIndexed != mCurrentlyIndexed) || !CanBatchPrimitives(topology) || wrapIndexBuffer + || wrapVertexBuffer) { FlushBatch(); } @@ -310,7 +305,7 @@ void PrimitiveBatchBase::Impl::Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIn grfxMemoryVB = grfxMem.Allocate(mDeviceContext.Get(), mMaxVertices * mVertexSize, 64); - mCurrentTopology = topology; + mCurrentTopology = topology; mCurrentlyIndexed = isIndexed; mCurrentIndex = mCurrentVertex = 0; } @@ -351,7 +346,7 @@ void PrimitiveBatchBase::Impl::Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIn LockBuffer(mDeviceContext.Get(), mVertexBuffer.Get(), mCurrentVertex, &mBaseVertex, &mMappedVertices); - mCurrentTopology = topology; + mCurrentTopology = topology; mCurrentlyIndexed = isIndexed; } @@ -375,7 +370,6 @@ void PrimitiveBatchBase::Impl::Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIn #endif } - // Sends queued primitives to the graphics device. void PrimitiveBatchBase::Impl::FlushBatch() { @@ -411,8 +405,7 @@ void PrimitiveBatchBase::Impl::FlushBatch() // Draw indexed geometry. mDeviceContext->Unmap(mIndexBuffer.Get(), 0); - mDeviceContext->DrawIndexed( - static_cast(mCurrentIndex - mBaseIndex), + mDeviceContext->DrawIndexed(static_cast(mCurrentIndex - mBaseIndex), static_cast(mBaseIndex), static_cast(mBaseVertex)); } @@ -426,17 +419,14 @@ void PrimitiveBatchBase::Impl::FlushBatch() mCurrentTopology = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED; } - // Public constructor. PrimitiveBatchBase::PrimitiveBatchBase(_In_ ID3D11DeviceContext* deviceContext, size_t maxIndices, size_t maxVertices, size_t vertexSize) : pImpl(std::make_unique(deviceContext, 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; // Begin a primitive batch. void PrimitiveBatchBase::Begin() @@ -444,17 +434,19 @@ void PrimitiveBatchBase::Begin() pImpl->Begin(); } - // End/draw a primitive batch. void PrimitiveBatchBase::End() { pImpl->End(); } - // Custom draw method. -_Use_decl_annotations_ -void PrimitiveBatchBase::Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIndexed, uint16_t const* indices, size_t indexCount, size_t vertexCount, void** pMappedVertices) +_Use_decl_annotations_ void PrimitiveBatchBase::Draw(D3D11_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/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 46f8df03..eb237d3e 100644 --- a/Src/ScreenGrab.cpp +++ b/Src/ScreenGrab.cpp @@ -37,11 +37,10 @@ using namespace DirectX::LoaderHelpers; namespace { //-------------------------------------------------------------------------------------- - HRESULT CaptureTexture( - _In_ ID3D11DeviceContext* pContext, - _In_ ID3D11Resource* pSource, - D3D11_TEXTURE2D_DESC& desc, - ComPtr& pStaging) noexcept + HRESULT CaptureTexture(_In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + D3D11_TEXTURE2D_DESC& desc, + ComPtr& pStaging) noexcept { if (!pContext || !pSource) return E_INVALIDARG; @@ -56,7 +55,7 @@ namespace } ComPtr pTexture; - HRESULT hr = pSource->QueryInterface(IID_GRAPHICS_PPV_ARGS(pTexture.GetAddressOf())); + HRESULT hr = pSource->QueryInterface(IID_GRAPHICS_PPV_ARGS(pTexture.GetAddressOf())); if (FAILED(hr)) return hr; @@ -66,7 +65,9 @@ namespace if (desc.ArraySize > 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"); } ComPtr d3dDevice; @@ -75,7 +76,7 @@ namespace if (desc.SampleDesc.Count > 1) { // MSAA content must be resolved before being copied to a staging texture - desc.SampleDesc.Count = 1; + desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; ComPtr pTemp; @@ -88,7 +89,7 @@ namespace const DXGI_FORMAT fmt = EnsureNotTypeless(desc.Format); UINT support = 0; - hr = d3dDevice->CheckFormatSupport(fmt, &support); + hr = d3dDevice->CheckFormatSupport(fmt, &support); if (FAILED(hr)) return hr; @@ -107,7 +108,7 @@ namespace desc.BindFlags = 0; desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; - desc.Usage = D3D11_USAGE_STAGING; + desc.Usage = D3D11_USAGE_STAGING; hr = d3dDevice->CreateTexture2D(&desc, nullptr, pStaging.ReleaseAndGetAddressOf()); if (FAILED(hr)) @@ -128,7 +129,7 @@ namespace desc.BindFlags = 0; desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; - desc.Usage = D3D11_USAGE_STAGING; + desc.Usage = D3D11_USAGE_STAGING; hr = d3dDevice->CreateTexture2D(&desc, nullptr, pStaging.ReleaseAndGetAddressOf()); if (FAILED(hr)) @@ -139,7 +140,7 @@ namespace pContext->CopyResource(pStaging.Get(), pSource); } - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) if (d3dDevice->GetCreationFlags() & D3D11_CREATE_DEVICE_IMMEDIATE_CONTEXT_FAST_SEMANTICS) { @@ -161,34 +162,28 @@ namespace } } - #endif +#endif return S_OK; } } // anonymous namespace - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::SaveDDSTextureToFile( - ID3D11DeviceContext* pContext, - ID3D11Resource* pSource, - const wchar_t* fileName) noexcept +_Use_decl_annotations_ HRESULT DirectX::SaveDDSTextureToFile(ID3D11DeviceContext* pContext, + ID3D11Resource* pSource, + const wchar_t* fileName) noexcept { if (!fileName) return E_INVALIDARG; - D3D11_TEXTURE2D_DESC desc = {}; + D3D11_TEXTURE2D_DESC desc = {}; ComPtr pStaging; - HRESULT hr = CaptureTexture(pContext, pSource, desc, pStaging); + HRESULT hr = CaptureTexture(pContext, pSource, desc, pStaging); if (FAILED(hr)) return hr; // Create file - ScopedHandle hFile(safe_handle(CreateFile2( - fileName, - GENERIC_WRITE | DELETE, 0, CREATE_ALWAYS, - nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_WRITE | DELETE, 0, CREATE_ALWAYS, nullptr))); if (!hFile) return HRESULT_FROM_WIN32(GetLastError()); @@ -199,53 +194,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 = 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 = 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; // DXGI 1.1 - case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy(&header->ddspf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 - case DXGI_FORMAT_YUY2: memcpy(&header->ddspf, &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 - case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy(&header->ddspf, &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 + 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; // DXGI 1.1 + case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy(&header->ddspf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 + case DXGI_FORMAT_YUY2: memcpy(&header->ddspf, &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 + case DXGI_FORMAT_B4G4R4A4_UNORM: + memcpy(&header->ddspf, &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); + break; // DXGI 1.2 // 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: @@ -258,10 +287,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 = D3D11_RESOURCE_DIMENSION_TEXTURE2D; - extHeader->arraySize = 1; + extHeader->arraySize = 1; break; } @@ -339,58 +368,54 @@ namespace DirectX { namespace ToolKitInternal { - extern bool IsWIC2() noexcept; + extern bool IsWIC2() noexcept; extern IWICImagingFactory* GetWIC() noexcept; - } - } -} - -_Use_decl_annotations_ -HRESULT DirectX::SaveWICTextureToFile( - ID3D11DeviceContext* pContext, - ID3D11Resource* pSource, - REFGUID guidContainerFormat, - const wchar_t* fileName, - const GUID* targetFormat, - std::function setCustomProps, - bool forceSRGB) + } // namespace ToolKitInternal + } // namespace DX11 +} // namespace DirectX + +_Use_decl_annotations_ HRESULT DirectX::SaveWICTextureToFile(ID3D11DeviceContext* pContext, + ID3D11Resource* pSource, + REFGUID guidContainerFormat, + const wchar_t* fileName, + const GUID* targetFormat, + std::function setCustomProps, + bool forceSRGB) { using namespace DX11::ToolKitInternal; if (!fileName) return E_INVALIDARG; - D3D11_TEXTURE2D_DESC desc = {}; + D3D11_TEXTURE2D_DESC desc = {}; ComPtr pStaging; - HRESULT hr = CaptureTexture(pContext, pSource, desc, pStaging); + HRESULT hr = CaptureTexture(pContext, pSource, desc, pStaging); if (FAILED(hr)) return hr; // 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; // DXGI 1.1 - 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; // DXGI 1.1 + 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: // DXGI 1.1 @@ -399,7 +424,7 @@ HRESULT DirectX::SaveWICTextureToFile( case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: // DXGI 1.1 pfGuid = GUID_WICPixelFormat32bppBGRA; - sRGB = true; + sRGB = true; break; case DXGI_FORMAT_B8G8R8X8_UNORM: // DXGI 1.1 @@ -408,11 +433,12 @@ HRESULT DirectX::SaveWICTextureToFile( case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: // DXGI 1.1 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); } @@ -441,7 +467,7 @@ HRESULT DirectX::SaveWICTextureToFile( return hr; ComPtr frame; - ComPtr props; + ComPtr props; hr = encoder->CreateNewFrame(frame.GetAddressOf(), props.GetAddressOf()); if (FAILED(hr)) return hr; @@ -453,9 +479,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) @@ -506,13 +532,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; } } @@ -533,7 +555,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) @@ -544,22 +566,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) +#if defined(_XBOX_ONE) && defined(_TITLE) else if (memcmp(&guidContainerFormat, &GUID_ContainerFormatJpeg, sizeof(GUID)) == 0) { // Set Software name @@ -568,7 +590,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); } @@ -581,12 +603,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 @@ -595,12 +617,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"System.Image.ColorSpace", &value); } } - #endif +#endif } D3D11_MAPPED_SUBRESOURCE mapped; @@ -619,10 +641,13 @@ HRESULT DirectX::SaveWICTextureToFile( { // Conversion required to write ComPtr source; - hr = pWIC->CreateBitmapFromMemory(desc.Width, desc.Height, + hr = pWIC->CreateBitmapFromMemory(desc.Width, + desc.Height, pfGuid, - mapped.RowPitch, static_cast(imageSize), - static_cast(mapped.pData), source.GetAddressOf()); + mapped.RowPitch, + static_cast(imageSize), + static_cast(mapped.pData), + source.GetAddressOf()); if (FAILED(hr)) { pContext->Unmap(pStaging.Get(), 0); @@ -638,7 +663,7 @@ HRESULT DirectX::SaveWICTextureToFile( } BOOL canConvert = FALSE; - hr = FC->CanConvert(pfGuid, targetGuid, &canConvert); + hr = FC->CanConvert(pfGuid, targetGuid, &canConvert); if (FAILED(hr) || !canConvert) { pContext->Unmap(pStaging.Get(), 0); @@ -653,14 +678,12 @@ 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, - mapped.RowPitch, static_cast(imageSize), - static_cast(mapped.pData)); + hr = frame->WritePixels(desc.Height, mapped.RowPitch, static_cast(imageSize), static_cast(mapped.pData)); } pContext->Unmap(pStaging.Get(), 0); @@ -681,7 +704,6 @@ HRESULT DirectX::SaveWICTextureToFile( return S_OK; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients @@ -689,28 +711,29 @@ HRESULT DirectX::SaveWICTextureToFile( namespace DirectX { - HRESULT __cdecl SaveDDSTextureToFile( - _In_ ID3D11DeviceContext* pContext, - _In_ ID3D11Resource* pSource, - _In_z_ const __wchar_t* fileName) noexcept + HRESULT __cdecl SaveDDSTextureToFile(_In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_z_ const __wchar_t* fileName) noexcept { - return SaveDDSTextureToFile(pContext, pSource, - reinterpret_cast(fileName)); + return SaveDDSTextureToFile(pContext, pSource, reinterpret_cast(fileName)); } - HRESULT __cdecl SaveWICTextureToFile( - _In_ ID3D11DeviceContext* pContext, - _In_ ID3D11Resource* pSource, - _In_ REFGUID guidContainerFormat, - _In_z_ const __wchar_t* fileName, - _In_opt_ const GUID* targetFormat, + HRESULT __cdecl SaveWICTextureToFile(_In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_ REFGUID guidContainerFormat, + _In_z_ const __wchar_t* fileName, + _In_opt_ const GUID* targetFormat, _In_ std::function setCustomProps, - _In_ bool forceSRGB) + _In_ bool forceSRGB) { - return SaveWICTextureToFile(pContext, pSource, guidContainerFormat, + return SaveWICTextureToFile(pContext, + pSource, + guidContainerFormat, reinterpret_cast(fileName), - targetFormat, setCustomProps, forceSRGB); + 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 1bb34ec7..eacee4f2 100644 --- a/Src/SkinnedEffect.cpp +++ b/Src/SkinnedEffect.cpp @@ -44,11 +44,11 @@ namespace { using ConstantBufferType = SkinnedEffectConstants; - static constexpr int VertexShaderCount = 18; - static constexpr int PixelShaderCount = 3; + static constexpr int VertexShaderCount = 18; + static constexpr int PixelShaderCount = 3; static constexpr int ShaderPermutationCount = 36; }; -} +} // namespace // Internal SkinnedEffect implementation class. class SkinnedEffect::Impl : public EffectBase @@ -56,15 +56,15 @@ class SkinnedEffect::Impl : public EffectBase public: explicit Impl(_In_ ID3D11Device* device); - Impl(const Impl&) = delete; + Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; - Impl(Impl&&) = default; + Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; bool preferPerPixelLighting; bool biasedVertexNormals; - int weightsPerVertex; + int weightsPerVertex; EffectLights lights; @@ -73,7 +73,6 @@ class SkinnedEffect::Impl : public EffectBase void Apply(_In_ ID3D11DeviceContext* deviceContext); }; - #pragma region Shaders // Include the precompiled shader code. namespace @@ -135,160 +134,163 @@ namespace #include "SkinnedEffect_PSSkinnedVertexLightingNoFog.inc" #include "SkinnedEffect_PSSkinnedPixelLighting.inc" #endif -} - +} // namespace template<> -const ShaderBytecode EffectBase::VertexShaderBytecode[] = -{ - { SkinnedEffect_VSSkinnedVertexLightingOneBone, sizeof(SkinnedEffect_VSSkinnedVertexLightingOneBone) }, - { SkinnedEffect_VSSkinnedVertexLightingTwoBones, sizeof(SkinnedEffect_VSSkinnedVertexLightingTwoBones) }, - { SkinnedEffect_VSSkinnedVertexLightingFourBones, sizeof(SkinnedEffect_VSSkinnedVertexLightingFourBones) }, +const ShaderBytecode EffectBase::VertexShaderBytecode[] = { + { SkinnedEffect_VSSkinnedVertexLightingOneBone, sizeof(SkinnedEffect_VSSkinnedVertexLightingOneBone) }, + { SkinnedEffect_VSSkinnedVertexLightingTwoBones, sizeof(SkinnedEffect_VSSkinnedVertexLightingTwoBones) }, + { SkinnedEffect_VSSkinnedVertexLightingFourBones, sizeof(SkinnedEffect_VSSkinnedVertexLightingFourBones) }, - { SkinnedEffect_VSSkinnedOneLightOneBone, sizeof(SkinnedEffect_VSSkinnedOneLightOneBone) }, - { SkinnedEffect_VSSkinnedOneLightTwoBones, sizeof(SkinnedEffect_VSSkinnedOneLightTwoBones) }, - { SkinnedEffect_VSSkinnedOneLightFourBones, sizeof(SkinnedEffect_VSSkinnedOneLightFourBones) }, + { SkinnedEffect_VSSkinnedOneLightOneBone, sizeof(SkinnedEffect_VSSkinnedOneLightOneBone) }, + { SkinnedEffect_VSSkinnedOneLightTwoBones, sizeof(SkinnedEffect_VSSkinnedOneLightTwoBones) }, + { SkinnedEffect_VSSkinnedOneLightFourBones, sizeof(SkinnedEffect_VSSkinnedOneLightFourBones) }, - { SkinnedEffect_VSSkinnedPixelLightingOneBone, sizeof(SkinnedEffect_VSSkinnedPixelLightingOneBone) }, - { SkinnedEffect_VSSkinnedPixelLightingTwoBones, sizeof(SkinnedEffect_VSSkinnedPixelLightingTwoBones) }, - { SkinnedEffect_VSSkinnedPixelLightingFourBones, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBones) }, + { SkinnedEffect_VSSkinnedPixelLightingOneBone, sizeof(SkinnedEffect_VSSkinnedPixelLightingOneBone) }, + { SkinnedEffect_VSSkinnedPixelLightingTwoBones, sizeof(SkinnedEffect_VSSkinnedPixelLightingTwoBones) }, + { SkinnedEffect_VSSkinnedPixelLightingFourBones, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBones) }, - { SkinnedEffect_VSSkinnedVertexLightingOneBoneBn, sizeof(SkinnedEffect_VSSkinnedVertexLightingOneBoneBn) }, - { SkinnedEffect_VSSkinnedVertexLightingTwoBonesBn, sizeof(SkinnedEffect_VSSkinnedVertexLightingTwoBonesBn) }, + { SkinnedEffect_VSSkinnedVertexLightingOneBoneBn, sizeof(SkinnedEffect_VSSkinnedVertexLightingOneBoneBn) }, + { SkinnedEffect_VSSkinnedVertexLightingTwoBonesBn, sizeof(SkinnedEffect_VSSkinnedVertexLightingTwoBonesBn) }, { SkinnedEffect_VSSkinnedVertexLightingFourBonesBn, sizeof(SkinnedEffect_VSSkinnedVertexLightingFourBonesBn) }, - { SkinnedEffect_VSSkinnedOneLightOneBoneBn, sizeof(SkinnedEffect_VSSkinnedOneLightOneBoneBn) }, - { SkinnedEffect_VSSkinnedOneLightTwoBonesBn, sizeof(SkinnedEffect_VSSkinnedOneLightTwoBonesBn) }, - { SkinnedEffect_VSSkinnedOneLightFourBonesBn, sizeof(SkinnedEffect_VSSkinnedOneLightFourBonesBn) }, + { SkinnedEffect_VSSkinnedOneLightOneBoneBn, sizeof(SkinnedEffect_VSSkinnedOneLightOneBoneBn) }, + { SkinnedEffect_VSSkinnedOneLightTwoBonesBn, sizeof(SkinnedEffect_VSSkinnedOneLightTwoBonesBn) }, + { SkinnedEffect_VSSkinnedOneLightFourBonesBn, sizeof(SkinnedEffect_VSSkinnedOneLightFourBonesBn) }, - { SkinnedEffect_VSSkinnedPixelLightingOneBoneBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingOneBoneBn) }, - { SkinnedEffect_VSSkinnedPixelLightingTwoBonesBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingTwoBonesBn) }, - { SkinnedEffect_VSSkinnedPixelLightingFourBonesBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBonesBn) }, + { SkinnedEffect_VSSkinnedPixelLightingOneBoneBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingOneBoneBn) }, + { SkinnedEffect_VSSkinnedPixelLightingTwoBonesBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingTwoBonesBn) }, + { SkinnedEffect_VSSkinnedPixelLightingFourBonesBn, sizeof(SkinnedEffect_VSSkinnedPixelLightingFourBonesBn) }, }; - template<> -const int EffectBase::VertexShaderIndices[] = -{ - 0, // vertex lighting, one bone - 0, // vertex lighting, one bone, no fog - 1, // vertex lighting, two bones - 1, // vertex lighting, two bones, no fog - 2, // vertex lighting, four bones - 2, // vertex lighting, four bones, no fog - - 3, // one light, one bone - 3, // one light, one bone, no fog - 4, // one light, two bones - 4, // one light, two bones, no fog - 5, // one light, four bones - 5, // one light, four bones, no fog - - 6, // pixel lighting, one bone - 6, // pixel lighting, one bone, no fog - 7, // pixel lighting, two bones - 7, // pixel lighting, two bones, no fog - 8, // pixel lighting, four bones - 8, // pixel lighting, four bones, no fog - - 9, // vertex lighting (biased vertex normals), one bone - 9, // vertex lighting (biased vertex normals), one bone, no fog - 10, // vertex lighting (biased vertex normals), two bones - 10, // vertex lighting (biased vertex normals), two bones, no fog - 11, // vertex lighting (biased vertex normals), four bones - 11, // vertex lighting (biased vertex normals), four bones, no fog - - 12, // one light (biased vertex normals), one bone - 12, // one light (biased vertex normals), one bone, no fog - 13, // one light (biased vertex normals), two bones - 13, // one light (biased vertex normals), two bones, no fog - 14, // one light (biased vertex normals), four bones - 14, // one light (biased vertex normals), four bones, no fog - - 15, // pixel lighting (biased vertex normals), one bone - 15, // pixel lighting (biased vertex normals), one bone, no fog - 16, // pixel lighting (biased vertex normals), two bones - 16, // pixel lighting (biased vertex normals), two bones, no fog - 17, // pixel lighting (biased vertex normals), four bones - 17, // pixel lighting (biased vertex normals), four bones, no fog +const int EffectBase::VertexShaderIndices[] = { + 0, // vertex lighting, one bone + 0, // vertex lighting, one bone, no fog + 1, // vertex lighting, two bones + 1, // vertex lighting, two bones, no fog + 2, // vertex lighting, four bones + 2, // vertex lighting, four bones, no fog + + 3, // one light, one bone + 3, // one light, one bone, no fog + 4, // one light, two bones + 4, // one light, two bones, no fog + 5, // one light, four bones + 5, // one light, four bones, no fog + + 6, // pixel lighting, one bone + 6, // pixel lighting, one bone, no fog + 7, // pixel lighting, two bones + 7, // pixel lighting, two bones, no fog + 8, // pixel lighting, four bones + 8, // pixel lighting, four bones, no fog + + 9, // vertex lighting (biased vertex normals), one bone + 9, // vertex lighting (biased vertex normals), one bone, no fog + 10, // vertex lighting (biased vertex normals), two bones + 10, // vertex lighting (biased vertex normals), two bones, no fog + 11, // vertex lighting (biased vertex normals), four bones + 11, // vertex lighting (biased vertex normals), four bones, no fog + + 12, // one light (biased vertex normals), one bone + 12, // one light (biased vertex normals), one bone, no fog + 13, // one light (biased vertex normals), two bones + 13, // one light (biased vertex normals), two bones, no fog + 14, // one light (biased vertex normals), four bones + 14, // one light (biased vertex normals), four bones, no fog + + 15, // pixel lighting (biased vertex normals), one bone + 15, // pixel lighting (biased vertex normals), one bone, no fog + 16, // pixel lighting (biased vertex normals), two bones + 16, // pixel lighting (biased vertex normals), two bones, no fog + 17, // pixel lighting (biased vertex normals), four bones + 17, // pixel lighting (biased vertex normals), four bones, no fog }; - template<> -const ShaderBytecode EffectBase::PixelShaderBytecode[] = -{ - { SkinnedEffect_PSSkinnedVertexLighting, sizeof(SkinnedEffect_PSSkinnedVertexLighting) }, +const ShaderBytecode 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, one bone - 1, // vertex lighting, one bone, no fog - 0, // vertex lighting, two bones - 1, // vertex lighting, two bones, no fog - 0, // vertex lighting, four bones - 1, // vertex lighting, four bones, no fog - - 0, // one light, one bone - 1, // one light, one bone, no fog - 0, // one light, two bones - 1, // one light, two bones, no fog - 0, // one light, four bones - 1, // one light, four bones, no fog - - 2, // pixel lighting, one bone - 2, // pixel lighting, one bone, no fog - 2, // pixel lighting, two bones - 2, // pixel lighting, two bones, no fog - 2, // pixel lighting, four bones - 2, // pixel lighting, four bones, no fog - - 0, // vertex lighting (biased vertex normals), one bone - 1, // vertex lighting (biased vertex normals), one bone, no fog - 0, // vertex lighting (biased vertex normals), two bones - 1, // vertex lighting (biased vertex normals), two bones, no fog - 0, // vertex lighting (biased vertex normals), four bones - 1, // vertex lighting (biased vertex normals), four bones, no fog - - 0, // one light (biased vertex normals), one bone - 1, // one light (biased vertex normals), one bone, no fog - 0, // one light (biased vertex normals), two bones - 1, // one light (biased vertex normals), two bones, no fog - 0, // one light (biased vertex normals), four bones - 1, // one light (biased vertex normals), four bones, no fog - - 2, // pixel lighting (biased vertex normals), one bone - 2, // pixel lighting (biased vertex normals), one bone, no fog - 2, // pixel lighting (biased vertex normals), two bones - 2, // pixel lighting (biased vertex normals), two bones, no fog - 2, // pixel lighting (biased vertex normals), four bones - 2, // pixel lighting (biased vertex normals), four bones, no fog +const int EffectBase::PixelShaderIndices[] = { + 0, // vertex lighting, one bone + 1, // vertex lighting, one bone, no fog + 0, // vertex lighting, two bones + 1, // vertex lighting, two bones, no fog + 0, // vertex lighting, four bones + 1, // vertex lighting, four bones, no fog + + 0, // one light, one bone + 1, // one light, one bone, no fog + 0, // one light, two bones + 1, // one light, two bones, no fog + 0, // one light, four bones + 1, // one light, four bones, no fog + + 2, // pixel lighting, one bone + 2, // pixel lighting, one bone, no fog + 2, // pixel lighting, two bones + 2, // pixel lighting, two bones, no fog + 2, // pixel lighting, four bones + 2, // pixel lighting, four bones, no fog + + 0, // vertex lighting (biased vertex normals), one bone + 1, // vertex lighting (biased vertex normals), one bone, no fog + 0, // vertex lighting (biased vertex normals), two bones + 1, // vertex lighting (biased vertex normals), two bones, no fog + 0, // vertex lighting (biased vertex normals), four bones + 1, // vertex lighting (biased vertex normals), four bones, no fog + + 0, // one light (biased vertex normals), one bone + 1, // one light (biased vertex normals), one bone, no fog + 0, // one light (biased vertex normals), two bones + 1, // one light (biased vertex normals), two bones, no fog + 0, // one light (biased vertex normals), four bones + 1, // one light (biased vertex normals), four bones, no fog + + 2, // pixel lighting (biased vertex normals), one bone + 2, // pixel lighting (biased vertex normals), one bone, no fog + 2, // pixel lighting (biased vertex normals), two bones + 2, // pixel lighting (biased vertex normals), two 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_ ID3D11Device* device) : EffectBase(device), - preferPerPixelLighting(false), - biasedVertexNormals(false), - weightsPerVertex(4) -{ - 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); + preferPerPixelLighting(false), + biasedVertexNormals(false), + weightsPerVertex(4) +{ + 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++) { @@ -298,7 +300,6 @@ SkinnedEffect::Impl::Impl(_In_ ID3D11Device* device) } } - int SkinnedEffect::Impl::GetCurrentShaderPermutation() const noexcept { int permutation = 0; @@ -339,7 +340,6 @@ int SkinnedEffect::Impl::GetCurrentShaderPermutation() const noexcept return permutation; } - // Sets our state onto the D3D device. void SkinnedEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) { @@ -350,13 +350,17 @@ void SkinnedEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) 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); // Set the texture. - ID3D11ShaderResourceView* textures[1] = - { - (texture) ? texture.Get() : GetDefaultTexture() - }; + ID3D11ShaderResourceView* textures[1] = { (texture) ? texture.Get() : GetDefaultTexture() }; deviceContext->PSSetShaderResources(0, 1, textures); @@ -364,17 +368,14 @@ void SkinnedEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) ApplyShaders(deviceContext, GetCurrentShaderPermutation()); } - // Public constructor. SkinnedEffect::SkinnedEffect(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext) @@ -382,13 +383,11 @@ void SkinnedEffect::Apply(_In_ ID3D11DeviceContext* deviceContext) pImpl->Apply(deviceContext); } - void SkinnedEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) { pImpl->GetVertexShaderBytecode(pImpl->GetCurrentShaderPermutation(), pShaderByteCode, pByteCodeLength); } - // Camera settings. void XM_CALLCONV SkinnedEffect::SetWorld(FXMMATRIX value) { @@ -397,7 +396,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; @@ -405,7 +403,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; @@ -413,17 +410,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) { @@ -432,7 +428,6 @@ void XM_CALLCONV SkinnedEffect::SetDiffuseColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::MaterialColor; } - void XM_CALLCONV SkinnedEffect::SetEmissiveColor(FXMVECTOR value) { pImpl->lights.emissiveColor = value; @@ -440,7 +435,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). @@ -449,7 +443,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). @@ -458,7 +451,6 @@ void SkinnedEffect::SetSpecularPower(float value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void SkinnedEffect::DisableSpecular() { // Set specular color to black, power to 1 @@ -469,7 +461,6 @@ void SkinnedEffect::DisableSpecular() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - void SkinnedEffect::SetAlpha(float value) { pImpl->lights.alpha = value; @@ -477,16 +468,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 SkinnedEffect::SetLightingEnabled(bool value) { @@ -496,13 +485,11 @@ void SkinnedEffect::SetLightingEnabled(bool value) } } - void SkinnedEffect::SetPerPixelLighting(bool value) { pImpl->preferPerPixelLighting = value; } - void XM_CALLCONV SkinnedEffect::SetAmbientLightColor(FXMVECTOR value) { pImpl->lights.ambientLightColor = value; @@ -510,13 +497,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); @@ -526,25 +512,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::SetFogEnabled(bool value) { @@ -553,7 +535,6 @@ void SkinnedEffect::SetFogEnabled(bool value) pImpl->dirtyFlags |= EffectDirtyFlags::FogEnable; } - void SkinnedEffect::SetFogStart(float value) { pImpl->fog.start = value; @@ -561,7 +542,6 @@ void SkinnedEffect::SetFogStart(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void SkinnedEffect::SetFogEnd(float value) { pImpl->fog.end = value; @@ -569,7 +549,6 @@ void SkinnedEffect::SetFogEnd(float value) pImpl->dirtyFlags |= EffectDirtyFlags::FogVector; } - void XM_CALLCONV SkinnedEffect::SetFogColor(FXMVECTOR value) { pImpl->constants.fogColor = value; @@ -577,20 +556,16 @@ void XM_CALLCONV SkinnedEffect::SetFogColor(FXMVECTOR value) pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Texture settings. void SkinnedEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->texture = value; } - // Animation settings. void SkinnedEffect::SetWeightsPerVertex(int value) { - if ((value != 1) && - (value != 2) && - (value != 4)) + if ((value != 1) && (value != 2) && (value != 4)) { throw std::invalid_argument("WeightsPerVertex must be 1, 2, or 4"); } @@ -598,7 +573,6 @@ void SkinnedEffect::SetWeightsPerVertex(int value) pImpl->weightsPerVertex = value; } - void SkinnedEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (count > MaxBones) @@ -608,22 +582,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; @@ -638,7 +611,6 @@ void SkinnedEffect::ResetBoneTransforms() pImpl->dirtyFlags |= EffectDirtyFlags::ConstantBuffer; } - // Normal compression settings. void SkinnedEffect::SetBiasedVertexNormals(bool value) { diff --git a/Src/SpriteBatch.cpp b/Src/SpriteBatch.cpp index 5bd78366..97b863cf 100644 --- a/Src/SpriteBatch.cpp +++ b/Src/SpriteBatch.cpp @@ -41,7 +41,6 @@ namespace return device; } - // Helper converts a RECT to XMVECTOR. inline XMVECTOR LoadRect(_In_ RECT const* rect) { @@ -54,51 +53,48 @@ namespace return v; } -} - +} // namespace // Internal SpriteBatch implementation class. XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew { public: - explicit Impl(_In_ ID3D11DeviceContext* deviceContext); + explicit Impl(_In_ ID3D11DeviceContext * deviceContext); - 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(SpriteSortMode sortMode, - _In_opt_ ID3D11BlendState* blendState, - _In_opt_ ID3D11SamplerState* samplerState, - _In_opt_ ID3D11DepthStencilState* depthStencilState, - _In_opt_ ID3D11RasterizerState* rasterizerState, + _In_opt_ ID3D11BlendState * blendState, + _In_opt_ ID3D11SamplerState * samplerState, + _In_opt_ ID3D11DepthStencilState * depthStencilState, + _In_opt_ ID3D11RasterizerState * rasterizerState, const std::function& setCustomShaders, - FXMMATRIX transformMatrix); - void End(); + FXMMATRIX transformMatrix); + void End(); - void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, - FXMVECTOR destination, + void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView * texture, + FXMVECTOR destination, _In_opt_ RECT const* sourceRectangle, - FXMVECTOR color, - FXMVECTOR originRotationDepth, - unsigned int flags); - + 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; ID3D11ShaderResourceView* texture; - unsigned int flags; - + 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"); @@ -106,10 +102,10 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew DXGI_MODE_ROTATION mRotation; - bool mSetViewport; + bool mSetViewport; D3D11_VIEWPORT mViewPort; - XMMATRIX GetViewportTransform(_In_ ID3D11DeviceContext* deviceContext, DXGI_MODE_ROTATION rotation); + XMMATRIX GetViewportTransform(_In_ ID3D11DeviceContext * deviceContext, DXGI_MODE_ROTATION rotation); private: // Implementation helper methods. @@ -119,23 +115,21 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew void SortSprites(); void GrowSortedSprites(); - void RenderBatch(_In_ ID3D11ShaderResourceView* texture, _In_reads_(count) SpriteInfo const* const* sprites, size_t count); + void RenderBatch(_In_ ID3D11ShaderResourceView * texture, _In_reads_(count) SpriteInfo const* const* sprites, 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); - - static XMVECTOR GetTextureSize(_In_ ID3D11ShaderResourceView* texture); + FXMVECTOR textureSize, + FXMVECTOR inverseTextureSize); + static XMVECTOR GetTextureSize(_In_ ID3D11ShaderResourceView * texture); // 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; // Queue of sprites waiting to be drawn. std::unique_ptr mSpriteQueue; @@ -143,31 +137,27 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew 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 // mSpriteQueue array, and we take care to keep them in order when sorting is disabled. std::vector mSortedSprites; - // If each SpriteInfo instance held a refcount on its texture, could end up with // many redundant AddRef/Release calls on the same object, so instead we use // this separate list to hold just a single refcount each time we change texture. std::vector> mSpriteTextureReferences; - // Mode settings from the last Begin call. bool mInBeginEndPair; - SpriteSortMode mSortMode; - ComPtr mBlendState; - ComPtr mSamplerState; + SpriteSortMode mSortMode; + ComPtr mBlendState; + ComPtr mSamplerState; ComPtr mDepthStencilState; - ComPtr mRasterizerState; - std::function mSetCustomShaders; - XMMATRIX mTransformMatrix; - + ComPtr mRasterizerState; + std::function mSetCustomShaders; + XMMATRIX mTransformMatrix; // Only one of these helpers is allocated per D3D device, even if there are multiple SpriteBatch instances. struct DeviceResources @@ -175,9 +165,9 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew DeviceResources(_In_ ID3D11Device* device); ComPtr vertexShader; - ComPtr pixelShader; - ComPtr inputLayout; - ComPtr indexBuffer; + ComPtr pixelShader; + ComPtr inputLayout; + ComPtr indexBuffer; CommonStates stateObjects; @@ -188,7 +178,6 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew static std::vector CreateIndexValues(); }; - // Only one of these helpers is allocated per D3D device context, even if there are multiple SpriteBatch instances. struct ContextResources { @@ -212,21 +201,18 @@ XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew void CreateVertexBuffer(); }; - // Per-device and per-context data. - std::shared_ptr mDeviceResources; + std::shared_ptr mDeviceResources; std::shared_ptr mContextResources; - static SharedResourcePool deviceResourcesPool; + static SharedResourcePool deviceResourcesPool; static SharedResourcePool contextResourcesPool; }; - // Global pools of per-device and per-context SpriteBatch resources. -SharedResourcePool SpriteBatch::Impl::deviceResourcesPool; +SharedResourcePool SpriteBatch::Impl::deviceResourcesPool; SharedResourcePool SpriteBatch::Impl::contextResourcesPool; - // Constants. const XMMATRIX SpriteBatch::MatrixIdentity = XMMatrixIdentity(); const XMFLOAT2 SpriteBatch::Float2Zero(0, 0); @@ -249,38 +235,25 @@ SpriteBatch::Impl::DeviceResources::DeviceResources(_In_ ID3D11Device* device) CreateIndexBuffer(device); } - // Creates the SpriteBatch shaders and input layout. void SpriteBatch::Impl::DeviceResources::CreateShaders(_In_ ID3D11Device* device) { ThrowIfFailed( - device->CreateVertexShader(SpriteEffect_SpriteVertexShader, - sizeof(SpriteEffect_SpriteVertexShader), - nullptr, - &vertexShader) - ); + device->CreateVertexShader(SpriteEffect_SpriteVertexShader, sizeof(SpriteEffect_SpriteVertexShader), nullptr, &vertexShader)); - ThrowIfFailed( - device->CreatePixelShader(SpriteEffect_SpritePixelShader, - sizeof(SpriteEffect_SpritePixelShader), - nullptr, - &pixelShader) - ); + ThrowIfFailed(device->CreatePixelShader(SpriteEffect_SpritePixelShader, sizeof(SpriteEffect_SpritePixelShader), nullptr, &pixelShader)); - ThrowIfFailed( - device->CreateInputLayout(VertexPositionColorTexture::InputElements, - VertexPositionColorTexture::InputElementCount, - SpriteEffect_SpriteVertexShader, - sizeof(SpriteEffect_SpriteVertexShader), - &inputLayout) - ); + ThrowIfFailed(device->CreateInputLayout(VertexPositionColorTexture::InputElements, + VertexPositionColorTexture::InputElementCount, + SpriteEffect_SpriteVertexShader, + sizeof(SpriteEffect_SpriteVertexShader), + &inputLayout)); SetDebugObjectName(vertexShader.Get(), "DirectXTK:SpriteBatch"); SetDebugObjectName(pixelShader.Get(), "DirectXTK:SpriteBatch"); SetDebugObjectName(inputLayout.Get(), "DirectXTK:SpriteBatch"); } - // Creates the SpriteBatch index buffer. void SpriteBatch::Impl::DeviceResources::CreateIndexBuffer(_In_ ID3D11Device* device) { @@ -290,20 +263,17 @@ void SpriteBatch::Impl::DeviceResources::CreateIndexBuffer(_In_ ID3D11Device* de indexBufferDesc.ByteWidth = sizeof(short) * MaxBatchSize * IndicesPerSprite; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; - indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; + indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; auto indexValues = CreateIndexValues(); D3D11_SUBRESOURCE_DATA indexDataDesc = { indexValues.data(), 0, 0 }; - ThrowIfFailed( - device->CreateBuffer(&indexBufferDesc, &indexDataDesc, &indexBuffer) - ); + ThrowIfFailed(device->CreateBuffer(&indexBufferDesc, &indexDataDesc, &indexBuffer)); SetDebugObjectName(indexBuffer.Get(), "DirectXTK:SpriteBatch"); } - // Helper for populating the SpriteBatch index buffer. std::vector SpriteBatch::Impl::DeviceResources::CreateIndexValues() { @@ -327,12 +297,11 @@ std::vector SpriteBatch::Impl::DeviceResources::CreateIndexValues() return indices; } - // Per-context constructor. SpriteBatch::Impl::ContextResources::ContextResources(_In_ ID3D11DeviceContext* context) - :constantBuffer(GetDevice(context).Get()), - vertexBufferPosition(0), - inImmediateMode(false) + : constantBuffer(GetDevice(context).Get()), + vertexBufferPosition(0), + inImmediateMode(false) { #if defined(_XBOX_ONE) && defined(_TITLE) ThrowIfFailed(context->QueryInterface(IID_GRAPHICS_PPV_ARGS(deviceContext.GetAddressOf()))); @@ -345,16 +314,15 @@ SpriteBatch::Impl::ContextResources::ContextResources(_In_ ID3D11DeviceContext* CreateVertexBuffer(); } - // Creates the SpriteBatch vertex buffer. void SpriteBatch::Impl::ContextResources::CreateVertexBuffer() { #if defined(_XBOX_ONE) && defined(_TITLE) D3D11_BUFFER_DESC vertexBufferDesc = {}; - vertexBufferDesc.ByteWidth = sizeof(VertexPositionColorTexture) * MaxBatchSize * VerticesPerSprite; - vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; + vertexBufferDesc.ByteWidth = sizeof(VertexPositionColorTexture) * MaxBatchSize * VerticesPerSprite; + vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; auto device = GetDevice(deviceContext.Get()); @@ -362,67 +330,60 @@ void SpriteBatch::Impl::ContextResources::CreateVertexBuffer() ComPtr deviceX; ThrowIfFailed(device.As(&deviceX)); - ThrowIfFailed( - deviceX->CreatePlacementBuffer(&vertexBufferDesc, nullptr, &vertexBuffer) - ); + ThrowIfFailed(deviceX->CreatePlacementBuffer(&vertexBufferDesc, nullptr, &vertexBuffer)); SetDebugObjectName(vertexBuffer.Get(), "DirectXTK:SpriteBatch"); #else D3D11_BUFFER_DESC vertexBufferDesc = {}; - vertexBufferDesc.ByteWidth = sizeof(VertexPositionColorTexture) * MaxBatchSize * VerticesPerSprite; - vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC; + vertexBufferDesc.ByteWidth = sizeof(VertexPositionColorTexture) * MaxBatchSize * VerticesPerSprite; + vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC; vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - ThrowIfFailed( - GetDevice(deviceContext.Get())->CreateBuffer(&vertexBufferDesc, nullptr, &vertexBuffer) - ); + ThrowIfFailed(GetDevice(deviceContext.Get())->CreateBuffer(&vertexBufferDesc, nullptr, &vertexBuffer)); SetDebugObjectName(vertexBuffer.Get(), "DirectXTK:SpriteBatch"); #endif } - // Per-SpriteBatch constructor. SpriteBatch::Impl::Impl(_In_ ID3D11DeviceContext* deviceContext) : mRotation(DXGI_MODE_ROTATION_IDENTITY), - mSetViewport(false), - mViewPort{}, - mSpriteQueueCount(0), - mSpriteQueueArraySize(0), - mInBeginEndPair(false), - mSortMode(SpriteSortMode_Deferred), - mTransformMatrix(MatrixIdentity) + mSetViewport(false), + mViewPort{}, + mSpriteQueueCount(0), + mSpriteQueueArraySize(0), + mInBeginEndPair(false), + mSortMode(SpriteSortMode_Deferred), + mTransformMatrix(MatrixIdentity) { if (!deviceContext) throw std::invalid_argument("Direct3D device context is null"); - mDeviceResources = deviceResourcesPool.DemandCreate(GetDevice(deviceContext).Get()); + mDeviceResources = deviceResourcesPool.DemandCreate(GetDevice(deviceContext).Get()); mContextResources = contextResourcesPool.DemandCreate(deviceContext); } - // Begins a batch of sprite drawing operations. -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Impl::Begin(SpriteSortMode sortMode, - ID3D11BlendState* blendState, - ID3D11SamplerState* samplerState, - ID3D11DepthStencilState* depthStencilState, - ID3D11RasterizerState* rasterizerState, - const std::function& setCustomShaders, - FXMMATRIX transformMatrix) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Impl::Begin(SpriteSortMode sortMode, + ID3D11BlendState* blendState, + ID3D11SamplerState* samplerState, + ID3D11DepthStencilState* depthStencilState, + ID3D11RasterizerState* rasterizerState, + const std::function& setCustomShaders, + FXMMATRIX transformMatrix) { if (mInBeginEndPair) throw std::logic_error("Cannot nest Begin calls on a single SpriteBatch"); - mSortMode = sortMode; - mBlendState = blendState; - mSamplerState = samplerState; + mSortMode = sortMode; + mBlendState = blendState; + mSamplerState = samplerState; mDepthStencilState = depthStencilState; - mRasterizerState = rasterizerState; - mSetCustomShaders = setCustomShaders; - mTransformMatrix = transformMatrix; + mRasterizerState = rasterizerState; + mSetCustomShaders = setCustomShaders; + mTransformMatrix = transformMatrix; if (sortMode == SpriteSortMode_Immediate) { @@ -438,7 +399,6 @@ void XM_CALLCONV SpriteBatch::Impl::Begin(SpriteSortMode sortMode, mInBeginEndPair = true; } - // Ends a batch of sprite drawing operations. void SpriteBatch::Impl::End() { @@ -467,15 +427,13 @@ void SpriteBatch::Impl::End() mInBeginEndPair = false; } - // Adds a single sprite to the queue. -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Impl::Draw(ID3D11ShaderResourceView* texture, - FXMVECTOR destination, - RECT const* sourceRectangle, - FXMVECTOR color, - FXMVECTOR originRotationDepth, - unsigned int flags) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Impl::Draw(ID3D11ShaderResourceView* texture, + FXMVECTOR destination, + RECT const* sourceRectangle, + FXMVECTOR color, + FXMVECTOR originRotationDepth, + unsigned int flags) { if (!texture) throw std::invalid_argument("Texture cannot be null"); @@ -522,7 +480,7 @@ void XM_CALLCONV SpriteBatch::Impl::Draw(ID3D11ShaderResourceView* texture, XMStoreFloat4A(&sprite->originRotationDepth, originRotationDepth); sprite->texture = texture; - sprite->flags = flags; + sprite->flags = flags; if (mSortMode == SpriteSortMode_Immediate) { @@ -545,7 +503,6 @@ void XM_CALLCONV SpriteBatch::Impl::Draw(ID3D11ShaderResourceView* texture, } } - // Dynamically expands the array used to store pending sprite information. void SpriteBatch::Impl::GrowSpriteQueue() { @@ -562,24 +519,23 @@ 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() { auto deviceContext = mContextResources->deviceContext.Get(); // Set state objects. - auto blendState = mBlendState ? mBlendState.Get() : mDeviceResources->stateObjects.AlphaBlend(); + auto blendState = mBlendState ? mBlendState.Get() : mDeviceResources->stateObjects.AlphaBlend(); auto depthStencilState = mDepthStencilState ? mDepthStencilState.Get() : mDeviceResources->stateObjects.DepthNone(); - auto rasterizerState = mRasterizerState ? mRasterizerState.Get() : mDeviceResources->stateObjects.CullCounterClockwise(); - auto samplerState = mSamplerState ? mSamplerState.Get() : mDeviceResources->stateObjects.LinearClamp(); + auto rasterizerState = mRasterizerState ? mRasterizerState.Get() : mDeviceResources->stateObjects.CullCounterClockwise(); + auto samplerState = mSamplerState ? mSamplerState.Get() : mDeviceResources->stateObjects.LinearClamp(); deviceContext->OMSetBlendState(blendState, nullptr, 0xFFFFFFFF); deviceContext->OMSetDepthStencilState(depthStencilState, 0); @@ -594,7 +550,7 @@ void SpriteBatch::Impl::PrepareForRendering() // Set the vertex and index buffer. #if !defined(_XBOX_ONE) || !defined(_TITLE) - auto vertexBuffer = mContextResources->vertexBuffer.Get(); + auto vertexBuffer = mContextResources->vertexBuffer.Get(); constexpr UINT vertexStride = sizeof(VertexPositionColorTexture); constexpr UINT vertexOffset = 0; @@ -604,9 +560,9 @@ void SpriteBatch::Impl::PrepareForRendering() deviceContext->IASetIndexBuffer(mDeviceResources->indexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0); // Set the transform matrix. - const XMMATRIX transformMatrix = (mRotation == DXGI_MODE_ROTATION_UNSPECIFIED) - ? mTransformMatrix - : (mTransformMatrix * GetViewportTransform(deviceContext, mRotation)); + const XMMATRIX transformMatrix = (mRotation == DXGI_MODE_ROTATION_UNSPECIFIED) ? + mTransformMatrix : + (mTransformMatrix * GetViewportTransform(deviceContext, mRotation)); #if defined(_XBOX_ONE) && defined(_TITLE) void* grfxMemory; @@ -634,7 +590,6 @@ void SpriteBatch::Impl::PrepareForRendering() } } - // Sends queued sprites to the graphics device. void SpriteBatch::Impl::FlushBatch() { @@ -645,7 +600,7 @@ void SpriteBatch::Impl::FlushBatch() // Walk through the sorted sprite list, looking for adjacent entries that share a texture. ID3D11ShaderResourceView* batchTexture = nullptr; - size_t batchStart = 0; + size_t batchStart = 0; for (size_t pos = 0; pos < mSpriteQueueCount; pos++) { @@ -662,7 +617,7 @@ void SpriteBatch::Impl::FlushBatch() } batchTexture = texture; - batchStart = pos; + batchStart = pos; } } @@ -682,7 +637,6 @@ void SpriteBatch::Impl::FlushBatch() } } - // Sorts the array of queued sprites. void SpriteBatch::Impl::SortSprites() { @@ -696,7 +650,8 @@ void SpriteBatch::Impl::SortSprites() { case SpriteSortMode_Texture: // Sort by texture. - std::sort(mSortedSprites.begin(), mSortedSprites.begin() + static_cast(mSpriteQueueCount), + std::sort(mSortedSprites.begin(), + mSortedSprites.begin() + static_cast(mSpriteQueueCount), [](SpriteInfo const* x, SpriteInfo const* y) noexcept -> bool { return x->texture < y->texture; @@ -705,7 +660,8 @@ void SpriteBatch::Impl::SortSprites() case SpriteSortMode_BackToFront: // Sort back to front. - std::sort(mSortedSprites.begin(), mSortedSprites.begin() + static_cast(mSpriteQueueCount), + std::sort(mSortedSprites.begin(), + mSortedSprites.begin() + static_cast(mSpriteQueueCount), [](SpriteInfo const* x, SpriteInfo const* y) noexcept -> bool { return x->originRotationDepth.w > y->originRotationDepth.w; @@ -714,19 +670,18 @@ void SpriteBatch::Impl::SortSprites() case SpriteSortMode_FrontToBack: // Sort front to back. - std::sort(mSortedSprites.begin(), mSortedSprites.begin() + static_cast(mSpriteQueueCount), + std::sort(mSortedSprites.begin(), + mSortedSprites.begin() + static_cast(mSpriteQueueCount), [](SpriteInfo const* x, SpriteInfo const* y) noexcept -> bool { return x->originRotationDepth.w < y->originRotationDepth.w; }); break; - default: - break; + default: break; } } - // Populates the mSortedSprites vector with pointers to individual elements of the mSpriteQueue array. void SpriteBatch::Impl::GrowSortedSprites() { @@ -740,17 +695,16 @@ void SpriteBatch::Impl::GrowSortedSprites() } } - // Submits a batch of sprites to the GPU. -_Use_decl_annotations_ -void SpriteBatch::Impl::RenderBatch(ID3D11ShaderResourceView* texture, SpriteInfo const* const* sprites, size_t count) +_Use_decl_annotations_ void +SpriteBatch::Impl::RenderBatch(ID3D11ShaderResourceView* texture, SpriteInfo const* const* sprites, size_t count) { auto deviceContext = mContextResources->deviceContext.Get(); // Draw using the specified texture. deviceContext->PSSetShaderResources(0, 1, &texture); - const XMVECTOR textureSize = GetTextureSize(texture); + const XMVECTOR textureSize = GetTextureSize(texture); const XMVECTOR inverseTextureSize = XMVectorReciprocal(textureSize); while (count > 0) @@ -777,24 +731,24 @@ void SpriteBatch::Impl::RenderBatch(ID3D11ShaderResourceView* texture, SpriteInf } } - #if defined(_XBOX_ONE) && defined(_TITLE) - void *grfxMemory = GraphicsMemory::Get().Allocate(deviceContext, sizeof(VertexPositionColorTexture) * batchSize * VerticesPerSprite, 64); +#if defined(_XBOX_ONE) && defined(_TITLE) + void* grfxMemory + = GraphicsMemory::Get().Allocate(deviceContext, sizeof(VertexPositionColorTexture) * batchSize * VerticesPerSprite, 64); auto vertices = static_cast(grfxMemory); - #else - // Lock the vertex buffer. +#else + // Lock the vertex buffer. const D3D11_MAP mapType = (mContextResources->vertexBufferPosition == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE; D3D11_MAPPED_SUBRESOURCE mappedBuffer; - ThrowIfFailed( - deviceContext->Map(mContextResources->vertexBuffer.Get(), 0, mapType, 0, &mappedBuffer) - ); + ThrowIfFailed(deviceContext->Map(mContextResources->vertexBuffer.Get(), 0, mapType, 0, &mappedBuffer)); - auto vertices = static_cast(mappedBuffer.pData) + mContextResources->vertexBufferPosition * VerticesPerSprite; - #endif + auto vertices + = static_cast(mappedBuffer.pData) + mContextResources->vertexBufferPosition * VerticesPerSprite; +#endif - // Generate sprite vertex data. + // Generate sprite vertex data. for (size_t i = 0; i < batchSize; i++) { assert(i < count); @@ -804,51 +758,49 @@ void SpriteBatch::Impl::RenderBatch(ID3D11ShaderResourceView* texture, SpriteInf vertices += VerticesPerSprite; } - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) deviceContext->IASetPlacementVertexBuffer(0, mContextResources->vertexBuffer.Get(), grfxMemory, sizeof(VertexPositionColorTexture)); - #else +#else deviceContext->Unmap(mContextResources->vertexBuffer.Get(), 0); - #endif +#endif - // Ok lads, the time has come for us draw ourselves some sprites! + // Ok lads, the time has come for us draw ourselves some sprites! const auto startIndex = static_cast(mContextResources->vertexBufferPosition * IndicesPerSprite); const auto indexCount = static_cast(batchSize * IndicesPerSprite); deviceContext->DrawIndexed(indexCount, startIndex, 0); // Advance the buffer position. - #if !defined(_XBOX_ONE) || !defined(_TITLE) +#if !defined(_XBOX_ONE) || !defined(_TITLE) mContextResources->vertexBufferPosition += batchSize; - #endif +#endif sprites += batchSize; count -= batchSize; } } - // 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) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, + VertexPositionColorTexture* vertices, + FXMVECTOR textureSize, + FXMVECTOR inverseTextureSize) { // 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); @@ -856,7 +808,7 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, // 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 @@ -893,8 +845,7 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, } // 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 } } }, @@ -908,8 +859,8 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, // 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; @@ -935,13 +886,13 @@ void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, 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); } } - // Helper looks up the size of the specified texture. XMVECTOR SpriteBatch::Impl::GetTextureSize(_In_ ID3D11ShaderResourceView* texture) { @@ -964,14 +915,11 @@ XMVECTOR SpriteBatch::Impl::GetTextureSize(_In_ ID3D11ShaderResourceView* textur texture2D->GetDesc(&desc); // Convert to vector format. - const XMVECTOR size = XMVectorMergeXY( - XMLoadInt(&desc.Width), - XMLoadInt(&desc.Height)); + const XMVECTOR size = XMVectorMergeXY(XMLoadInt(&desc.Width), XMLoadInt(&desc.Height)); return XMConvertVectorUIntToFloat(size, 0); } - // Generates a viewport transform matrix for rendering sprites using x-right y-down screen pixel coordinates. XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ ID3D11DeviceContext* deviceContext, DXGI_MODE_ROTATION rotation) { @@ -992,94 +940,57 @@ XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ ID3D11DeviceContext* devic 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. SpriteBatch::SpriteBatch(_In_ ID3D11DeviceContext* deviceContext) : pImpl(std::make_unique(deviceContext)) {} - -SpriteBatch::SpriteBatch(SpriteBatch&&) noexcept = default; -SpriteBatch& SpriteBatch::operator= (SpriteBatch&&) noexcept = default; -SpriteBatch::~SpriteBatch() = default; - - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Begin(SpriteSortMode sortMode, - ID3D11BlendState* blendState, - ID3D11SamplerState* samplerState, - ID3D11DepthStencilState* depthStencilState, - ID3D11RasterizerState* rasterizerState, - std::function setCustomShaders, - FXMMATRIX transformMatrix) +SpriteBatch::SpriteBatch(SpriteBatch&&) noexcept = default; +SpriteBatch& SpriteBatch::operator=(SpriteBatch&&) noexcept = default; +SpriteBatch::~SpriteBatch() = default; + +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Begin(SpriteSortMode sortMode, + ID3D11BlendState* blendState, + ID3D11SamplerState* samplerState, + ID3D11DepthStencilState* depthStencilState, + ID3D11RasterizerState* rasterizerState, + std::function setCustomShaders, + FXMMATRIX transformMatrix) { pImpl->Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, setCustomShaders, transformMatrix); } - void SpriteBatch::End() { pImpl->End(); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, XMFLOAT2 const& position, FXMVECTOR color) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, XMFLOAT2 const& position, FXMVECTOR color) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(XMLoadFloat2(&position), g_XMOne); // x, y, 1, 1 pImpl->Draw(texture, destination, nullptr, color, g_XMZero, 0); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, - 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(ID3D11ShaderResourceView* texture, + 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 @@ -1088,17 +999,15 @@ void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, pImpl->Draw(texture, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, - 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(ID3D11ShaderResourceView* texture, + 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 @@ -1107,26 +1016,22 @@ void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, pImpl->Draw(texture, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, FXMVECTOR position, FXMVECTOR color) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, FXMVECTOR position, FXMVECTOR color) { const XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(position, g_XMOne); // x, y, 1, 1 pImpl->Draw(texture, destination, nullptr, color, g_XMZero, 0); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, - 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(ID3D11ShaderResourceView* texture, + 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 @@ -1137,17 +1042,15 @@ void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, pImpl->Draw(texture, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, - 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(ID3D11ShaderResourceView* texture, + 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 @@ -1158,55 +1061,53 @@ void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, pImpl->Draw(texture, destination, sourceRectangle, color, originRotationDepth, static_cast(effects)); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, RECT const& destinationRectangle, FXMVECTOR color) +_Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, + RECT const& destinationRectangle, + FXMVECTOR color) { const XMVECTOR destination = LoadRect(&destinationRectangle); // x, y, w, h pImpl->Draw(texture, destination, nullptr, color, g_XMZero, Impl::SpriteInfo::DestSizeInPixels); } - -_Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(ID3D11ShaderResourceView* texture, - 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(ID3D11ShaderResourceView* texture, + 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, destination, sourceRectangle, color, originRotationDepth, static_cast(effects) | Impl::SpriteInfo::DestSizeInPixels); + pImpl->Draw(texture, + 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 D3D11_VIEWPORT& viewPort) { pImpl->mSetViewport = true; - pImpl->mViewPort = viewPort; + pImpl->mViewPort = viewPort; } - -_Use_decl_annotations_ -void SpriteBatch::GetViewportTransform(ID3D11DeviceContext* deviceContext, XMMATRIX& transformMatrix) const +_Use_decl_annotations_ void SpriteBatch::GetViewportTransform(ID3D11DeviceContext* deviceContext, XMMATRIX& transformMatrix) const { transformMatrix = pImpl->GetViewportTransform(deviceContext, pImpl->mRotation); } diff --git a/Src/SpriteFont.cpp b/Src/SpriteFont.cpp index 5af530f4..efd5e042 100644 --- a/Src/SpriteFont.cpp +++ b/Src/SpriteFont.cpp @@ -20,23 +20,18 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; - // Internal SpriteFont implementation class. class SpriteFont::Impl { public: - Impl(_In_ ID3D11Device* device, - _In_ BinaryReader* reader, - bool forceSRGB) noexcept(false); - Impl(_In_ ID3D11ShaderResourceView* texture, - _In_reads_(glyphCount) Glyph const* glyphs, - size_t glyphCount, - float lineSpacing) noexcept(false); - - Impl(const Impl&) = delete; + Impl(_In_ ID3D11Device* device, _In_ BinaryReader* reader, bool forceSRGB) noexcept(false); + Impl(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, size_t glyphCount, float lineSpacing) noexcept( + false); + + 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; @@ -46,64 +41,59 @@ 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 texture; - std::vector glyphs; - std::vector glyphsIndex; - Glyph const* defaultGlyph; - float lineSpacing; - bool pixelAlignment; + std::vector glyphs; + std::vector glyphsIndex; + Glyph const* defaultGlyph; + float lineSpacing; + bool pixelAlignment; private: void CreateTextureResource(_In_ ID3D11Device* device, - 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; + 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( - ID3D11Device* device, - BinaryReader* reader, - bool forceSRGB) noexcept(false) : - defaultGlyph(nullptr), - lineSpacing(0), - pixelAlignment(false), - utfBufferSize(0) +_Use_decl_annotations_ SpriteFont::Impl::Impl(ID3D11Device* device, BinaryReader* reader, bool forceSRGB) noexcept(false) + : defaultGlyph(nullptr), + lineSpacing(0), + pixelAlignment(false), + utfBufferSize(0) { if (!device || !reader) throw std::invalid_argument("Direct3D device is null"); @@ -120,7 +110,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()); @@ -136,19 +126,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 > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) - || (textureHeight > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) - || LoaderHelpers::BitsPerPixel(textureFormat) == 0) + auto textureRows = reader->Read(); + + if (!textureWidth || !textureHeight || !textureStride || !textureRows || (textureWidth > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) + || (textureHeight > D3D11_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"); @@ -169,28 +154,18 @@ SpriteFont::Impl::Impl( } // Create the D3D texture. - CreateTextureResource( - device, - textureWidth, textureHeight, - textureFormat, - textureStride, textureRows, - textureData); + CreateTextureResource(device, textureWidth, textureHeight, textureFormat, textureStride, textureRows, textureData); } - // Constructs a SpriteFont from arbitrary user specified glyph data. _Use_decl_annotations_ -SpriteFont::Impl::Impl( - ID3D11ShaderResourceView* itexture, - Glyph const* iglyphs, - size_t glyphCount, - float ilineSpacing) noexcept(false) : - texture(itexture), - glyphs(iglyphs, iglyphs + glyphCount), - defaultGlyph(nullptr), - lineSpacing(ilineSpacing), - pixelAlignment(false), - utfBufferSize(0) +SpriteFont::Impl::Impl(ID3D11ShaderResourceView* itexture, Glyph const* iglyphs, size_t glyphCount, float ilineSpacing) noexcept(false) + : texture(itexture), + glyphs(iglyphs, iglyphs + glyphCount), + defaultGlyph(nullptr), + lineSpacing(ilineSpacing), + pixelAlignment(false), + utfBufferSize(0) { if (!itexture || !iglyphs) { @@ -210,7 +185,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 { @@ -218,15 +192,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; @@ -235,7 +212,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++) @@ -254,11 +234,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) { @@ -270,7 +251,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 @@ -305,9 +285,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); @@ -319,14 +297,13 @@ void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action, } } - -_Use_decl_annotations_ -void SpriteFont::Impl::CreateTextureResource( - ID3D11Device* device, - 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(ID3D11Device* device, + 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) @@ -336,33 +313,28 @@ void SpriteFont::Impl::CreateTextureResource( } D3D11_TEXTURE2D_DESC desc = {}; - desc.Width = width; - desc.Height = height; - desc.MipLevels = 1; - desc.ArraySize = 1; - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.Usage = D3D11_USAGE_IMMUTABLE; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.Width = width; + desc.Height = height; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_IMMUTABLE; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; D3D11_SUBRESOURCE_DATA initData = { data, stride, static_cast(sliceBytes) }; ComPtr texture2D; - ThrowIfFailed( - device->CreateTexture2D(&desc, &initData, &texture2D) - ); + ThrowIfFailed(device->CreateTexture2D(&desc, &initData, &texture2D)); CD3D11_SHADER_RESOURCE_VIEW_DESC viewDesc(D3D11_SRV_DIMENSION_TEXTURE2D, format); - ThrowIfFailed( - device->CreateShaderResourceView(texture2D.Get(), &viewDesc, texture.ReleaseAndGetAddressOf()) - ); + ThrowIfFailed(device->CreateShaderResourceView(texture2D.Get(), &viewDesc, texture.ReleaseAndGetAddressOf())); SetDebugObjectName(texture.Get(), "DirectXTK:SpriteFont"); SetDebugObjectName(texture2D.Get(), "DirectXTK:SpriteFont"); } - -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) { @@ -374,7 +346,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]); @@ -391,75 +363,110 @@ 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(ID3D11Device* device, wchar_t const* fileName, bool forceSRGB) +_Use_decl_annotations_ SpriteFont::SpriteFont(ID3D11Device* device, wchar_t const* fileName, bool forceSRGB) { BinaryReader reader(fileName); pImpl = std::make_unique(device, &reader, forceSRGB); } - // Construct from a binary blob created by the MakeSpriteFont utility and already loaded into memory. -_Use_decl_annotations_ -SpriteFont::SpriteFont(ID3D11Device* device, uint8_t const* dataBlob, size_t dataSize, bool forceSRGB) +_Use_decl_annotations_ SpriteFont::SpriteFont(ID3D11Device* device, uint8_t const* dataBlob, size_t dataSize, bool forceSRGB) { BinaryReader reader(dataBlob, dataSize); pImpl = std::make_unique(device, &reader, forceSRGB); } - // Construct from arbitrary user specified glyph data (for those not using the MakeSpriteFont utility). -_Use_decl_annotations_ -SpriteFont::SpriteFont(ID3D11ShaderResourceView* texture, Glyph const* glyphs, size_t glyphCount, float lineSpacing) +_Use_decl_annotations_ SpriteFont::SpriteFont(ID3D11ShaderResourceView* texture, Glyph const* glyphs, size_t glyphCount, float lineSpacing) : pImpl(std::make_unique(texture, 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 } } }, @@ -471,14 +478,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); @@ -501,43 +507,43 @@ void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wc } spriteBatch->Draw(pImpl->texture.Get(), position, &glyph->Subrect, color, rotation, offset, scale, effects, layerDepth); - }, true); + }, + 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); @@ -556,18 +562,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; @@ -576,44 +582,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; @@ -622,52 +669,44 @@ 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); } - void SpriteFont::GetSpriteSheet(ID3D11ShaderResourceView** texture) const { if (!texture) @@ -676,32 +715,87 @@ void SpriteFont::GetSpriteSheet(ID3D11ShaderResourceView** texture) const ThrowIfFailed(pImpl->texture.CopyTo(texture)); } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) -SpriteFont::SpriteFont(_In_ ID3D11Device* device, _In_z_ __wchar_t const* fileName, bool forceSRGB) : - SpriteFont(device, reinterpret_cast(fileName), forceSRGB) +SpriteFont::SpriteFont(_In_ ID3D11Device* device, _In_z_ __wchar_t const* fileName, bool forceSRGB) + : SpriteFont(device, reinterpret_cast(fileName), 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 862b11e3..22c36ee9 100644 --- a/Src/ToneMapPostProcess.cpp +++ b/Src/ToneMapPostProcess.cpp @@ -23,13 +23,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) - 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 @@ -45,30 +45,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. @@ -105,60 +128,58 @@ namespace #include "ToneMap_PSACESFilmic_SRGB.inc" #include "ToneMap_PSHDR10.inc" #endif -} +} // namespace namespace { struct ShaderBytecode { void const* code; - size_t length; + size_t length; }; - const ShaderBytecode 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 ShaderBytecode 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) // 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) // MRT Linear EOTF @@ -171,7 +192,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 @@ -189,10 +210,10 @@ namespace public: DeviceResources(_In_ ID3D11Device* device) : stateObjects(device), - mDevice(device), - mVertexShader{}, - mPixelShaders{}, - mMutex{} + mDevice(device), + mVertexShader{}, + mPixelShaders{}, + mMutex{} { if (!device) { @@ -205,16 +226,18 @@ namespace } } - DeviceResources(const DeviceResources&) = delete; + DeviceResources(const DeviceResources&) = delete; DeviceResources& operator=(const DeviceResources&) = delete; - DeviceResources(DeviceResources&&) = delete; + DeviceResources(DeviceResources&&) = delete; DeviceResources& operator=(DeviceResources&&) = delete; // Gets or lazily creates the vertex shader. ID3D11VertexShader* GetVertexShader() { - return DemandCreate(mVertexShader, mMutex, [&](ID3D11VertexShader** pResult) -> HRESULT + return DemandCreate(mVertexShader, + mMutex, + [&](ID3D11VertexShader** pResult) -> HRESULT { HRESULT hr = mDevice->CreateVertexShader(ToneMap_VSQuad, sizeof(ToneMap_VSQuad), nullptr, pResult); @@ -234,9 +257,12 @@ namespace assert(shaderIndex >= 0 && shaderIndex < PixelShaderCount); _Analysis_assume_(shaderIndex >= 0 && shaderIndex < PixelShaderCount); - return DemandCreate(mPixelShaders[shaderIndex], mMutex, [&](ID3D11PixelShader** pResult) -> HRESULT + return DemandCreate(mPixelShaders[shaderIndex], + mMutex, + [&](ID3D11PixelShader** pResult) -> HRESULT { - HRESULT hr = mDevice->CreatePixelShader(pixelShaders[shaderIndex].code, pixelShaders[shaderIndex].length, nullptr, pResult); + HRESULT hr + = mDevice->CreatePixelShader(pixelShaders[shaderIndex].code, pixelShaders[shaderIndex].length, nullptr, pResult); if (SUCCEEDED(hr)) SetDebugObjectName(*pResult, "ToneMapPostProcess"); @@ -245,27 +271,26 @@ namespace }); } - CommonStates stateObjects; + CommonStates stateObjects; protected: - ComPtr mDevice; - ComPtr mVertexShader; - ComPtr mPixelShaders[PixelShaderCount]; - std::mutex mMutex; + ComPtr mDevice; + ComPtr mVertexShader; + ComPtr mPixelShaders[PixelShaderCount]; + std::mutex mMutex; }; -} +} // namespace #pragma endregion - class ToneMapPostProcess::Impl : public AlignedNew { public: explicit Impl(_In_ ID3D11Device* 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 Process(_In_ ID3D11DeviceContext* deviceContext, const std::function& setCustomState); @@ -275,53 +300,48 @@ class ToneMapPostProcess::Impl : public AlignedNew int GetCurrentShaderPermutation() const noexcept; // Fields. - ToneMapConstants constants; - ComPtr hdrTexture; - float linearExposure; - float paperWhiteNits; + ToneMapConstants constants; + ComPtr hdrTexture; + float linearExposure; + float paperWhiteNits; - Operator op; - TransferFunction func; - bool mrt; + Operator op; + TransferFunction func; + bool mrt; private: - int mDirtyFlags; + int mDirtyFlags; - ConstantBuffer mConstantBuffer; + ConstantBuffer mConstantBuffer; // Per-device resources. - std::shared_ptr mDeviceResources; + std::shared_ptr mDeviceResources; static SharedResourcePool deviceResourcesPool; }; - // Global pool of per-device ToneMapPostProcess resources. SharedResourcePool ToneMapPostProcess::Impl::deviceResourcesPool; - // Constructor. ToneMapPostProcess::Impl::Impl(_In_ ID3D11Device* device) : constants{}, - linearExposure(1.f), - paperWhiteNits(200.f), - op(None), - func(Linear), - mrt(false), - mDirtyFlags(INT_MAX), - mConstantBuffer(device), - mDeviceResources(deviceResourcesPool.DemandCreate(device)) + linearExposure(1.f), + paperWhiteNits(200.f), + op(None), + func(Linear), + mrt(false), + mDirtyFlags(INT_MAX), + mConstantBuffer(device), + mDeviceResources(deviceResourcesPool.DemandCreate(device)) { memcpy(constants.colorRotation, c_from709to2020, sizeof(c_from709to2020)); SetDebugObjectName(mConstantBuffer.GetBuffer(), "ToneMapPostProcess"); } - // Sets our state onto the D3D device. -void ToneMapPostProcess::Impl::Process( - _In_ ID3D11DeviceContext* deviceContext, - const std::function& setCustomState) +void ToneMapPostProcess::Impl::Process(_In_ ID3D11DeviceContext* deviceContext, const std::function& setCustomState) { // Set the texture. ID3D11ShaderResourceView* textures[1] = { hdrTexture.Get() }; @@ -337,7 +357,7 @@ void ToneMapPostProcess::Impl::Process( // Set shaders. auto vertexShader = mDeviceResources->GetVertexShader(); - auto pixelShader = mDeviceResources->GetPixelShader(GetCurrentShaderPermutation()); + auto pixelShader = mDeviceResources->GetPixelShader(GetCurrentShaderPermutation()); deviceContext->VSSetShader(vertexShader, nullptr, 0); deviceContext->PSSetShader(pixelShader, nullptr, 0); @@ -352,7 +372,7 @@ void ToneMapPostProcess::Impl::Process( } #if defined(_XBOX_ONE) && defined(_TITLE) - void *grfxMemory; + void* grfxMemory; mConstantBuffer.SetData(deviceContext, constants, &grfxMemory); ComPtr deviceContextX; @@ -386,7 +406,6 @@ void ToneMapPostProcess::Impl::Process( deviceContext->Draw(3, 0); } - int ToneMapPostProcess::Impl::GetCurrentShaderPermutation() const noexcept { #if defined(_XBOX_ONE) && defined(_TITLE) @@ -397,27 +416,21 @@ int ToneMapPostProcess::Impl::GetCurrentShaderPermutation() const noexcept #endif } - // Public constructor. ToneMapPostProcess::ToneMapPostProcess(_In_ ID3D11Device* device) : pImpl(std::make_unique(device)) {} - -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_ ID3D11DeviceContext* deviceContext, - _In_ std::function setCustomState) +void ToneMapPostProcess::Process(_In_ ID3D11DeviceContext* deviceContext, _In_ std::function setCustomState) { pImpl->Process(deviceContext, setCustomState); } - // Shader control. void ToneMapPostProcess::SetOperator(Operator op) { @@ -427,7 +440,6 @@ void ToneMapPostProcess::SetOperator(Operator op) pImpl->op = op; } - void ToneMapPostProcess::SetTransferFunction(TransferFunction func) { if (func >= TransferFunction_Max) @@ -436,7 +448,6 @@ void ToneMapPostProcess::SetTransferFunction(TransferFunction func) pImpl->func = func; } - #if defined(_XBOX_ONE) && defined(_TITLE) void ToneMapPostProcess::SetMRTOutput(bool value) { @@ -444,44 +455,39 @@ void ToneMapPostProcess::SetMRTOutput(bool value) } #endif - // Properties void ToneMapPostProcess::SetHDRSourceTexture(_In_opt_ ID3D11ShaderResourceView* value) { pImpl->hdrTexture = value; } - 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 e0bd5a8b..5fd3c111 100644 --- a/Src/VertexTypes.cpp +++ b/Src/VertexTypes.cpp @@ -15,121 +15,101 @@ using namespace DirectX; using namespace DirectX::PackedVector; - //-------------------------------------------------------------------------------------- // Vertex struct holding position . -const D3D11_INPUT_ELEMENT_DESC VertexPosition::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPosition::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPosition) == 12, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position and color information. -const D3D11_INPUT_ELEMENT_DESC VertexPositionColor::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionColor::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionColor) == 28, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position and texture mapping information. -const D3D11_INPUT_ELEMENT_DESC VertexPositionTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionTexture) == 20, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position and dual texture mapping information. -const D3D11_INPUT_ELEMENT_DESC VertexPositionDualTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionDualTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionDualTexture) == 28, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position and normal vector. -const D3D11_INPUT_ELEMENT_DESC VertexPositionNormal::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionNormal::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormal) == 24, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position, color, and texture mapping information. -const D3D11_INPUT_ELEMENT_DESC VertexPositionColorTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionColorTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionColorTexture) == 36, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position, normal vector, and color information. -const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalColor::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalColor::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalColor) == 40, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position, normal vector, and texture mapping information. -const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalTexture) == 32, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct holding position, normal vector, color, and texture mapping information. -const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalColorTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalColorTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalColorTexture) == 48, "Vertex struct/layout mismatch"); - //-------------------------------------------------------------------------------------- // Vertex struct for Visual Studio Shader Designer (DGSL) holding position, normal, // tangent, color (RGBA), and texture mapping information -const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTexture::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTexture::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; static_assert(sizeof(VertexPositionNormalTangentColorTexture) == 52, "Vertex struct/layout mismatch"); @@ -141,22 +121,22 @@ void XM_CALLCONV VertexPositionNormalTangentColorTexture::SetColor(FXMVECTOR ico this->color = rgba.v; } - //-------------------------------------------------------------------------------------- // Vertex struct for Visual Studio Shader Designer (DGSL) holding position, normal, // tangent, color (RGBA), texture mapping information, and skinning weights -const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTextureSkinning::InputElements[] = -{ - { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "BLENDINDICES",0, DXGI_FORMAT_R8G8B8A8_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "BLENDWEIGHT", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, +const D3D11_INPUT_ELEMENT_DESC VertexPositionNormalTangentColorTextureSkinning::InputElements[] = { + { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "BLENDINDICES", 0, DXGI_FORMAT_R8G8B8A8_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "BLENDWEIGHT", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; -static_assert(VertexPositionNormalTangentColorTextureSkinning::InputElementCount == VertexPositionNormalTangentColorTexture::InputElementCount + 2, "layout mismatch"); +static_assert(VertexPositionNormalTangentColorTextureSkinning::InputElementCount + == VertexPositionNormalTangentColorTexture::InputElementCount + 2, + "layout mismatch"); static_assert(sizeof(VertexPositionNormalTangentColorTextureSkinning) == 60, "Vertex struct/layout mismatch"); diff --git a/Src/WICTextureLoader.cpp b/Src/WICTextureLoader.cpp index 39d5cbf9..db7685e8 100644 --- a/Src/WICTextureLoader.cpp +++ b/Src/WICTextureLoader.cpp @@ -42,38 +42,37 @@ 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[] = - { - { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, + constexpr WICTranslate g_WICFormats[] = { + { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, - { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, - { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, + { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, + { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, - { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, - { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 - { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, + { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 - { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 - { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, + { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, - { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, - { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, + { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, + { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, - { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, - { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, - { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, - { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, + { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, + { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, + { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, + { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, - { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, + { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, }; //------------------------------------------------------------------------------------- @@ -84,81 +83,74 @@ 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[] = { // Note target GUID in this conversion table must be one of those directly supported formats (above). - { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM - { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM - { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM - { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT - { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT + { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT + { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT - { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM + { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM - { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM + { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM - { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT // We don't support n-channel formats }; bool g_WIC2 = false; - BOOL WINAPI InitializeWICFactory(PINIT_ONCE, PVOID, PVOID *ifactory) noexcept + BOOL WINAPI InitializeWICFactory(PINIT_ONCE, PVOID, PVOID* ifactory) noexcept { - HRESULT hr = CoCreateInstance( - CLSID_WICImagingFactory2, - nullptr, - CLSCTX_INPROC_SERVER, - __uuidof(IWICImagingFactory2), - ifactory - ); + HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory2), ifactory); if (SUCCEEDED(hr)) { @@ -168,17 +160,11 @@ namespace } else { - hr = CoCreateInstance( - CLSID_WICImagingFactory1, - nullptr, - CLSCTX_INPROC_SERVER, - __uuidof(IWICImagingFactory), - ifactory - ); + hr = CoCreateInstance(CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), ifactory); return SUCCEEDED(hr) ? TRUE : FALSE; } } -} +} // namespace //-------------------------------------------------------------------------------------- namespace DirectX @@ -187,12 +173,12 @@ namespace DirectX { namespace ToolKitInternal { - bool IsWIC2() noexcept; + bool IsWIC2() noexcept; IWICImagingFactory* GetWIC() noexcept; // Also used by ScreenGrab - } - } -} + } // namespace ToolKitInternal + } // namespace DX11 +} // namespace DirectX bool DirectX::DX11::ToolKitInternal::IsWIC2() noexcept { @@ -204,11 +190,7 @@ IWICImagingFactory* DirectX::DX11::ToolKitInternal::GetWIC() noexcept static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; IWICImagingFactory* factory = nullptr; - if (!InitOnceExecuteOnce( - &s_initOnce, - InitializeWICFactory, - nullptr, - reinterpret_cast(&factory))) + if (!InitOnceExecuteOnce(&s_initOnce, InitializeWICFactory, nullptr, reinterpret_cast(&factory))) { return nullptr; } @@ -268,24 +250,23 @@ namespace } //--------------------------------------------------------------------------------- - HRESULT CreateTextureFromWIC( - _In_ ID3D11Device* d3dDevice, - _In_opt_ ID3D11DeviceContext* d3dContext, - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_opt_ ID3D11DeviceX* d3dDeviceX, + HRESULT CreateTextureFromWIC(_In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_opt_ ID3D11DeviceX* d3dDeviceX, _In_opt_ ID3D11DeviceContextX* d3dContextX, - #endif - _In_ IWICBitmapFrameDecode *frame, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, +#endif + _In_ IWICBitmapFrameDecode* frame, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { - UINT width, height; + UINT width, height; HRESULT hr = frame->GetSize(&width, &height); if (FAILED(hr)) return hr; @@ -305,23 +286,18 @@ namespace { case D3D_FEATURE_LEVEL_9_1: case D3D_FEATURE_LEVEL_9_2: - case D3D_FEATURE_LEVEL_9_3: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + case D3D_FEATURE_LEVEL_9_3: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); case D3D_FEATURE_LEVEL_10_0: - case D3D_FEATURE_LEVEL_10_1: - maxsize = 8192u /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; - break; + case D3D_FEATURE_LEVEL_10_1: maxsize = 8192u /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; break; - default: - maxsize = size_t(D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION); - break; + default: maxsize = size_t(D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION); break; } } assert(maxsize > 0); - UINT twidth = width; + UINT twidth = width; UINT theight = height; if (loadFlags & WIC_LOADER_FIT_POW2) { @@ -332,20 +308,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; } @@ -369,13 +345,13 @@ namespace { memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat96bppRGBFloat, sizeof(GUID)); format = DXGI_FORMAT_R32G32B32_FLOAT; - bpp = 96; + bpp = 96; } else { memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat128bppRGBAFloat, sizeof(GUID)); format = DXGI_FORMAT_R32G32B32A32_FLOAT; - bpp = 128; + bpp = 128; } } else @@ -396,10 +372,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); } } @@ -412,13 +398,13 @@ namespace { // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT UINT fmtSupport = 0; - hr = d3dDevice->CheckFormatSupport(DXGI_FORMAT_R32G32B32_FLOAT, &fmtSupport); + hr = d3dDevice->CheckFormatSupport(DXGI_FORMAT_R32G32B32_FLOAT, &fmtSupport); if (FAILED(hr) || !(fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) { // Use R32G32B32A32_FLOAT instead which is required for Feature Level 10.0 and up memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat128bppRGBAFloat, sizeof(GUID)); format = DXGI_FORMAT_R32G32B32A32_FLOAT; - bpp = 128; + bpp = 128; } } @@ -426,7 +412,7 @@ namespace { memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat32bppRGBA, sizeof(GUID)); format = DXGI_FORMAT_R8G8B8A8_UNORM; - bpp = 32; + bpp = 32; } if (!bpp) @@ -467,7 +453,7 @@ namespace sRGB = (loadFlags & WIC_LOADER_SRGB_DEFAULT) != 0; } } - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) else if (memcmp(&containerFormat, &GUID_ContainerFormatJpeg, sizeof(GUID)) == 0) { if (SUCCEEDED(metareader->GetMetadataByName(L"/app1/ifd/exif/{ushort=40961}", &value)) && value.vt == VT_UI2) @@ -490,7 +476,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); @@ -499,7 +485,7 @@ namespace { sRGB = (loadFlags & WIC_LOADER_SRGB_DEFAULT) != 0; } - #endif +#endif std::ignore = PropVariantClear(&value); @@ -512,13 +498,13 @@ namespace // Verify our target format is supported by the current device // (handles WDDM 1.0 or WDDM 1.1 device driver cases as well as DirectX 11.0 Runtime without 16bpp format support) UINT support = 0; - hr = d3dDevice->CheckFormatSupport(format, &support); + hr = d3dDevice->CheckFormatSupport(format, &support); if (FAILED(hr) || !(support & D3D11_FORMAT_SUPPORT_TEXTURE2D)) { // Fallback to RGBA 32-bit format which is supported by all devices memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat32bppRGBA, sizeof(GUID)); format = DXGI_FORMAT_R8G8B8A8_UNORM; - bpp = 32; + bpp = 32; } // Allocate temporary memory for image @@ -528,7 +514,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); std::unique_ptr temp(new (std::nothrow) uint8_t[imageSize]); @@ -536,9 +522,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), temp.get()); @@ -581,13 +565,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; @@ -609,7 +598,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; @@ -629,28 +618,28 @@ namespace if (d3dContext && textureView) // Must have context and shader-view to auto generate mipmaps { UINT fmtSupport = 0; - hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); + hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) { autogen = true; - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) if (!d3dDeviceX || !d3dContextX) return E_INVALIDARG; - #endif +#endif } } // Create texture D3D11_TEXTURE2D_DESC desc = {}; - desc.Width = twidth; - desc.Height = theight; - desc.MipLevels = (autogen) ? 0u : 1u; - desc.ArraySize = 1; - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - desc.Usage = usage; - desc.CPUAccessFlags = cpuAccessFlags; + desc.Width = twidth; + desc.Height = theight; + desc.MipLevels = (autogen) ? 0u : 1u; + desc.ArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = usage; + desc.CPUAccessFlags = cpuAccessFlags; if (autogen) { @@ -666,15 +655,15 @@ namespace D3D11_SUBRESOURCE_DATA initData = { temp.get(), static_cast(rowPitch), static_cast(imageSize) }; ID3D11Texture2D* tex = nullptr; - hr = d3dDevice->CreateTexture2D(&desc, (autogen) ? nullptr : &initData, &tex); + hr = d3dDevice->CreateTexture2D(&desc, (autogen) ? nullptr : &initData, &tex); if (SUCCEEDED(hr) && tex) { if (textureView) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = desc.Format; + SRVDesc.Format = desc.Format; - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MipLevels = (autogen) ? unsigned(-1) : 1u; hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); @@ -688,11 +677,12 @@ namespace { assert(d3dContext != nullptr); - #if defined(_XBOX_ONE) && defined(_TITLE) - ID3D11Texture2D *pStaging = nullptr; - CD3D11_TEXTURE2D_DESC stagingDesc(format, twidth, theight, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, 0); - initData.pSysMem = temp.get(); - initData.SysMemPitch = static_cast(rowPitch); +#if defined(_XBOX_ONE) && defined(_TITLE) + ID3D11Texture2D* pStaging = nullptr; + CD3D11_TEXTURE2D_DESC + stagingDesc(format, twidth, theight, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, 0); + initData.pSysMem = temp.get(); + initData.SysMemPitch = static_cast(rowPitch); initData.SysMemSlicePitch = static_cast(imageSize); hr = d3dDevice->CreateTexture2D(&stagingDesc, &initData, &pStaging); @@ -701,12 +691,15 @@ namespace d3dContext->CopySubresourceRegion(tex, 0, 0, 0, 0, pStaging, 0, nullptr); UINT64 copyFence = d3dContextX->InsertFence(0); - while (d3dDeviceX->IsFencePending(copyFence)) { SwitchToThread(); } + while (d3dDeviceX->IsFencePending(copyFence)) + { + SwitchToThread(); + } pStaging->Release(); } - #else +#else d3dContext->UpdateSubresource(tex, 0, nullptr, temp.get(), static_cast(rowPitch), static_cast(imageSize)); - #endif +#endif d3dContext->GenerateMips(*textureView); } } @@ -726,15 +719,14 @@ namespace } //-------------------------------------------------------------------------------------- - void SetDebugTextureInfo( - _In_z_ const wchar_t* fileName, - _In_opt_ ID3D11Resource** texture, - _In_opt_ ID3D11ShaderResourceView** textureView) noexcept + void SetDebugTextureInfo(_In_z_ const wchar_t* fileName, + _In_opt_ ID3D11Resource** texture, + _In_opt_ ID3D11ShaderResourceView** textureView) noexcept { - #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#if !defined(NO_D3D11_DEBUG_NAME) && (defined(_DEBUG) || defined(PROFILE)) if (texture || textureView) { - #if defined(_XBOX_ONE) && defined(_TITLE) +#if defined(_XBOX_ONE) && defined(_TITLE) if (texture && *texture) { (*texture)->SetName(fileName); @@ -743,100 +735,93 @@ namespace { (*textureView)->SetName(fileName); } - #else - CHAR strFileA[MAX_PATH]; - const int result = WideCharToMultiByte(CP_UTF8, - WC_NO_BEST_FIT_CHARS, - fileName, - -1, - strFileA, - MAX_PATH, - nullptr, - nullptr - ); +#else + CHAR strFileA[MAX_PATH]; + const int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, fileName, -1, strFileA, MAX_PATH, nullptr, nullptr); if (result > 0) { if (texture && *texture) { - (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, - static_cast(result), - strFileA - ); + (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast(result), strFileA); } if (textureView && *textureView) { - (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, - static_cast(result), - strFileA - ); + (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast(result), strFileA); } } - #endif +#endif } - #else +#else UNREFERENCED_PARAMETER(fileName); UNREFERENCED_PARAMETER(texture); UNREFERENCED_PARAMETER(textureView); - #endif +#endif } } // anonymous namespace //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromMemory( - ID3D11Device* d3dDevice, - const uint8_t* wicData, - size_t wicDataSize, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - size_t maxsize) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, + const uint8_t* wicData, + size_t wicDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) noexcept { return CreateWICTextureFromMemoryEx(d3dDevice, - wicData, wicDataSize, + wicData, + wicDataSize, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, WIC_LOADER_DEFAULT, - texture, textureView); + texture, + textureView); } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateWICTextureFromMemory( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateWICTextureFromMemory(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateWICTextureFromMemory( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const uint8_t* wicData, - size_t wicDataSize, - ID3D11Resource** texture, + HRESULT + DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const uint8_t* wicData, + size_t wicDataSize, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, - size_t maxsize) noexcept + size_t maxsize) noexcept { - return CreateWICTextureFromMemoryEx(d3dDevice, d3dContext, - wicData, wicDataSize, + return CreateWICTextureFromMemoryEx(d3dDevice, + d3dContext, + wicData, + wicDataSize, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, WIC_LOADER_DEFAULT, - texture, textureView); + texture, + textureView); } -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromMemoryEx( - ID3D11Device* d3dDevice, - const uint8_t* wicData, - size_t wicDataSize, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, + const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) noexcept { if (texture) { @@ -869,7 +854,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; @@ -888,14 +873,21 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( if (FAILED(hr)) return hr; - hr = CreateTextureFromWIC(d3dDevice, nullptr, - #if defined(_XBOX_ONE) && defined(_TITLE) - nullptr, nullptr, - #endif - frame.Get(), maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + hr = CreateTextureFromWIC(d3dDevice, + nullptr, +#if defined(_XBOX_ONE) && defined(_TITLE) + nullptr, + nullptr, +#endif + frame.Get(), + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (FAILED(hr)) return hr; @@ -914,23 +906,23 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateWICTextureFromMemoryEx( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateWICTextureFromMemoryEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateWICTextureFromMemoryEx( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const uint8_t* wicData, - size_t wicDataSize, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, + HRESULT + DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView) noexcept { if (texture) @@ -964,7 +956,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; @@ -983,15 +975,21 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( if (FAILED(hr)) return hr; - hr = CreateTextureFromWIC(d3dDevice, d3dContext, - #if defined(_XBOX_ONE) && defined(_TITLE) - d3dDevice, d3dContext, - #endif + hr = CreateTextureFromWIC(d3dDevice, + d3dContext, +#if defined(_XBOX_ONE) && defined(_TITLE) + d3dDevice, + d3dContext, +#endif frame.Get(), maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (FAILED(hr)) return hr; @@ -1009,57 +1007,62 @@ HRESULT DirectX::CreateWICTextureFromMemoryEx( } //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromFile( - ID3D11Device* d3dDevice, - const wchar_t* fileName, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - size_t maxsize) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) noexcept { return CreateWICTextureFromFileEx(d3dDevice, fileName, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, WIC_LOADER_DEFAULT, - texture, textureView); + texture, + textureView); } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateWICTextureFromFile( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateWICTextureFromFile(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateWICTextureFromFile( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const wchar_t* fileName, - ID3D11Resource** texture, + HRESULT + DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const wchar_t* fileName, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, - size_t maxsize) noexcept + size_t maxsize) noexcept { - return CreateWICTextureFromFileEx(d3dDevice, d3dContext, + return CreateWICTextureFromFileEx(d3dDevice, + d3dContext, fileName, maxsize, - D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, + D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, + 0, + 0, WIC_LOADER_DEFAULT, - texture, textureView); + texture, + textureView); } -_Use_decl_annotations_ -HRESULT DirectX::CreateWICTextureFromFileEx( - ID3D11Device* d3dDevice, - const wchar_t* fileName, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView) noexcept +_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) noexcept { if (texture) { @@ -1086,11 +1089,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; @@ -1099,15 +1098,21 @@ HRESULT DirectX::CreateWICTextureFromFileEx( if (FAILED(hr)) return hr; - hr = CreateTextureFromWIC(d3dDevice, nullptr, - #if defined(_XBOX_ONE) && defined(_TITLE) - nullptr, nullptr, - #endif + hr = CreateTextureFromWIC(d3dDevice, + nullptr, +#if defined(_XBOX_ONE) && defined(_TITLE) + nullptr, + nullptr, +#endif frame.Get(), maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (SUCCEEDED(hr)) { @@ -1119,22 +1124,22 @@ HRESULT DirectX::CreateWICTextureFromFileEx( _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) -HRESULT DirectX::CreateWICTextureFromFileEx( - ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT + DirectX::CreateWICTextureFromFileEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT DirectX::CreateWICTextureFromFileEx( - ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, - #endif - const wchar_t* fileName, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - WIC_LOADER_FLAGS loadFlags, - ID3D11Resource** texture, + HRESULT + DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, +#endif + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + WIC_LOADER_FLAGS loadFlags, + ID3D11Resource** texture, ID3D11ShaderResourceView** textureView) noexcept { if (texture) @@ -1162,11 +1167,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; @@ -1175,15 +1176,21 @@ HRESULT DirectX::CreateWICTextureFromFileEx( if (FAILED(hr)) return hr; - hr = CreateTextureFromWIC(d3dDevice, d3dContext, - #if defined(_XBOX_ONE) && defined(_TITLE) - d3dDevice, d3dContext, - #endif + hr = CreateTextureFromWIC(d3dDevice, + d3dContext, +#if defined(_XBOX_ONE) && defined(_TITLE) + d3dDevice, + d3dContext, +#endif frame.Get(), maxsize, - usage, bindFlags, cpuAccessFlags, miscFlags, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, loadFlags, - texture, textureView); + texture, + textureView); if (SUCCEEDED(hr)) { @@ -1193,7 +1200,6 @@ HRESULT DirectX::CreateWICTextureFromFileEx( return hr; } - //-------------------------------------------------------------------------------------- // Adapters for /Zc:wchar_t- clients @@ -1201,75 +1207,89 @@ HRESULT DirectX::CreateWICTextureFromFileEx( namespace DirectX { - HRESULT __cdecl CreateWICTextureFromFile( - _In_ ID3D11Device* d3dDevice, - _In_z_ const __wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize) noexcept + HRESULT __cdecl CreateWICTextureFromFile(_In_ ID3D11Device* d3dDevice, + _In_z_ const __wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize) noexcept { - return CreateWICTextureFromFile(d3dDevice, - reinterpret_cast(szFileName), - texture, textureView, maxsize); + return CreateWICTextureFromFile(d3dDevice, reinterpret_cast(szFileName), texture, textureView, maxsize); } HRESULT __cdecl CreateWICTextureFromFile( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, +#else + _In_ ID3D11Device* d3dDevice, _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const __wchar_t* szFileName, - _Outptr_opt_ ID3D11Resource** texture, +#endif + _In_z_ const __wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize) noexcept + _In_ size_t maxsize) noexcept { - return CreateWICTextureFromFile(d3dDevice, d3dContext, + return CreateWICTextureFromFile(d3dDevice, + d3dContext, reinterpret_cast(szFileName), - texture, textureView, maxsize); + texture, + textureView, + maxsize); } - HRESULT __cdecl CreateWICTextureFromFileEx( - _In_ ID3D11Device* d3dDevice, - _In_z_ const __wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept + HRESULT __cdecl CreateWICTextureFromFileEx(_In_ ID3D11Device* d3dDevice, + _In_z_ const __wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { return CreateWICTextureFromFileEx(d3dDevice, reinterpret_cast(szFileName), - maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView); } HRESULT __cdecl CreateWICTextureFromFileEx( - #if defined(_XBOX_ONE) && defined(_TITLE) - _In_ ID3D11DeviceX* d3dDevice, +#if defined(_XBOX_ONE) && defined(_TITLE) + _In_ ID3D11DeviceX* d3dDevice, _In_opt_ ID3D11DeviceContextX* d3dContext, - #else - _In_ ID3D11Device* d3dDevice, +#else + _In_ ID3D11Device* d3dDevice, _In_opt_ ID3D11DeviceContext* d3dContext, - #endif - _In_z_ const __wchar_t* szFileName, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ WIC_LOADER_FLAGS loadFlags, - _Outptr_opt_ ID3D11Resource** texture, +#endif + _In_z_ const __wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ WIC_LOADER_FLAGS loadFlags, + _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { - return CreateWICTextureFromFileEx(d3dDevice, d3dContext, + return CreateWICTextureFromFileEx(d3dDevice, + d3dContext, reinterpret_cast(szFileName), - maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); + maxsize, + usage, + bindFlags, + cpuAccessFlags, + miscFlags, + loadFlags, + texture, + textureView); } -} +} // namespace DirectX #endif // !_NATIVE_WCHAR_T_DEFINED diff --git a/Src/XboxDDSTextureLoader.cpp b/Src/XboxDDSTextureLoader.cpp index 564f8b5a..195e8b3a 100644 --- a/Src/XboxDDSTextureLoader.cpp +++ b/Src/XboxDDSTextureLoader.cpp @@ -33,8 +33,7 @@ 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, @@ -42,10 +41,10 @@ namespace //-------------------------------------------------------------------------------------- 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) { @@ -53,10 +52,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) { @@ -94,12 +90,7 @@ namespace // read the data in DWORD BytesRead = 0; - if (!ReadFile(hFile.get(), - ddsData.get(), - FileSize.LowPart, - &BytesRead, - nullptr - )) + if (!ReadFile(hFile.get(), ddsData.get(), FileSize.LowPart, &BytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } @@ -119,15 +110,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); @@ -140,10 +129,10 @@ namespace } // setup the pointers in the process request - *header = hdr; + *header = hdr; auto offset = DDS_XBOX_HEADER_SIZE; - *bitData = ddsData.get() + offset; - *bitSize = FileSize.LowPart - offset; + *bitData = ddsData.get() + offset; + *bitSize = FileSize.LowPart - offset; return S_OK; } @@ -153,45 +142,37 @@ 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_ ID3D11DeviceX* d3dDevice, - _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_ bool isCubeMap, - _In_ void* grfxMemory, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView) 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_ bool isCubeMap, + _In_ void* grfxMemory, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { if (!d3dDevice || !grfxMemory) return E_POINTER; @@ -206,184 +187,171 @@ namespace switch (xboxext->resourceDimension) { - case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: { + D3D11_TEXTURE1D_DESC desc = {}; + desc.Width = static_cast(width); + desc.MipLevels = static_cast(mipCount); + desc.ArraySize = static_cast(arraySize); + desc.Format = format; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + + ID3D11Texture1D* tex = nullptr; + hr = d3dDevice->CreatePlacementTexture1D(&desc, xboxext->tileMode, 0, grfxMemory, &tex); + if (SUCCEEDED(hr) && tex != 0) { - D3D11_TEXTURE1D_DESC desc = {}; - desc.Width = static_cast(width); - desc.MipLevels = static_cast(mipCount); - desc.ArraySize = static_cast(arraySize); - desc.Format = format; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - - ID3D11Texture1D* tex = nullptr; - hr = d3dDevice->CreatePlacementTexture1D(&desc, xboxext->tileMode, 0, grfxMemory, &tex); - if (SUCCEEDED(hr) && tex != 0) + if (textureView != 0) { - if (textureView != 0) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = format; - - if (arraySize > 1) - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; - SRVDesc.Texture1DArray.MipLevels = desc.MipLevels; - SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); - } - else - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; - SRVDesc.Texture1D.MipLevels = desc.MipLevels; - } + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; - hr = d3dDevice->CreateShaderResourceView(tex, - &SRVDesc, - textureView - ); - if (FAILED(hr)) - { - tex->Release(); - return hr; - } - } - - if (texture != 0) + if (arraySize > 1) { - *texture = tex; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; + SRVDesc.Texture1DArray.MipLevels = desc.MipLevels; + SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); } else { - SetDebugObjectName(tex, "XboxDDSTextureLoader"); + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; + SRVDesc.Texture1D.MipLevels = desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) + { tex->Release(); + return hr; } } - } - break; - case D3D11_RESOURCE_DIMENSION_TEXTURE2D: + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "XboxDDSTextureLoader"); + tex->Release(); + } + } + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: { + D3D11_TEXTURE2D_DESC desc = {}; + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.MipLevels = static_cast(mipCount); + desc.ArraySize = static_cast(arraySize); + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0; + + ID3D11Texture2D* tex = nullptr; + hr = d3dDevice->CreatePlacementTexture2D(&desc, xboxext->tileMode, 0, grfxMemory, &tex); + if (SUCCEEDED(hr) && tex != 0) { - D3D11_TEXTURE2D_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.MipLevels = static_cast(mipCount); - desc.ArraySize = static_cast(arraySize); - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0; - - ID3D11Texture2D* tex = nullptr; - hr = d3dDevice->CreatePlacementTexture2D(&desc, xboxext->tileMode, 0, grfxMemory, &tex); - if (SUCCEEDED(hr) && tex != 0) + if (textureView != 0) { - if (textureView != 0) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = format; + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; - if (isCubeMap) - { - if (arraySize > 6) - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; - SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels; - - // Earlier we set arraySize to (NumCubes * 6) - SRVDesc.TextureCubeArray.NumCubes = static_cast(arraySize / 6); - } - else - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; - SRVDesc.TextureCube.MipLevels = desc.MipLevels; - } - } - else if (arraySize > 1) + if (isCubeMap) + { + if (arraySize > 6) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; - SRVDesc.Texture2DArray.MipLevels = desc.MipLevels; - SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; + SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels; + + // Earlier we set arraySize to (NumCubes * 6) + SRVDesc.TextureCubeArray.NumCubes = static_cast(arraySize / 6); } else { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Texture2D.MipLevels = desc.MipLevels; - } - - hr = d3dDevice->CreateShaderResourceView(tex, - &SRVDesc, - textureView - ); - if (FAILED(hr)) - { - tex->Release(); - return hr; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; + SRVDesc.TextureCube.MipLevels = desc.MipLevels; } } - - if (texture != 0) + else if (arraySize > 1) { - *texture = tex; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; + SRVDesc.Texture2DArray.MipLevels = desc.MipLevels; + SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); } else { - SetDebugObjectName(tex, "XboxDDSTextureLoader"); + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) + { tex->Release(); + return hr; } } - } - break; - case D3D11_RESOURCE_DIMENSION_TEXTURE3D: + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "XboxDDSTextureLoader"); + tex->Release(); + } + } + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: { + D3D11_TEXTURE3D_DESC desc = {}; + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.Depth = static_cast(depth); + desc.MipLevels = static_cast(mipCount); + desc.Format = format; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + + ID3D11Texture3D* tex = nullptr; + hr = d3dDevice->CreatePlacementTexture3D(&desc, xboxext->tileMode, 0, grfxMemory, &tex); + if (SUCCEEDED(hr) && tex != 0) { - D3D11_TEXTURE3D_DESC desc = {}; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.Depth = static_cast(depth); - desc.MipLevels = static_cast(mipCount); - desc.Format = format; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - - ID3D11Texture3D* tex = nullptr; - hr = d3dDevice->CreatePlacementTexture3D(&desc, xboxext->tileMode, 0, grfxMemory, &tex); - if (SUCCEEDED(hr) && tex != 0) + if (textureView != 0) { - if (textureView != 0) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; - SRVDesc.Format = format; + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; - SRVDesc.Texture3D.MipLevels = desc.MipLevels; - - hr = d3dDevice->CreateShaderResourceView(tex, - &SRVDesc, - textureView - ); - if (FAILED(hr)) - { - tex->Release(); - return hr; - } - } + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; + SRVDesc.Texture3D.MipLevels = desc.MipLevels; - if (texture != 0) - { - *texture = tex; - } - else + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) { - SetDebugObjectName(tex, "XboxDDSTextureLoader"); tex->Release(); + return hr; } } + + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "XboxDDSTextureLoader"); + tex->Release(); + } } - break; + } + break; - default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } return hr; @@ -391,19 +359,19 @@ namespace //-------------------------------------------------------------------------------------- HRESULT CreateTextureFromDDS(_In_ ID3D11DeviceX* d3dDevice, - _In_ const DDS_HEADER* header, - _In_reads_bytes_(bitSize) const uint8_t* bitData, - _In_ size_t bitSize, - _In_ bool forceSRGB, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Outptr_ void** grfxMemory) noexcept + _In_ const DDS_HEADER* header, + _In_reads_bytes_(bitSize) const uint8_t* bitData, + _In_ size_t bitSize, + _In_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Outptr_ void** grfxMemory) 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) @@ -411,8 +379,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); @@ -420,12 +387,12 @@ namespace auto xboxext = reinterpret_cast(reinterpret_cast(header) + sizeof(DDS_HEADER)); - #ifndef NDEBUG +#ifndef NDEBUG if (xboxext->xdkVer < _XDK_VER) { OutputDebugStringA("WARNING: DDS XBOX file may be outdated and need regeneration\n"); } - #endif +#endif uint32_t arraySize = xboxext->arraySize; if (arraySize == 0) @@ -466,8 +433,7 @@ namespace } break; - default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } if (xboxext->tileMode == uint32_t(-1)) @@ -484,8 +450,7 @@ namespace switch (xboxext->resourceDimension) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: - if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) + if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } @@ -495,33 +460,28 @@ namespace if (isCubeMap) { // This is the right bound because we set arraySize to (NumCubes*6) above - if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURECUBE_DIMENSION) || - (height > D3D11_REQ_TEXTURECUBE_DIMENSION)) + if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURECUBE_DIMENSION) + || (height > D3D11_REQ_TEXTURECUBE_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } - else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) || - (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) + || (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; case D3D11_RESOURCE_DIMENSION_TEXTURE3D: - if ((arraySize > 1) || - (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) + if ((arraySize > 1) || (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) + || (depth > D3D11_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) @@ -548,10 +508,18 @@ namespace memcpy(*grfxMemory, bitData, xboxext->dataSize); // Create the texture - hr = CreateD3DResources(d3dDevice, xboxext, - width, height, depth, mipCount, arraySize, - forceSRGB, isCubeMap, *grfxMemory, - texture, textureView); + hr = CreateD3DResources(d3dDevice, + xboxext, + width, + height, + depth, + mipCount, + arraySize, + forceSRGB, + isCubeMap, + *grfxMemory, + texture, + textureView); if (FAILED(hr)) { XMemFree(grfxMemory, c_XMemAllocAttributes); @@ -569,17 +537,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; } } } @@ -588,18 +554,15 @@ namespace } } // anonymous namespace - //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT Xbox::CreateDDSTextureFromMemory( - ID3D11DeviceX* d3dDevice, - const uint8_t* ddsData, - size_t ddsDataSize, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - void** grfxMemory, - DDS_ALPHA_MODE* alphaMode, - bool forceSRGB) noexcept +_Use_decl_annotations_ HRESULT Xbox::CreateDDSTextureFromMemory(ID3D11DeviceX* d3dDevice, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + void** grfxMemory, + DDS_ALPHA_MODE* alphaMode, + bool forceSRGB) noexcept { if (texture) { @@ -638,15 +601,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); @@ -660,10 +621,8 @@ HRESULT Xbox::CreateDDSTextureFromMemory( auto offset = DDS_XBOX_HEADER_SIZE; - HRESULT hr = CreateTextureFromDDS(d3dDevice, header, - ddsData + offset, ddsDataSize - offset, forceSRGB, - texture, textureView, - grfxMemory); + HRESULT hr + = CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, forceSRGB, texture, textureView, grfxMemory); if (SUCCEEDED(hr)) { if (texture != 0 && *texture != 0) @@ -684,15 +643,13 @@ HRESULT Xbox::CreateDDSTextureFromMemory( } //-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -HRESULT Xbox::CreateDDSTextureFromFile( - ID3D11DeviceX* d3dDevice, - const wchar_t* fileName, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - void** grfxMemory, - DDS_ALPHA_MODE* alphaMode, - bool forceSRGB) noexcept +_Use_decl_annotations_ HRESULT Xbox::CreateDDSTextureFromFile(ID3D11DeviceX* d3dDevice, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + void** grfxMemory, + DDS_ALPHA_MODE* alphaMode, + bool forceSRGB) noexcept { if (texture) { @@ -716,30 +673,22 @@ 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(d3dDevice, header, - bitData, bitSize, forceSRGB, - texture, textureView, - grfxMemory); + hr = CreateTextureFromDDS(d3dDevice, header, bitData, bitSize, forceSRGB, texture, textureView, grfxMemory); 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 != 0 && *texture != 0) { (*texture)->SetName(fileName); @@ -748,7 +697,7 @@ HRESULT Xbox::CreateDDSTextureFromFile( { (*textureView)->SetName(fileName); } - #endif +#endif if (alphaMode) *alphaMode = GetAlphaMode(header); @@ -758,8 +707,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 6db38093..fe63250b 100644 --- a/Src/pch.h +++ b/Src/pch.h @@ -11,7 +11,8 @@ #ifdef _MSC_VER // Off by default warnings -#pragma warning(disable : 4619 4616 4061 4265 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4865 4987 5026 5027 5031 5032 5039 5045 5219 5264 26812) +#pragma warning( \ + disable : 4619 4616 4061 4265 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4865 4987 5026 5027 5031 5032 5039 5045 5219 5264 26812) // C4619/4616 #pragma warning warnings // 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 @@ -49,11 +50,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 @@ -191,17 +192,24 @@ #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 #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 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/XWBTool/CmdLineHelpers.h b/XWBTool/CmdLineHelpers.h index 06744c18..ca4779e7 100644 --- a/XWBTool/CmdLineHelpers.h +++ b/XWBTool/CmdLineHelpers.h @@ -27,16 +27,33 @@ #error Define TOOL_VERSION before including this header #endif - namespace Helpers { - struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; + struct handle_closer + { + void operator()(HANDLE h) + { + 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; + } - struct find_closer { void operator()(HANDLE h) noexcept { assert(h != INVALID_HANDLE_VALUE); if (h) FindClose(h); } }; + struct find_closer + { + void operator()(HANDLE h) noexcept + { + assert(h != INVALID_HANDLE_VALUE); + if (h) + FindClose(h); + } + }; using ScopedFindHandle = std::unique_ptr; @@ -53,12 +70,12 @@ namespace Helpers template struct SValue { - const wchar_t* name; - T value; + const wchar_t* name; + T value; }; template - T LookupByName(const wchar_t _In_z_ *pName, const SValue *pArray) noexcept + T LookupByName(const wchar_t _In_z_* pName, const SValue* pArray) noexcept { while (pArray->name) { @@ -72,7 +89,7 @@ namespace Helpers } template - const wchar_t* LookupByValue(T value, const SValue *pArray) noexcept + const wchar_t* LookupByValue(T value, const SValue* pArray) noexcept { while (pArray->name) { @@ -123,7 +140,7 @@ namespace Helpers } template - void PrintList(size_t cch, const SValue *pValue) noexcept + void PrintList(size_t cch, const SValue* pValue) noexcept { while (pValue->name) { @@ -156,8 +173,8 @@ namespace Helpers auto verInfo = std::make_unique(size); if (GetFileVersionInfoW(appName, 0, size, verInfo.get())) { - LPVOID lpstr = nullptr; - UINT strLen = 0; + LPVOID lpstr = nullptr; + UINT strLen = 0; if (VerQueryValueW(verInfo.get(), L"\\StringFileInfo\\040904B0\\ProductVersion", &lpstr, &strLen)) { wcsncpy_s(version, reinterpret_cast(lpstr), strLen); @@ -179,9 +196,9 @@ namespace Helpers { wprintf(L"%ls Version %ls\n", desc, version); wprintf(L"Copyright (C) Microsoft Corp.\n"); - #ifdef _DEBUG +#ifdef _DEBUG wprintf(L"*** Debug build ***\n"); - #endif +#endif wprintf(L"\n"); } } @@ -190,10 +207,8 @@ namespace Helpers { // Process files WIN32_FIND_DATAW findData = {}; - ScopedFindHandle hFile(safe_handle(FindFirstFileExW(path.c_str(), - FindExInfoBasic, &findData, - FindExSearchNameMatch, nullptr, - FIND_FIRST_EX_LARGE_FETCH))); + ScopedFindHandle hFile(safe_handle( + FindFirstFileExW(path.c_str(), FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, FIND_FIRST_EX_LARGE_FETCH))); if (hFile) { for (;;) @@ -201,7 +216,7 @@ namespace Helpers if (!(findData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_DIRECTORY))) { SConversion conv = {}; - conv.szSrc = path.parent_path().append(findData.cFileName).native(); + conv.szSrc = path.parent_path().append(findData.cFileName).native(); if (folder) { conv.szFolder = folder; @@ -220,8 +235,10 @@ namespace Helpers auto searchDir = path.parent_path().append(L"*"); hFile.reset(safe_handle(FindFirstFileExW(searchDir.c_str(), - FindExInfoBasic, &findData, - FindExSearchLimitToDirectories, nullptr, + FindExInfoBasic, + &findData, + FindExSearchLimitToDirectories, + nullptr, FIND_FIRST_EX_LARGE_FETCH))); if (!hFile) return; @@ -232,9 +249,10 @@ namespace Helpers { if (findData.cFileName[0] != L'.') { - auto subfolder = (folder) - ? (std::wstring(folder) + std::wstring(findData.cFileName) + std::filesystem::path::preferred_separator) - : (std::wstring(findData.cFileName) + std::filesystem::path::preferred_separator); + auto subfolder + = (folder) ? + (std::wstring(folder) + std::wstring(findData.cFileName) + std::filesystem::path::preferred_separator) : + (std::wstring(findData.cFileName) + std::filesystem::path::preferred_separator); auto subdir = path.parent_path().append(findData.cFileName).append(path.filename().c_str()); @@ -273,7 +291,7 @@ namespace Helpers else { std::filesystem::path path(fname.c_str() + 1); - auto& npath = path.make_preferred(); + auto& npath = path.make_preferred(); if (wcspbrk(fname.c_str(), L"?*") != nullptr) { std::list removeFiles; @@ -301,7 +319,7 @@ namespace Helpers } else { - SConversion conv = {}; + SConversion conv = {}; std::filesystem::path path(fname.c_str()); conv.szSrc = path.make_preferred().native(); flist.push_back(conv); @@ -343,8 +361,12 @@ namespace Helpers LPWSTR errorText = nullptr; const DWORD result = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER, - nullptr, static_cast(hr), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast(&errorText), 0, nullptr); + nullptr, + static_cast(hr), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&errorText), + 0, + nullptr); *desc = 0; @@ -372,4 +394,4 @@ namespace Helpers return desc; } -} +} // namespace Helpers diff --git a/XWBTool/xwbtool.cpp b/XWBTool/xwbtool.cpp index 0b602b2b..d79d687b 100644 --- a/XWBTool/xwbtool.cpp +++ b/XWBTool/xwbtool.cpp @@ -82,11 +82,9 @@ using namespace Helpers; ////////////////////////////////////////////////////////////////////////////// #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) */ #ifndef WAVE_FORMAT_XMA2 @@ -104,18 +102,18 @@ struct XMA2WAVEFORMATEX // wBitsPerSample; // Bits per decoded mono sample; always 16 for XMA // cbSize; // Size in bytes of the rest of this structure (34) - WORD NumStreams; // Number of audio streams (1 or 2 channels each) - DWORD ChannelMask; // Spatial positions of the channels in this file, - // stored as SPEAKER_xxx values (see audiodefs.h) - DWORD SamplesEncoded; // Total number of PCM samples per channel the file decodes to - DWORD BytesPerBlock; // XMA block size (but the last one may be shorter) - DWORD PlayBegin; // First valid sample in the decoded audio - DWORD PlayLength; // Length of the valid part of the decoded audio - DWORD LoopBegin; // Beginning of the loop region in decoded sample terms - DWORD LoopLength; // Length of the loop region in decoded sample terms - BYTE LoopCount; // Number of loop repetitions; 255 = infinite - BYTE EncoderVersion; // Version of XMA encoder that generated the file - WORD BlockCount; // XMA blocks in file (and entries in its seek table) + WORD NumStreams; // Number of audio streams (1 or 2 channels each) + DWORD ChannelMask; // Spatial positions of the channels in this file, + // stored as SPEAKER_xxx values (see audiodefs.h) + DWORD SamplesEncoded; // Total number of PCM samples per channel the file decodes to + DWORD BytesPerBlock; // XMA block size (but the last one may be shorter) + DWORD PlayBegin; // First valid sample in the decoded audio + DWORD PlayLength; // Length of the valid part of the decoded audio + DWORD LoopBegin; // Beginning of the loop region in decoded sample terms + DWORD LoopLength; // Length of the loop region in decoded sample terms + BYTE LoopCount; // Number of loop repetitions; 255 = infinite + BYTE EncoderVersion; // Version of XMA encoder that generated the file + WORD BlockCount; // XMA blocks in file (and entries in its seek table) }; #endif @@ -127,8 +125,7 @@ static_assert(sizeof(XMA2WAVEFORMATEX) == 52, "Mismatch of XMA2 type"); namespace { -#define BLOCKALIGNPAD(a, b) \ - ((((a) + ((b) - 1)) / (b)) * (b)) +#define BLOCKALIGNPAD(a, b) ((((a) + ((b) - 1)) / (b)) * (b)) #define XACT_CONTENT_VERSION 46 // DirectX SDK (June 2010) @@ -148,79 +145,79 @@ namespace 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. }; 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. }; struct HEADER { static constexpr uint32_t SIGNATURE = MAKEFOURCC('W', 'B', 'N', 'D'); - 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 }; #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; }; 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 @@ -228,44 +225,44 @@ 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. }; 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 }; struct BANKDATA { 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 }; #pragma pack(pop) @@ -279,10 +276,15 @@ namespace static_assert(sizeof(ENTRYCOMPACT) == 4, "Mismatch with xact3wb.h"); static_assert(sizeof(BANKDATA) == 96, "Mismatch with xact3wb.h"); - 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; } @@ -316,37 +318,10 @@ namespace DWORD EncodeWMABlockAlign(DWORD dwBlockAlign, DWORD dwAvgBytesPerSec) noexcept { - static const uint32_t aWMABlockAlign[17] = - { - 929, - 1487, - 1280, - 2230, - 8917, - 8192, - 4459, - 5945, - 2304, - 1536, - 1485, - 1008, - 2731, - 4096, - 6827, - 5462, - 1280 - }; + static const uint32_t aWMABlockAlign[17] + = { 929, 1487, 1280, 2230, 8917, 8192, 4459, 5945, 2304, 1536, 1485, 1008, 2731, 4096, 6827, 5462, 1280 }; - static const uint32_t aWMAAvgBytesPerSec[7] = - { - 12000, - 24000, - 4000, - 6000, - 8000, - 20000, - 2500 - }; + static const uint32_t aWMAAvgBytesPerSec[7] = { 12000, 24000, 4000, 6000, 8000, 20000, 2500 }; auto bit = std::find(std::begin(aWMABlockAlign), std::end(aWMABlockAlign), dwBlockAlign); if (bit == std::end(aWMABlockAlign)) @@ -392,9 +367,9 @@ namespace return false; } - miniFmt.dwValue = 0; + miniFmt.dwValue = 0; miniFmt.nSamplesPerSec = wfx->nSamplesPerSec; - miniFmt.nChannels = wfx->nChannels; + miniFmt.nChannels = wfx->nChannels; switch (wfx->wFormatTag) { @@ -414,25 +389,27 @@ namespace if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { wprintf(L"ERROR: 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)) { wprintf(L"ERROR: nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\n", - wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); + wfx->nAvgBytesPerSec, + wfx->nSamplesPerSec, + wfx->nBlockAlign); return false; } - miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_PCM; + miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_PCM; miniFmt.wBitsPerSample = (wfx->wBitsPerSample == 16) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; - miniFmt.wBlockAlign = wfx->nBlockAlign; + miniFmt.wBlockAlign = wfx->nBlockAlign; return true; - case WAVE_FORMAT_IEEE_FLOAT: - wprintf(L"ERROR: Wave banks do not support IEEE float PCM data\n"); - return false; + case WAVE_FORMAT_IEEE_FLOAT: wprintf(L"ERROR: Wave banks do not support IEEE float PCM data\n"); return false; case WAVE_FORMAT_ADPCM: if ((wfx->nChannels != 1) && (wfx->nChannels != 2)) @@ -466,11 +443,10 @@ namespace for (int j = 0; j < 7 /*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; } @@ -495,20 +471,24 @@ namespace return false; } - unsigned int nHeaderBytes = 7 /*MSADPCM_HEADER_LENGTH*/ * wfx->nChannels; - unsigned int nBitsPerFrame = 4 /*MSADPCM_BITS_PER_SAMPLE*/ * wfx->nChannels; + unsigned int nHeaderBytes = 7 /*MSADPCM_HEADER_LENGTH*/ * wfx->nChannels; + unsigned int nBitsPerFrame = 4 /*MSADPCM_BITS_PER_SAMPLE*/ * wfx->nChannels; unsigned int nPcmFramesPerBlock = (wfx->nBlockAlign - nHeaderBytes) * 8 / nBitsPerFrame + 2; if (wfadpcm->wSamplesPerBlock != nPcmFramesPerBlock) { wprintf(L"ERROR: ADPCM %u-channel format with nBlockAlign = %u must have wSamplesPerBlock = %u (not %u)\n", - wfx->nChannels, wfx->nBlockAlign, nPcmFramesPerBlock, wfadpcm->wSamplesPerBlock); + wfx->nChannels, + wfx->nBlockAlign, + nPcmFramesPerBlock, + wfadpcm->wSamplesPerBlock); return false; } - miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_ADPCM; + miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_ADPCM; miniFmt.wBitsPerSample = 0; - miniFmt.wBlockAlign = AdpcmBlockSizeFromPcmFrames(wfadpcm->wSamplesPerBlock, 1) - MINIWAVEFORMAT::ADPCM_BLOCKALIGN_CONVERSION_OFFSET; + miniFmt.wBlockAlign + = AdpcmBlockSizeFromPcmFrames(wfadpcm->wSamplesPerBlock, 1) - MINIWAVEFORMAT::ADPCM_BLOCKALIGN_CONVERSION_OFFSET; } return true; @@ -544,7 +524,7 @@ namespace return false; } - miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_WMA; + miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_WMA; miniFmt.wBitsPerSample = (wfx->wFormatTag == WAVE_FORMAT_WMAUDIO3) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; { DWORD blockAlign = EncodeWMABlockAlign(wfx->nBlockAlign, wfx->nAvgBytesPerSec); @@ -609,7 +589,9 @@ namespace if (channelBits != wfx->nChannels) { wprintf(L"ERROR: XMA2 nChannels=%lu but ChannelMask (%08X) has %u bits set\n", - xmaFmt->ChannelMask, wfx->nChannels, channelBits); + xmaFmt->ChannelMask, + wfx->nChannels, + channelBits); return false; } } @@ -628,18 +610,24 @@ namespace if ((xmaFmt->PlayBegin + xmaFmt->PlayLength) > xmaFmt->SamplesEncoded) { - wprintf(L"ERROR: XMA2 play region too large (%lu + %lu > %lu)", xmaFmt->PlayBegin, xmaFmt->PlayLength, xmaFmt->SamplesEncoded); + wprintf(L"ERROR: XMA2 play region too large (%lu + %lu > %lu)", + xmaFmt->PlayBegin, + xmaFmt->PlayLength, + xmaFmt->SamplesEncoded); return false; } if ((xmaFmt->LoopBegin + xmaFmt->LoopLength) > xmaFmt->SamplesEncoded) { - wprintf(L"ERROR: XMA2 loop region too large (%lu + %lu > %lu)", xmaFmt->LoopBegin, xmaFmt->LoopLength, xmaFmt->SamplesEncoded); + wprintf(L"ERROR: XMA2 loop region too large (%lu + %lu > %lu)", + xmaFmt->LoopBegin, + xmaFmt->LoopLength, + xmaFmt->SamplesEncoded); return false; } - miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_XMA; - miniFmt.wBlockAlign = 2 * wfx->nChannels; + miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_XMA; + miniFmt.wBlockAlign = 2 * wfx->nChannels; miniFmt.wBitsPerSample = MINIWAVEFORMAT::BITDEPTH_16; } return true; @@ -647,7 +635,9 @@ namespace case WAVE_FORMAT_EXTENSIBLE: if (wfx->cbSize < (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))) { - wprintf(L"ERROR: WAVEFORMATEXTENSIBLE cbSize must be at least %zu (%u)", (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)), wfx->cbSize); + wprintf(L"ERROR: WAVEFORMATEXTENSIBLE cbSize must be at least %zu (%u)", + (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)), + wfx->cbSize); return false; } else @@ -657,12 +647,24 @@ namespace 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) { - wprintf(L"ERROR: 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]); + wprintf( + L"ERROR: WAVEFORMATEXTENSIBLE encountered with unknown GUID " + L"({%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; } @@ -680,7 +682,7 @@ namespace wprintf(L"WARNING: Integer PCM WAVEFORMATEXTENSIBLE format should not have wValidBitsPerSample = 0\n"); } else if (((wfex->Samples.wValidBitsPerSample != 8) && (wfex->Samples.wValidBitsPerSample != 16)) - || (wfex->Samples.wValidBitsPerSample > wfx->wBitsPerSample)) + || (wfex->Samples.wValidBitsPerSample > wfx->wBitsPerSample)) { wprintf(L"ERROR: Unexpected wValidBitsPerSample value (%u)\n", wfex->Samples.wValidBitsPerSample); return false; @@ -695,29 +697,30 @@ namespace if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { wprintf(L"ERROR: 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)) { wprintf(L"ERROR: nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\n", - wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); + wfx->nAvgBytesPerSec, + wfx->nSamplesPerSec, + wfx->nBlockAlign); return false; } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_PCM; - miniFmt.wBitsPerSample = (wfex->Samples.wValidBitsPerSample == 16) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; + miniFmt.wBitsPerSample + = (wfex->Samples.wValidBitsPerSample == 16) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; miniFmt.wBlockAlign = wfx->nBlockAlign; break; - case WAVE_FORMAT_IEEE_FLOAT: - wprintf(L"ERROR: Wave banks do not support float PCM data\n"); - return false; + case WAVE_FORMAT_IEEE_FLOAT: wprintf(L"ERROR: Wave banks do not support float PCM data\n"); return false; - case WAVE_FORMAT_ADPCM: - wprintf(L"ERROR: ADPCM is not supported as a WAVEFORMATEXTENSIBLE\n"); - return false; + case WAVE_FORMAT_ADPCM: wprintf(L"ERROR: ADPCM is not supported as a WAVEFORMATEXTENSIBLE\n"); return false; case WAVE_FORMAT_WMAUDIO2: case WAVE_FORMAT_WMAUDIO3: @@ -746,7 +749,8 @@ namespace } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_WMA; - miniFmt.wBitsPerSample = (wfx->wFormatTag == WAVE_FORMAT_WMAUDIO3) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; + miniFmt.wBitsPerSample + = (wfx->wFormatTag == WAVE_FORMAT_WMAUDIO3) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; { DWORD blockAlign = EncodeWMABlockAlign(wfx->nBlockAlign, wfx->nAvgBytesPerSec); if (blockAlign == DWORD(-1)) @@ -758,13 +762,9 @@ namespace } break; - case WAVE_FORMAT_XMA2: - wprintf(L"ERROR: XMA2 is not supported as a WAVEFORMATEXTENSIBLE\n"); - return false; + case WAVE_FORMAT_XMA2: wprintf(L"ERROR: XMA2 is not supported as a WAVEFORMATEXTENSIBLE\n"); return false; - default: - wprintf(L"ERROR: Unknown WAVEFORMATEXTENSIBLE format tag\n"); - return false; + default: wprintf(L"ERROR: Unknown WAVEFORMATEXTENSIBLE format tag\n"); return false; } if (wfex->dwChannelMask) @@ -773,7 +773,8 @@ namespace if (channelBits != wfx->nChannels) { wprintf(L"ERROR: WAVEFORMATEXTENSIBLE: nChannels=%u but ChannelMask has %u bits set\n", - wfx->nChannels, channelBits); + wfx->nChannels, + channelBits); return false; } else @@ -785,8 +786,7 @@ namespace return true; } - default: - return false; + default: return false; } } @@ -794,7 +794,7 @@ namespace ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - const wchar_t* g_ToolName = L"xwbtool"; + const wchar_t* g_ToolName = L"xwbtool"; const wchar_t* g_Description = L"Microsoft (R) XACT-style Wave Bank Tool [DirectXTK]"; const wchar_t* g_FeedbackURL = L"https://github.com/microsoft/DirectXTK/issues"; @@ -821,19 +821,19 @@ namespace struct WaveFile { - DirectX::WAVData data; - size_t conv; - MINIWAVEFORMAT miniFmt; + DirectX::WAVData data; + size_t conv; + MINIWAVEFORMAT miniFmt; std::unique_ptr waveData; - WaveFile() noexcept : - data{}, - conv(0), - miniFmt{} + WaveFile() noexcept + : data{}, + conv(0), + miniFmt{} {} - WaveFile(WaveFile&) = delete; - WaveFile& operator= (WaveFile&) = delete; + WaveFile(WaveFile&) = delete; + WaveFile& operator=(WaveFile&) = delete; WaveFile(WaveFile&&) = default; }; @@ -854,37 +854,31 @@ namespace ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - const SValue g_pOptions[] = - { - { L"r", OPT_RECURSIVE }, - { L"s", OPT_STREAMING }, - { L"af", OPT_ADVANCED_FORMAT }, - { L"o", OPT_OUTPUTFILE }, - { L"l", OPT_TOLOWER }, - { L"h", OPT_OUTPUTHEADER }, - { L"y", OPT_OVERWRITE }, - { L"c", OPT_COMPACT }, - { L"nc", OPT_NOCOMPACT }, - { L"f", OPT_FRIENDLY_NAMES }, - { L"nologo", OPT_NOLOGO }, - { L"flist", OPT_FILELIST }, - { nullptr, 0 } - }; - - const SValue g_pOptionsLong[] = - { - { L"advanced-format", OPT_ADVANCED_FORMAT }, - { L"compact", OPT_COMPACT }, - { L"file-list", OPT_FILELIST }, - { L"friendly-names", OPT_FRIENDLY_NAMES }, - { L"help", OPT_HELP }, - { L"no-compact", OPT_NOCOMPACT }, - { L"overwrite", OPT_OVERWRITE }, - { L"streaming", OPT_STREAMING }, - { L"to-lowercase", OPT_TOLOWER }, - { L"version", OPT_VERSION }, - { nullptr, 0 } - }; + const SValue g_pOptions[] = { { L"r", OPT_RECURSIVE }, + { L"s", OPT_STREAMING }, + { L"af", OPT_ADVANCED_FORMAT }, + { L"o", OPT_OUTPUTFILE }, + { L"l", OPT_TOLOWER }, + { L"h", OPT_OUTPUTHEADER }, + { L"y", OPT_OVERWRITE }, + { L"c", OPT_COMPACT }, + { L"nc", OPT_NOCOMPACT }, + { L"f", OPT_FRIENDLY_NAMES }, + { L"nologo", OPT_NOLOGO }, + { L"flist", OPT_FILELIST }, + { nullptr, 0 } }; + + const SValue g_pOptionsLong[] = { { L"advanced-format", OPT_ADVANCED_FORMAT }, + { L"compact", OPT_COMPACT }, + { L"file-list", OPT_FILELIST }, + { L"friendly-names", OPT_FRIENDLY_NAMES }, + { L"help", OPT_HELP }, + { L"no-compact", OPT_NOCOMPACT }, + { L"overwrite", OPT_OVERWRITE }, + { L"streaming", OPT_STREAMING }, + { L"to-lowercase", OPT_TOLOWER }, + { L"version", OPT_VERSION }, + { nullptr, 0 } }; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @@ -894,30 +888,29 @@ namespace { PrintLogo(false, g_ToolName, g_Description); - static const wchar_t* const s_usage = - L"Usage: xwbtool [--] \n\n"; - - static const wchar_t* const s_fullUsage = - L" -r wildcard filename search is recursive\n" - L" -flist , --file-list \n" - L" use text file with a list of input files (one per line)\n" - L"\n" - L" -s, --streaming creates a streaming wave bank,\n" - L" otherwise an in-memory bank is created\n" - L" -af, --advanced-format for streaming, use 4K instead of 2K alignment\n" - L" (required for advanced format drives without 512e)\n" - L"\n" - L" -o output filename\n" - L" -h output C/C++ header\n" - L" -l, --to-lowercase force output filename to lower case\n" - L" -y, --overwrite overwrite existing output file (if any)\n" - L"\n" - L" -c, --compact force creation of compact wavebank\n" - L" -nc, --no-compact force creation of non-compact wavebank\n" - L" -f, --friendly-names include entry friendly names\n" - L" -nologo suppress copyright message\n" - L"\n" - L" '-- ' is needed if any input filepath starts with the '-' or '/' character\n"; + static const wchar_t* const s_usage = L"Usage: xwbtool [--] \n\n"; + + static const wchar_t* const s_fullUsage + = L" -r wildcard filename search is recursive\n" + L" -flist , --file-list \n" + L" use text file with a list of input files (one per line)\n" + L"\n" + L" -s, --streaming creates a streaming wave bank,\n" + L" otherwise an in-memory bank is created\n" + L" -af, --advanced-format for streaming, use 4K instead of 2K alignment\n" + L" (required for advanced format drives without 512e)\n" + L"\n" + L" -o output filename\n" + L" -h output C/C++ header\n" + L" -l, --to-lowercase force output filename to lower case\n" + L" -y, --overwrite overwrite existing output file (if any)\n" + L"\n" + L" -c, --compact force creation of compact wavebank\n" + L" -nc, --no-compact force creation of non-compact wavebank\n" + L" -f, --friendly-names include entry friendly names\n" + L" -nologo suppress copyright message\n" + L"\n" + L" '-- ' is needed if any input filepath starts with the '-' or '/' character\n"; wprintf(L"%ls", s_usage); @@ -931,36 +924,36 @@ namespace { switch (wFormatTag) { - case WAVE_FORMAT_PCM: return "PCM"; - case WAVE_FORMAT_ADPCM: return "MS ADPCM"; - case WAVE_FORMAT_EXTENSIBLE: return "EXTENSIBLE"; - case WAVE_FORMAT_IEEE_FLOAT: return "IEEE float"; - case WAVE_FORMAT_MPEGLAYER3: return "ISO/MPEG Layer3"; + case WAVE_FORMAT_PCM: return "PCM"; + case WAVE_FORMAT_ADPCM: return "MS ADPCM"; + case WAVE_FORMAT_EXTENSIBLE: return "EXTENSIBLE"; + case WAVE_FORMAT_IEEE_FLOAT: return "IEEE float"; + case WAVE_FORMAT_MPEGLAYER3: return "ISO/MPEG Layer3"; case WAVE_FORMAT_DOLBY_AC3_SPDIF: return "Dolby Audio Codec 3 over S/PDIF"; - case WAVE_FORMAT_WMAUDIO2: return "Windows Media Audio"; - case WAVE_FORMAT_WMAUDIO3: return "Windows Media Audio Pro"; - case WAVE_FORMAT_WMASPDIF: return "Windows Media Audio over S/PDIF"; - case 0x165: /*WAVE_FORMAT_XMA*/ return "Xbox XMA"; - case 0x166: /*WAVE_FORMAT_XMA2*/ return "Xbox XMA2"; - default: return "*UNKNOWN*"; + case WAVE_FORMAT_WMAUDIO2: return "Windows Media Audio"; + case WAVE_FORMAT_WMAUDIO3: return "Windows Media Audio Pro"; + case WAVE_FORMAT_WMASPDIF: return "Windows Media Audio over S/PDIF"; + case 0x165: /*WAVE_FORMAT_XMA*/ return "Xbox XMA"; + case 0x166: /*WAVE_FORMAT_XMA2*/ return "Xbox XMA2"; + default: return "*UNKNOWN*"; } } - const char *ChannelDesc(DWORD dwChannelMask) noexcept + const char* ChannelDesc(DWORD dwChannelMask) noexcept { switch (dwChannelMask) { - case 0x00000004 /*SPEAKER_MONO*/: return "Mono"; - case 0x00000003 /* SPEAKER_STEREO */: return "Stereo"; - case 0x0000000B /* SPEAKER_2POINT1 */: return "2.1"; - case 0x00000107 /* SPEAKER_SURROUND */: return "Surround"; - case 0x00000033 /* SPEAKER_QUAD */: return "Quad"; - case 0x0000003B /* SPEAKER_4POINT1 */: return "4.1"; - case 0x0000003F /* SPEAKER_5POINT1 */: return "5.1"; - case 0x000000FF /* SPEAKER_7POINT1 */: return "7.1"; + case 0x00000004 /*SPEAKER_MONO*/: return "Mono"; + case 0x00000003 /* SPEAKER_STEREO */: return "Stereo"; + case 0x0000000B /* SPEAKER_2POINT1 */: return "2.1"; + case 0x00000107 /* SPEAKER_SURROUND */: return "Surround"; + case 0x00000033 /* SPEAKER_QUAD */: return "Quad"; + case 0x0000003B /* SPEAKER_4POINT1 */: return "4.1"; + case 0x0000003F /* SPEAKER_5POINT1 */: return "5.1"; + case 0x000000FF /* SPEAKER_7POINT1 */: return "7.1"; case 0x0000060F /* SPEAKER_5POINT1_SURROUND */: return "Surround5.1"; case 0x0000063F /* SPEAKER_7POINT1_SURROUND */: return "Surround7.1"; - default: return "Custom"; + default: return "Custom"; } } @@ -971,14 +964,23 @@ namespace { auto wext = reinterpret_cast(&wave.data.wfx); - wprintf(L" (%hs %u channels, %u-bit, %lu Hz, CMask:%hs)", GetFormatTagName(wave.data.wfx->wFormatTag), wave.data.wfx->nChannels, wave.data.wfx->wBitsPerSample, wave.data.wfx->nSamplesPerSec, ChannelDesc(wext->dwChannelMask)); + wprintf(L" (%hs %u channels, %u-bit, %lu Hz, CMask:%hs)", + GetFormatTagName(wave.data.wfx->wFormatTag), + wave.data.wfx->nChannels, + wave.data.wfx->wBitsPerSample, + wave.data.wfx->nSamplesPerSec, + ChannelDesc(wext->dwChannelMask)); } else { - wprintf(L" (%hs %u channels, %u-bit, %lu Hz)", GetFormatTagName(wave.data.wfx->wFormatTag), wave.data.wfx->nChannels, wave.data.wfx->wBitsPerSample, wave.data.wfx->nSamplesPerSec); + wprintf(L" (%hs %u channels, %u-bit, %lu Hz)", + GetFormatTagName(wave.data.wfx->wFormatTag), + wave.data.wfx->nChannels, + wave.data.wfx->wBitsPerSample, + wave.data.wfx->nSamplesPerSec); } } -} +} // namespace ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @@ -1019,9 +1021,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) return 0; } - uint32_t dwOptions = 0; + uint32_t dwOptions = 0; std::list conversion; - bool allowOpts = true; + bool allowOpts = true; for (int iArg = 1; iArg < argc; iArg++) { @@ -1030,13 +1032,14 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (allowOpts && (('-' == pArg[0]) || ('/' == pArg[0]))) { uint32_t dwOption = 0; - PWSTR pValue = nullptr; + PWSTR pValue = nullptr; if (('-' == pArg[0]) && ('-' == pArg[1])) { if (pArg[2] == 0) { - // "-- " is the POSIX standard for "end of options" marking to escape the '-' and '/' characters at the start of filepaths. + // "-- " is the POSIX standard for "end of options" marking to escape the '-' and '/' characters at the start of + // filepaths. allowOpts = false; continue; } @@ -1044,7 +1047,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) { pArg += 2; - for (pValue = pArg; *pValue && (':' != *pValue) && ('=' != *pValue); ++pValue); + for (pValue = pArg; *pValue && (':' != *pValue) && ('=' != *pValue); ++pValue) + ; if (*pValue) *pValue++ = 0; @@ -1056,7 +1060,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) { pArg++; - for (pValue = pArg; *pValue && (':' != *pValue) && ('=' != *pValue); ++pValue); + for (pValue = pArg; *pValue && (':' != *pValue) && ('=' != *pValue); ++pValue) + ; if (*pValue) *pValue++ = 0; @@ -1075,9 +1080,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) switch (dwOption) { - case 0: - wprintf(L"ERROR: Unknown option: `%ls`\n\nUse %ls --help\n", pArg, g_ToolName); - return 1; + case 0: wprintf(L"ERROR: Unknown option: `%ls`\n\nUse %ls --help\n", pArg, g_ToolName); return 1; case OPT_FILELIST: case OPT_OUTPUTHEADER: @@ -1085,13 +1088,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) // These don't use flag bits break; - case OPT_VERSION: - PrintLogo(true, g_ToolName, g_Description); - return 0; + case OPT_VERSION: PrintLogo(true, g_ToolName, g_Description); return 0; - case OPT_HELP: - PrintUsage(true); - return 0; + case OPT_HELP: PrintUsage(true); return 0; default: if (dwOptions & (UINT32_C(1) << dwOption)) @@ -1126,19 +1125,17 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) switch (dwOption) { - case OPT_OUTPUTFILE: - { - std::filesystem::path path(pValue); - outputFile = path.make_preferred().native(); - } - break; + case OPT_OUTPUTFILE: { + std::filesystem::path path(pValue); + outputFile = path.make_preferred().native(); + } + break; - case OPT_OUTPUTHEADER: - { - std::filesystem::path path(pValue); - headerFile = path.make_preferred().native(); - } - break; + case OPT_OUTPUTHEADER: { + std::filesystem::path path(pValue); + headerFile = path.make_preferred().native(); + } + break; case OPT_ADVANCED_FORMAT: // Must disable compact version to support 4K @@ -1171,26 +1168,25 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } break; - case OPT_FILELIST: + case OPT_FILELIST: { + std::filesystem::path path(pValue); + std::wifstream inFile(path.make_preferred().c_str()); + if (!inFile) { - std::filesystem::path path(pValue); - std::wifstream inFile(path.make_preferred().c_str()); - if (!inFile) - { - wprintf(L"Error opening -flist file %ls\n", pValue); - return 1; - } + wprintf(L"Error opening -flist file %ls\n", pValue); + return 1; + } - inFile.imbue(std::locale::classic()); + inFile.imbue(std::locale::classic()); - ProcessFileList(inFile, conversion); - } - break; + ProcessFileList(inFile, conversion); + } + break; } } else if (wcspbrk(pArg, L"?*") != nullptr) { - size_t count = conversion.size(); + size_t count = conversion.size(); std::filesystem::path path(pArg); SearchForFiles(path.make_preferred(), conversion, (dwOptions & (UINT32_C(1) << OPT_RECURSIVE)) != 0, nullptr); if (conversion.size() <= count) @@ -1201,7 +1197,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } else { - SConversion conv = {}; + SConversion conv = {}; std::filesystem::path path(pArg); conv.szSrc = path.make_preferred().native(); conversion.push_back(conv); @@ -1262,9 +1258,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) // Gather wave files std::unique_ptr entries; - std::unique_ptr entryNames; - std::vector waves; - MINIWAVEFORMAT compactFormat = {}; + std::unique_ptr entryNames; + std::vector waves; + MINIWAVEFORMAT compactFormat = {}; bool xma = false; @@ -1316,8 +1312,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) // Convert wave format to miniformat, failing if any won't map // Check to see if we can use the compact wave bank format - bool compact = (dwOptions & (UINT32_C(1) << OPT_NOCOMPACT)) ? false : true; - int reason = 0; + bool compact = (dwOptions & (UINT32_C(1) << OPT_NOCOMPACT)) ? false : true; + int reason = 0; uint64_t waveOffset = 0; for (auto it = waves.begin(); it != waves.end(); ++it) @@ -1374,7 +1370,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } if (reason & 0x4) { - wprintf(L"- Audio wave data is too large to encode in compact wavebank (%llu > %llu).\n", waveOffset, (uint64_t(MAX_COMPACT_DATA_SEGMENT_SIZE) * uint64_t(dwAlignment))); + wprintf(L"- Audio wave data is too large to encode in compact wavebank (%llu > %llu).\n", + waveOffset, + (uint64_t(MAX_COMPACT_DATA_SEGMENT_SIZE) * uint64_t(dwAlignment))); } return 1; } @@ -1389,8 +1387,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) memset(entryNames.get(), 0, sizeof(char) * waves.size() * ENTRYNAME_LENGTH); } - waveOffset = 0; - size_t count = 0; + waveOffset = 0; + size_t count = 0; size_t seekEntries = 0; for (auto it = waves.begin(); it != waves.end(); ++it, ++count) { @@ -1409,18 +1407,17 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) duration = reinterpret_cast(wfx)->SamplesEncoded; break; - case MINIWAVEFORMAT::TAG_ADPCM: + case MINIWAVEFORMAT::TAG_ADPCM: { + auto adpcmFmt = reinterpret_cast(wfx); + duration = (uint64_t(it->data.audioBytes) / uint64_t(wfx->nBlockAlign)) * uint64_t(adpcmFmt->wSamplesPerBlock); + int partial = it->data.audioBytes % wfx->nBlockAlign; + if (partial) { - auto adpcmFmt = reinterpret_cast(wfx); - duration = (uint64_t(it->data.audioBytes) / uint64_t(wfx->nBlockAlign)) * uint64_t(adpcmFmt->wSamplesPerBlock); - int partial = it->data.audioBytes % wfx->nBlockAlign; - if (partial) - { - if (partial >= (7 * wfx->nChannels)) - duration += (uint64_t(partial) * 2 / uint64_t(wfx->nChannels - 12)); - } + if (partial >= (7 * wfx->nChannels)) + duration += (uint64_t(partial) * 2 / uint64_t(wfx->nChannels - 12)); } - break; + } + break; case MINIWAVEFORMAT::TAG_WMA: if (it->data.seekCount > 0) @@ -1464,7 +1461,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (it->data.loopLength > 0) { - entry->LoopRegion.dwStartSample = it->data.loopStart; + entry->LoopRegion.dwStartSample = it->data.loopStart; entry->LoopRegion.dwTotalSamples = it->data.loopLength; } } @@ -1479,7 +1476,14 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) wchar_t wEntryName[ENTRYNAME_LENGTH] = {}; wcscpy_s(wEntryName, ename.stem().c_str()); - int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, wEntryName, -1, &entryNames[count * ENTRYNAME_LENGTH], ENTRYNAME_LENGTH, nullptr, nullptr); + int result = WideCharToMultiByte(CP_UTF8, + WC_NO_BEST_FIT_CHARS, + wEntryName, + -1, + &entryNames[count * ENTRYNAME_LENGTH], + ENTRYNAME_LENGTH, + nullptr, + nullptr); if (result <= 0) { memset(&entryNames[count * ENTRYNAME_LENGTH], 0, ENTRYNAME_LENGTH); @@ -1494,15 +1498,15 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) // Create wave bank assert(!outputFile.empty()); - wprintf(L"writing %ls%ls wavebank %ls w/ %zu entries\n", (compact) ? L"compact " : L"", (dwOptions & (UINT32_C(1) << OPT_STREAMING)) ? L"streaming" : L"in-memory", outputFile.c_str(), waves.size()); + wprintf(L"writing %ls%ls wavebank %ls w/ %zu entries\n", + (compact) ? L"compact " : L"", + (dwOptions & (UINT32_C(1) << OPT_STREAMING)) ? L"streaming" : L"in-memory", + outputFile.c_str(), + waves.size()); fflush(stdout); - ScopedHandle hFile(safe_handle(CreateFileW( - outputFile.c_str(), - GENERIC_WRITE, 0, - nullptr, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, - nullptr))); + ScopedHandle hFile( + safe_handle(CreateFileW(outputFile.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); if (!hFile) { wprintf(L"ERROR: Failed opening output file %ls, %lu\n", outputFile.c_str(), GetLastError()); @@ -1510,10 +1514,10 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // Setup wave bank header - HEADER header = {}; - header.dwSignature = HEADER::SIGNATURE; + HEADER header = {}; + header.dwSignature = HEADER::SIGNATURE; header.dwHeaderVersion = HEADER::VERSION; - header.dwVersion = XACT_CONTENT_VERSION; + header.dwVersion = XACT_CONTENT_VERSION; DWORD segmentOffset = sizeof(HEADER); @@ -1523,7 +1527,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) BANKDATA data = {}; data.dwEntryCount = uint32_t(waves.size()); - data.dwAlignment = dwAlignment; + data.dwAlignment = dwAlignment; GetSystemTimeAsFileTime(&data.BuildTime); @@ -1557,7 +1561,14 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) wchar_t wBankName[BANKDATA::BANKNAME_LENGTH] = {}; wcscpy_s(wBankName, bname.stem().c_str()); - int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, wBankName, -1, data.szBankName, BANKDATA::BANKNAME_LENGTH, nullptr, nullptr); + int result = WideCharToMultiByte(CP_UTF8, + WC_NO_BEST_FIT_CHARS, + wBankName, + -1, + data.szBankName, + BANKDATA::BANKNAME_LENGTH, + nullptr, + nullptr); if (result <= 0) { memset(data.szBankName, 0, BANKDATA::BANKNAME_LENGTH); @@ -1571,8 +1582,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } DWORD bytesWritten; - if (!WriteFile(hFile.get(), &data, sizeof(data), &bytesWritten, nullptr) - || bytesWritten != sizeof(data)) + if (!WriteFile(hFile.get(), &data, sizeof(data), &bytesWritten, nullptr) || bytesWritten != sizeof(data)) { wprintf(L"ERROR: Failed writing bank data to %ls, %lu\n", outputFile.c_str(), GetLastError()); return 1; @@ -1592,8 +1602,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } uint32_t entryBytes = uint32_t(waves.size() * data.dwEntryMetaDataElementSize); - if (!WriteFile(hFile.get(), entries.get(), entryBytes, &bytesWritten, nullptr) - || bytesWritten != entryBytes) + if (!WriteFile(hFile.get(), entries.get(), entryBytes, &bytesWritten, nullptr) || bytesWritten != entryBytes) { wprintf(L"ERROR: Failed writing entry metadata to %ls, %lu\n", outputFile.c_str(), GetLastError()); return 1; @@ -1621,14 +1630,14 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } uint32_t seekoffset = 0; - uint32_t windex = 0; + uint32_t windex = 0; for (auto it = waves.begin(); it != waves.end(); ++it, ++windex) { if (it->miniFmt.wFormatTag == MINIWAVEFORMAT::TAG_WMA) { seekTables[windex] = seekoffset * sizeof(uint32_t); - uint32_t baseoffset = uint32_t(waves.size() + seekoffset); + uint32_t baseoffset = uint32_t(waves.size() + seekoffset); seekTables[baseoffset] = it->data.seekCount; for (uint32_t j = 0; j < it->data.seekCount; ++j) @@ -1642,7 +1651,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) { seekTables[windex] = seekoffset * sizeof(uint32_t); - uint32_t baseoffset = uint32_t(waves.size() + seekoffset); + uint32_t baseoffset = uint32_t(waves.size() + seekoffset); seekTables[baseoffset] = it->data.seekCount; for (uint32_t j = 0; j < it->data.seekCount; ++j) @@ -1660,8 +1669,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) uint32_t seekLen = uint32_t(sizeof(uint32_t) * seekEntries); - if (!WriteFile(hFile.get(), seekTables.get(), seekLen, &bytesWritten, nullptr) - || bytesWritten != seekLen) + if (!WriteFile(hFile.get(), seekTables.get(), seekLen, &bytesWritten, nullptr) || bytesWritten != seekLen) { wprintf(L"ERROR: Failed writing seek tables to %ls, %lu\n", outputFile.c_str(), GetLastError()); return 1; @@ -1688,8 +1696,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } uint32_t entryNamesBytes = uint32_t(count * data.dwEntryNameElementSize); - if (!WriteFile(hFile.get(), entryNames.get(), entryNamesBytes, &bytesWritten, nullptr) - || bytesWritten != entryNamesBytes) + if (!WriteFile(hFile.get(), entryNames.get(), entryNamesBytes, &bytesWritten, nullptr) || bytesWritten != entryNamesBytes) { wprintf(L"ERROR: Failed writing friendly entry names to %ls, %lu\n", outputFile.c_str(), GetLastError()); return 1; @@ -1714,8 +1721,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) return 1; } - if (!WriteFile(hFile.get(), it.data.startAudio, it.data.audioBytes, &bytesWritten, nullptr) - || bytesWritten != it.data.audioBytes) + if (!WriteFile(hFile.get(), it.data.startAudio, it.data.audioBytes, &bytesWritten, nullptr) || bytesWritten != it.data.audioBytes) { wprintf(L"ERROR: Failed writing audio data to %ls, %lu\n", outputFile.c_str(), GetLastError()); return 1; @@ -1753,8 +1759,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) return 1; } - if (!WriteFile(hFile.get(), &header, sizeof(header), &bytesWritten, nullptr) - || bytesWritten != sizeof(header)) + if (!WriteFile(hFile.get(), &header, sizeof(header), &bytesWritten, nullptr) || bytesWritten != sizeof(header)) { wprintf(L"ERROR: Failed committing output file %ls, HDR %lu\n", outputFile.c_str(), GetLastError()); return 1; From e2c53e89f5cbaa898c05fb6d16a0aab334a4d783 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 12:02:45 -0700 Subject: [PATCH 03/15] Keep some formatting --- Src/WICTextureLoader.cpp | 114 ++++++++++++++++++++------------------- 1 file changed, 59 insertions(+), 55 deletions(-) diff --git a/Src/WICTextureLoader.cpp b/Src/WICTextureLoader.cpp index db7685e8..dbb4cdbc 100644 --- a/Src/WICTextureLoader.cpp +++ b/Src/WICTextureLoader.cpp @@ -52,27 +52,29 @@ namespace }; constexpr WICTranslate g_WICFormats[] = { - { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, + // clang-format off + { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, - { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, - { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, + { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, + { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, - { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, - { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 - { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, + { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 - { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 - { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, + { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, - { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, - { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, + { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, + { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, - { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, - { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, - { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, - { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, + { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, + { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, + { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, + { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, - { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, + { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, + // clang-format on }; //------------------------------------------------------------------------------------- @@ -90,60 +92,62 @@ namespace }; 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 + { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM - { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM - { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM - { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT - { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT + { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT + { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT - { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM + { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM - { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM + { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM - { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT - { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT - { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM - { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM - { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT // We don't support n-channel formats + // clang-format on }; bool g_WIC2 = false; @@ -680,7 +684,7 @@ namespace #if defined(_XBOX_ONE) && defined(_TITLE) ID3D11Texture2D* pStaging = nullptr; CD3D11_TEXTURE2D_DESC - stagingDesc(format, twidth, theight, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, 0); + stagingDesc(format, twidth, theight, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, 0); initData.pSysMem = temp.get(); initData.SysMemPitch = static_cast(rowPitch); initData.SysMemSlicePitch = static_cast(imageSize); From 1451327d6f3755f7835f6142d95a8cd5e8526ed3 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 12:33:03 -0700 Subject: [PATCH 04/15] Use matching clang-format --- .github/workflows/lint.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 7923ae89..6b6fafcd 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -30,6 +30,11 @@ jobs: with: fetch-depth: 0 + - name: Install VS 2022's version of clang-format + run: > + sudo apt install -y clang-format-19 + clang-format --version + - name: Lint Code Base uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 env: From d320a3c0df76a5ac5e04f87932f04ea9644b712b Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 12:35:45 -0700 Subject: [PATCH 05/15] Fix syntax --- .github/workflows/lint.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 6b6fafcd..0b57c8e5 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -31,9 +31,7 @@ jobs: fetch-depth: 0 - name: Install VS 2022's version of clang-format - run: > - sudo apt install -y clang-format-19 - clang-format --version + run: sudo apt install -y clang-format-19 - name: Lint Code Base uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 From 569d65baef532a35007367f682cbc84e04a47d9f Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 12:39:47 -0700 Subject: [PATCH 06/15] Try to map to older version --- .github/workflows/lint.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0b57c8e5..c5f6ce66 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -31,7 +31,10 @@ jobs: fetch-depth: 0 - name: Install VS 2022's version of clang-format - run: sudo apt install -y clang-format-19 + run: | + sudo apt install -y clang-format-19 + sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-19 190 + sudo update-alternatives --config clang-format - name: Lint Code Base uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 From 472ba4e1e679c9eeb345fc344eed2b3772b418c9 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 12:44:28 -0700 Subject: [PATCH 07/15] try another appraoch --- .github/workflows/lint.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index c5f6ce66..320b67ff 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -33,8 +33,7 @@ jobs: - name: Install VS 2022's version of clang-format run: | sudo apt install -y clang-format-19 - sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-19 190 - sudo update-alternatives --config clang-format + sudo cp /usr/bin/clang-format-19 /usr/local/bin/clang-format - name: Lint Code Base uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 From 16df49a819de3e349e9a47d01c1b01e9a7301a7b Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 13:01:13 -0700 Subject: [PATCH 08/15] Have to use clang-format 21.1.2. locally --- .github/workflows/lint.yml | 5 -- Audio/SoundCommon.h | 8 +- Inc/Audio.h | 33 ++++--- Inc/Effects.h | 179 ++++++++++++++++++------------------- Inc/GamePad.h | 7 +- Inc/GeometricPrimitive.h | 81 ++++++----------- Inc/Model.h | 5 +- Inc/Mouse.h | 2 +- Inc/PostProcess.h | 6 +- Inc/ScreenGrab.h | 5 +- Inc/SimpleMath.h | 10 +-- Inc/SpriteBatch.h | 4 +- Inc/SpriteFont.h | 6 +- Inc/VertexTypes.h | 4 +- Src/DDSTextureLoader.cpp | 40 ++++----- Src/ScreenGrab.cpp | 5 +- Src/WICTextureLoader.cpp | 42 ++++----- Src/pch.h | 4 +- build/Format.ps1 | 11 +++ 19 files changed, 204 insertions(+), 253 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 320b67ff..7923ae89 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -30,11 +30,6 @@ jobs: with: fetch-depth: 0 - - name: Install VS 2022's version of clang-format - run: | - sudo apt install -y clang-format-19 - sudo cp /usr/bin/clang-format-19 /usr/local/bin/clang-format - - name: Lint Code Base uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 env: diff --git a/Audio/SoundCommon.h b/Audio/SoundCommon.h index dd25c067..a6788f9c 100644 --- a/Audio/SoundCommon.h +++ b/Audio/SoundCommon.h @@ -84,11 +84,9 @@ namespace DirectX // 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 + 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; #endif diff --git a/Inc/Audio.h b/Inc/Audio.h index 2126270f..3b88cb00 100644 --- a/Inc/Audio.h +++ b/Inc/Audio.h @@ -249,7 +249,7 @@ namespace DirectX // 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); + DIRECTX_TOOLKIT_API void __cdecl SetMasterVolume(float volume); // Master volume property for all sounds DIRECTX_TOOLKIT_API void __cdecl SetReverb(AUDIO_ENGINE_REVERB reverb); @@ -301,16 +301,16 @@ namespace DirectX // 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 @@ -381,16 +381,14 @@ 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; + 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 @@ -505,7 +503,7 @@ namespace DirectX } void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Position), v); } - void __cdecl SetPosition(const XMFLOAT3& pos) noexcept + void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; Position.y = pos.y; @@ -513,7 +511,7 @@ namespace DirectX } void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Velocity), v); } - void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept + void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; Velocity.y = vel.y; @@ -599,7 +597,7 @@ namespace DirectX } void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Position), v); } - void __cdecl SetPosition(const XMFLOAT3& pos) noexcept + void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; Position.y = pos.y; @@ -607,7 +605,7 @@ namespace DirectX } void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast(&Velocity), v); } - void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept + void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; Velocity.y = vel.y; @@ -809,9 +807,8 @@ namespace DirectX 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, uint32_t offset, size_t audioBytes); DIRECTX_TOOLKIT_API SoundState __cdecl GetState() noexcept; diff --git a/Inc/Effects.h b/Inc/Effects.h index 575e59e5..c9607ff0 100644 --- a/Inc/Effects.h +++ b/Inc/Effects.h @@ -100,11 +100,11 @@ namespace DirectX IEffectLights(const IEffectLights&) = delete; IEffectLights& operator=(const IEffectLights&) = delete; - virtual void __cdecl SetLightingEnabled(bool value) = 0; - virtual void __cdecl SetPerPixelLighting(bool value) = 0; + virtual void __cdecl SetLightingEnabled(bool value) = 0; + virtual void __cdecl SetPerPixelLighting(bool value) = 0; virtual void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) = 0; - virtual void __cdecl SetLightEnabled(int whichLight, bool 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; @@ -128,9 +128,9 @@ namespace DirectX IEffectFog(const IEffectFog&) = delete; IEffectFog& operator=(const IEffectFog&) = delete; - virtual void __cdecl SetFogEnabled(bool value) = 0; - virtual void __cdecl SetFogStart(float value) = 0; - virtual void __cdecl SetFogEnd(float value) = 0; + virtual void __cdecl SetFogEnabled(bool 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: @@ -191,17 +191,17 @@ 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 __cdecl SetLightingEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(bool value) override; 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; @@ -209,9 +209,9 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool 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; // Vertex color setting. @@ -259,13 +259,13 @@ 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 SetFogEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool 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; // Vertex color setting. @@ -313,13 +313,13 @@ 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 SetFogEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool 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; // Vertex color setting. @@ -372,23 +372,23 @@ 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 SetPerPixelLighting(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetLightEnabled(int whichLight, bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(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 SetFogEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool 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. @@ -396,10 +396,10 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl SetEnvironmentMap(_In_opt_ ID3D11ShaderResourceView* value); // Environment map settings. - DIRECTX_TOOLKIT_API void __cdecl SetMode(Mapping mapping); - DIRECTX_TOOLKIT_API void __cdecl SetEnvironmentMapAmount(float value); + DIRECTX_TOOLKIT_API void __cdecl SetMode(Mapping mapping); + 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); // Normal compression settings. DIRECTX_TOOLKIT_API void __cdecl SetBiasedVertexNormals(bool value); @@ -411,7 +411,7 @@ namespace DirectX std::unique_ptr pImpl; // Unsupported interface methods. - DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override; }; @@ -445,16 +445,16 @@ 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 __cdecl SetPerPixelLighting(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(bool value) override; 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; @@ -462,9 +462,9 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool 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. @@ -522,22 +522,22 @@ 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); // Additional settings. DIRECTX_TOOLKIT_API void XM_CALLCONV SetUVTransform(FXMMATRIX value); - DIRECTX_TOOLKIT_API void __cdecl SetViewport(float width, float height); - DIRECTX_TOOLKIT_API void __cdecl SetTime(float time); - DIRECTX_TOOLKIT_API void __cdecl SetAlphaDiscardEnable(bool value); + DIRECTX_TOOLKIT_API void __cdecl SetViewport(float width, float height); + DIRECTX_TOOLKIT_API void __cdecl SetTime(float time); + DIRECTX_TOOLKIT_API void __cdecl SetAlphaDiscardEnable(bool value); // Light settings. - DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; 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; @@ -623,15 +623,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; @@ -639,9 +639,9 @@ namespace DirectX DIRECTX_TOOLKIT_API void __cdecl EnableDefaultLighting() override; // Fog settings. - DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogStart(float value) override; - DIRECTX_TOOLKIT_API void __cdecl SetFogEnd(float value) override; + DIRECTX_TOOLKIT_API void __cdecl SetFogEnabled(bool 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; // Vertex color setting. @@ -723,17 +723,17 @@ 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(_In_opt_ ID3D11ShaderResourceView* value); @@ -746,9 +746,8 @@ namespace DirectX _In_opt_ ID3D11ShaderResourceView* normal, _In_opt_ ID3D11ShaderResourceView* roughnessMetallicAmbientOcclusion); - DIRECTX_TOOLKIT_API void __cdecl SetIBLTextures(_In_opt_ ID3D11ShaderResourceView* radiance, - int numRadianceMips, - _In_opt_ ID3D11ShaderResourceView* irradiance); + DIRECTX_TOOLKIT_API void __cdecl + SetIBLTextures(_In_opt_ ID3D11ShaderResourceView* radiance, int numRadianceMips, _In_opt_ ID3D11ShaderResourceView* irradiance); // Normal compression settings. DIRECTX_TOOLKIT_API void __cdecl SetBiasedVertexNormals(bool value); @@ -772,8 +771,8 @@ namespace DirectX private: // Unsupported interface methods. - DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(bool value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; DIRECTX_TOOLKIT_API void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override; }; @@ -835,9 +834,9 @@ namespace DirectX DIRECTX_TOOLKIT_API void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override; // Debug Settings. - DIRECTX_TOOLKIT_API void __cdecl SetMode(Mode debugMode); + DIRECTX_TOOLKIT_API void __cdecl SetMode(Mode debugMode); 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); // Vertex color setting. DIRECTX_TOOLKIT_API void __cdecl SetVertexColorEnabled(bool value); @@ -894,14 +893,14 @@ 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; @@ -924,10 +923,10 @@ namespace DirectX // 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(); // Vertex color setting. DIRECTX_TOOLKIT_API void __cdecl SetVertexColorEnabled(bool value); @@ -948,10 +947,10 @@ namespace DirectX private: // Unsupported interface methods. - DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; - DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetLightingEnabled(bool value) override; + DIRECTX_TOOLKIT_API void __cdecl SetPerPixelLighting(bool value) override; 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; }; @@ -1057,9 +1056,9 @@ namespace DirectX // IEffectFactory methods. DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // Settings. DIRECTX_TOOLKIT_API void __cdecl ReleaseCache(); @@ -1098,9 +1097,9 @@ namespace DirectX // IEffectFactory methods. DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // Settings. DIRECTX_TOOLKIT_API void __cdecl ReleaseCache(); @@ -1138,9 +1137,9 @@ namespace DirectX // IEffectFactory methods. DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // Settings. DIRECTX_TOOLKIT_API void __cdecl ReleaseCache(); @@ -1184,9 +1183,9 @@ namespace DirectX // IEffectFactory methods. DIRECTX_TOOLKIT_API std::shared_ptr __cdecl CreateEffect(_In_ const EffectInfo& info, _In_opt_ ID3D11DeviceContext* deviceContext) override; - DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, - _In_opt_ ID3D11DeviceContext* deviceContext, - _Outptr_ ID3D11ShaderResourceView** textureView) override; + DIRECTX_TOOLKIT_API void __cdecl CreateTexture(_In_z_ const wchar_t* name, + _In_opt_ ID3D11DeviceContext* deviceContext, + _Outptr_ ID3D11ShaderResourceView** textureView) override; // DGSL methods. struct DIRECTX_TOOLKIT_API DGSLEffectInfo : public EffectInfo diff --git a/Inc/GamePad.h b/Inc/GamePad.h index 8b92fddf..9c2a54f5 100644 --- a/Inc/GamePad.h +++ b/Inc/GamePad.h @@ -321,11 +321,8 @@ namespace DirectX 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; diff --git a/Inc/GeometricPrimitive.h b/Inc/GeometricPrimitive.h index b97828b0..117ce9b3 100644 --- a/Inc/GeometricPrimitive.h +++ b/Inc/GeometricPrimitive.h @@ -59,22 +59,17 @@ namespace DirectX DIRECTX_TOOLKIT_API virtual ~GeometricPrimitive(); // Factory methods. - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCube(_In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateBox(_In_ ID3D11DeviceContext* deviceContext, - const XMFLOAT3& size, - bool rhcoords = true, - bool invertn = false); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateCube(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateBox(_In_ ID3D11DeviceContext* deviceContext, const XMFLOAT3& size, bool rhcoords = true, bool invertn = false); DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateSphere(_In_ ID3D11DeviceContext* deviceContext, float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateGeoSphere(_In_ ID3D11DeviceContext* deviceContext, - float diameter = 1, - size_t tessellation = 3, - bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateGeoSphere(_In_ ID3D11DeviceContext* deviceContext, float diameter = 1, size_t tessellation = 3, bool rhcoords = true); DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCylinder(_In_ ID3D11DeviceContext* deviceContext, float height = 1, float diameter = 1, @@ -90,34 +85,22 @@ namespace DirectX float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTetrahedron( - _In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateOctahedron(_In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateDodecahedron( - _In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateIcosahedron( - _In_ ID3D11DeviceContext* deviceContext, - float size = 1, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateTeapot(_In_ ID3D11DeviceContext* deviceContext, - float size = 1, - size_t tessellation = 8, - bool rhcoords = true); - DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl CreateCustom(_In_ ID3D11DeviceContext* deviceContext, - const VertexCollection& vertices, - const IndexCollection& indices); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateTetrahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateOctahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateDodecahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateIcosahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateTeapot(_In_ ID3D11DeviceContext* deviceContext, float size = 1, size_t tessellation = 8, bool rhcoords = true); + DIRECTX_TOOLKIT_API static std::unique_ptr __cdecl + CreateCustom(_In_ ID3D11DeviceContext* deviceContext, const VertexCollection& vertices, const IndexCollection& indices); // Vertex/Index methods. - DIRECTX_TOOLKIT_API static void __cdecl CreateCube(VertexCollection& vertices, - IndexCollection& indices, - float size = 1, - bool rhcoords = true); + 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, @@ -152,22 +135,14 @@ namespace DirectX 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 + 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, diff --git a/Inc/Model.h b/Inc/Model.h index 3eb99dc7..db280f0e 100644 --- a/Inc/Model.h +++ b/Inc/Model.h @@ -163,9 +163,8 @@ namespace DirectX _In_ std::function setCustomState = nullptr) const; // Create input layout for drawing with a custom effect. - void __cdecl CreateInputLayout(_In_ ID3D11Device* device, - _In_ IEffect* ieffect, - _Outptr_ ID3D11InputLayout** iinputLayout) const; + void __cdecl + CreateInputLayout(_In_ ID3D11Device* device, _In_ IEffect* ieffect, _Outptr_ ID3D11InputLayout** iinputLayout) const; // Change effect used by part and regenerate input layout (be sure to call Model::Modified as well) void __cdecl ModifyEffect(_In_ ID3D11Device* device, _In_ const std::shared_ptr& ieffect, bool isalpha = false); diff --git a/Inc/Mouse.h b/Inc/Mouse.h index d2d2137f..8cda7cac 100644 --- a/Inc/Mouse.h +++ b/Inc/Mouse.h @@ -181,7 +181,7 @@ namespace DirectX DIRECTX_TOOLKIT_API static void __cdecl SetDpi(float dpi); #elif defined(WM_USER) - DIRECTX_TOOLKIT_API void __cdecl SetWindow(HWND window); + DIRECTX_TOOLKIT_API void __cdecl SetWindow(HWND window); DIRECTX_TOOLKIT_API static void __cdecl ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam); #ifdef _GAMING_XBOX diff --git a/Inc/PostProcess.h b/Inc/PostProcess.h index b0b2c21f..89a8e7d8 100644 --- a/Inc/PostProcess.h +++ b/Inc/PostProcess.h @@ -154,10 +154,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. diff --git a/Inc/ScreenGrab.h b/Inc/ScreenGrab.h index 64c8ff45..9250bb71 100644 --- a/Inc/ScreenGrab.h +++ b/Inc/ScreenGrab.h @@ -56,9 +56,8 @@ namespace DirectX { DIRECTX_TOOLKIT_API - HRESULT __cdecl SaveDDSTextureToFile(_In_ ID3D11DeviceContext* pContext, - _In_ ID3D11Resource* pSource, - _In_z_ const wchar_t* fileName) noexcept; + HRESULT __cdecl + SaveDDSTextureToFile(_In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _In_z_ const wchar_t* fileName) noexcept; DIRECTX_TOOLKIT_API HRESULT __cdecl SaveWICTextureToFile(_In_ ID3D11DeviceContext* pContext, diff --git a/Inc/SimpleMath.h b/Inc/SimpleMath.h index 2e64dbe1..6fa6e9b2 100644 --- a/Inc/SimpleMath.h +++ b/Inc/SimpleMath.h @@ -1131,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) @@ -1158,10 +1158,10 @@ namespace DirectX 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; @@ -1388,7 +1388,7 @@ namespace DirectX 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 @@ -1404,7 +1404,7 @@ namespace DirectX 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 diff --git a/Inc/SpriteBatch.h b/Inc/SpriteBatch.h index 7256721b..dfabd220 100644 --- a/Inc/SpriteBatch.h +++ b/Inc/SpriteBatch.h @@ -83,7 +83,7 @@ namespace DirectX _In_opt_ ID3D11RasterizerState* rasterizerState = nullptr, _In_ std::function setCustomShaders = nullptr, FXMMATRIX transformMatrix = MatrixIdentity); - DIRECTX_TOOLKIT_API void __cdecl End(); + DIRECTX_TOOLKIT_API void __cdecl End(); // Draw overloads specifying position, origin and scale as XMFLOAT2. DIRECTX_TOOLKIT_API void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, @@ -145,7 +145,7 @@ namespace DirectX float layerDepth = 0); // Rotation mode to be applied to the sprite transformation - DIRECTX_TOOLKIT_API void __cdecl SetRotation(DXGI_MODE_ROTATION mode); + DIRECTX_TOOLKIT_API void __cdecl SetRotation(DXGI_MODE_ROTATION mode); DIRECTX_TOOLKIT_API DXGI_MODE_ROTATION __cdecl GetRotation() const noexcept; // Set viewport for sprite transformation diff --git a/Inc/SpriteFont.h b/Inc/SpriteFont.h index ed115e19..6edd90be 100644 --- a/Inc/SpriteFont.h +++ b/Inc/SpriteFont.h @@ -154,19 +154,19 @@ namespace DirectX // 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 void __cdecl GetSpriteSheet(ID3D11ShaderResourceView** texture) const; + DIRECTX_TOOLKIT_API void __cdecl GetSpriteSheet(ID3D11ShaderResourceView** texture) const; // Describes a single character glyph. struct Glyph diff --git a/Inc/VertexTypes.h b/Inc/VertexTypes.h index ce365fa2..16660899 100644 --- a/Inc/VertexTypes.h +++ b/Inc/VertexTypes.h @@ -399,7 +399,7 @@ namespace DirectX SetColor(icolor); } - void __cdecl SetColor(XMFLOAT4 const& icolor) noexcept { SetColor(XMLoadFloat4(&icolor)); } + void __cdecl SetColor(XMFLOAT4 const& icolor) noexcept { SetColor(XMLoadFloat4(&icolor)); } void XM_CALLCONV SetColor(FXMVECTOR icolor) noexcept; static constexpr unsigned int InputElementCount = 5; @@ -483,7 +483,7 @@ namespace DirectX void __cdecl SetBlendIndices(XMUINT4 const& iindices) noexcept; - void __cdecl SetBlendWeights(XMFLOAT4 const& iweights) noexcept { SetBlendWeights(XMLoadFloat4(&iweights)); } + void __cdecl SetBlendWeights(XMFLOAT4 const& iweights) noexcept { SetBlendWeights(XMLoadFloat4(&iweights)); } void XM_CALLCONV SetBlendWeights(FXMVECTOR iweights) noexcept; static constexpr unsigned int InputElementCount = 7; diff --git a/Src/DDSTextureLoader.cpp b/Src/DDSTextureLoader.cpp index d56dc0d1..1f93fdd3 100644 --- a/Src/DDSTextureLoader.cpp +++ b/Src/DDSTextureLoader.cpp @@ -972,13 +972,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateDDSTextureFromMemory(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const uint8_t* ddsData, size_t ddsDataSize, @@ -1087,13 +1085,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Devic _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateDDSTextureFromMemoryEx(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const uint8_t* ddsData, size_t ddsDataSize, @@ -1200,13 +1196,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateDDSTextureFromFile(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateDDSTextureFromFile(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const wchar_t* fileName, ID3D11Resource** texture, @@ -1305,13 +1299,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateDDSTextureFromFileEx(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const wchar_t* fileName, size_t maxsize, diff --git a/Src/ScreenGrab.cpp b/Src/ScreenGrab.cpp index eb237d3e..3823a194 100644 --- a/Src/ScreenGrab.cpp +++ b/Src/ScreenGrab.cpp @@ -711,9 +711,8 @@ _Use_decl_annotations_ HRESULT DirectX::SaveWICTextureToFile(ID3D11DeviceContext namespace DirectX { - HRESULT __cdecl SaveDDSTextureToFile(_In_ ID3D11DeviceContext* pContext, - _In_ ID3D11Resource* pSource, - _In_z_ const __wchar_t* fileName) noexcept + HRESULT __cdecl + SaveDDSTextureToFile(_In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _In_z_ const __wchar_t* fileName) noexcept { return SaveDDSTextureToFile(pContext, pSource, reinterpret_cast(fileName)); } diff --git a/Src/WICTextureLoader.cpp b/Src/WICTextureLoader.cpp index dbb4cdbc..91f6efb7 100644 --- a/Src/WICTextureLoader.cpp +++ b/Src/WICTextureLoader.cpp @@ -684,7 +684,7 @@ namespace #if defined(_XBOX_ONE) && defined(_TITLE) ID3D11Texture2D* pStaging = nullptr; CD3D11_TEXTURE2D_DESC - stagingDesc(format, twidth, theight, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, 0); + stagingDesc(format, twidth, theight, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, 0); initData.pSysMem = temp.get(); initData.SysMemPitch = static_cast(rowPitch); initData.SysMemSlicePitch = static_cast(imageSize); @@ -787,13 +787,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateWICTextureFromMemory(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateWICTextureFromMemory(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const uint8_t* wicData, size_t wicDataSize, @@ -910,13 +908,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Devic _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateWICTextureFromMemoryEx(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const uint8_t* wicData, size_t wicDataSize, @@ -1031,13 +1027,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateWICTextureFromFile(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateWICTextureFromFile(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const wchar_t* fileName, ID3D11Resource** texture, @@ -1128,13 +1122,11 @@ _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) - HRESULT - DirectX::CreateWICTextureFromFileEx(ID3D11DeviceX* d3dDevice, - ID3D11DeviceContextX* d3dContext, + HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11DeviceX* d3dDevice, + ID3D11DeviceContextX* d3dContext, #else - HRESULT - DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, - ID3D11DeviceContext* d3dContext, + HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, #endif const wchar_t* fileName, size_t maxsize, diff --git a/Src/pch.h b/Src/pch.h index fe63250b..eb7d928c 100644 --- a/Src/pch.h +++ b/Src/pch.h @@ -11,8 +11,8 @@ #ifdef _MSC_VER // Off by default warnings -#pragma warning( \ - disable : 4619 4616 4061 4265 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4865 4987 5026 5027 5031 5032 5039 5045 5219 5264 26812) +#pragma warning(disable \ + : 4619 4616 4061 4265 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4865 4987 5026 5027 5031 5032 5039 5045 5219 5264 26812) // C4619/4616 #pragma warning warnings // 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 diff --git a/build/Format.ps1 b/build/Format.ps1 index 84ca249d..072ec271 100644 --- a/build/Format.ps1 +++ b/build/Format.ps1 @@ -17,6 +17,17 @@ if (-not $clangFormat) { 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 = (& $clangFormat.Source '--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' From cfc820c79e16a2ca27f38f293af46c458fd9280b Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 13:18:33 -0700 Subject: [PATCH 09/15] Update script --- build/Format.ps1 | 50 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/build/Format.ps1 b/build/Format.ps1 index 072ec271..dbbff2bf 100644 --- a/build/Format.ps1 +++ b/build/Format.ps1 @@ -1,6 +1,36 @@ +<# + +.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/DirectXTK + +#> + [CmdletBinding()] param( - [switch] $Check + [switch] $Check, + [Alias('UseLLVM')] + [switch] $LLVM ) $ErrorActionPreference = 'Stop' @@ -12,14 +42,24 @@ if (-not (Test-Path -LiteralPath $configFile -PathType Leaf)) { throw "clang-format configuration was not found: $configFile" } -$clangFormat = Get-Command clang-format -ErrorAction SilentlyContinue -if (-not $clangFormat) { +$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 = (& $clangFormat.Source '--version' 2>&1 | Out-String).Trim() +$clangFormatVersion = (& $clangFormatPath '--version' 2>&1 | Out-String).Trim() if ($LASTEXITCODE -ne 0) { throw "Unable to determine clang-format version." } @@ -51,7 +91,7 @@ else { } foreach ($sourceFile in $sourceFiles) { - & $clangFormat.Source @arguments $sourceFile.FullName + & $clangFormatPath @arguments $sourceFile.FullName if ($LASTEXITCODE -ne 0) { throw "clang-format failed for $($sourceFile.FullName)." } From 797021e9e44a53e9c724f10a9d31e0dda1353887 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 13:34:03 -0700 Subject: [PATCH 10/15] Editorconfig intenting too strict for clang-format --- .github/linters/.editorconfig-checker.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/linters/.editorconfig-checker.json b/.github/linters/.editorconfig-checker.json index 078fa78e..5f3ecd6a 100644 --- a/.github/linters/.editorconfig-checker.json +++ b/.github/linters/.editorconfig-checker.json @@ -4,5 +4,8 @@ ".git", "LICENSE", "Tests" - ] + ], + "Disable": { + "IndentSize": true + } } From 6aa2c1ef8df49ee263485e4fddaa6346c640e329 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 13:49:23 -0700 Subject: [PATCH 11/15] Preserve some formatting --- XWBTool/xwbtool.cpp | 58 ++++++++++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/XWBTool/xwbtool.cpp b/XWBTool/xwbtool.cpp index d79d687b..7acffb7c 100644 --- a/XWBTool/xwbtool.cpp +++ b/XWBTool/xwbtool.cpp @@ -854,31 +854,39 @@ namespace ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - const SValue g_pOptions[] = { { L"r", OPT_RECURSIVE }, - { L"s", OPT_STREAMING }, - { L"af", OPT_ADVANCED_FORMAT }, - { L"o", OPT_OUTPUTFILE }, - { L"l", OPT_TOLOWER }, - { L"h", OPT_OUTPUTHEADER }, - { L"y", OPT_OVERWRITE }, - { L"c", OPT_COMPACT }, - { L"nc", OPT_NOCOMPACT }, - { L"f", OPT_FRIENDLY_NAMES }, - { L"nologo", OPT_NOLOGO }, - { L"flist", OPT_FILELIST }, - { nullptr, 0 } }; - - const SValue g_pOptionsLong[] = { { L"advanced-format", OPT_ADVANCED_FORMAT }, - { L"compact", OPT_COMPACT }, - { L"file-list", OPT_FILELIST }, - { L"friendly-names", OPT_FRIENDLY_NAMES }, - { L"help", OPT_HELP }, - { L"no-compact", OPT_NOCOMPACT }, - { L"overwrite", OPT_OVERWRITE }, - { L"streaming", OPT_STREAMING }, - { L"to-lowercase", OPT_TOLOWER }, - { L"version", OPT_VERSION }, - { nullptr, 0 } }; + // clang-format off + const SValue g_pOptions[] = + { + { L"r", OPT_RECURSIVE }, + { L"s", OPT_STREAMING }, + { L"af", OPT_ADVANCED_FORMAT }, + { L"o", OPT_OUTPUTFILE }, + { L"l", OPT_TOLOWER }, + { L"h", OPT_OUTPUTHEADER }, + { L"y", OPT_OVERWRITE }, + { L"c", OPT_COMPACT }, + { L"nc", OPT_NOCOMPACT }, + { L"f", OPT_FRIENDLY_NAMES }, + { L"nologo", OPT_NOLOGO }, + { L"flist", OPT_FILELIST }, + { nullptr, 0 } + }; + + const SValue g_pOptionsLong[] = + { + { L"advanced-format", OPT_ADVANCED_FORMAT }, + { L"compact", OPT_COMPACT }, + { L"file-list", OPT_FILELIST }, + { L"friendly-names", OPT_FRIENDLY_NAMES }, + { L"help", OPT_HELP }, + { L"no-compact", OPT_NOCOMPACT }, + { L"overwrite", OPT_OVERWRITE }, + { L"streaming", OPT_STREAMING }, + { L"to-lowercase", OPT_TOLOWER }, + { L"version", OPT_VERSION }, + { nullptr, 0 } + }; + // clang-format on ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// From 87ca5b76ced90327ae22212d5cfc9305cd71971a Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Mon, 7 Sep 2026 14:40:13 -0700 Subject: [PATCH 12/15] Add missing inl files --- Inc/SimpleMath.inl | 857 +++++++++++++++++++++++---------------------- build/Format.ps1 | 2 +- 2 files changed, 447 insertions(+), 412 deletions(-) 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/build/Format.ps1 b/build/Format.ps1 index dbbff2bf..a5f0bc4f 100644 --- a/build/Format.ps1 +++ b/build/Format.ps1 @@ -70,7 +70,7 @@ if ($clangFormatVersion -notmatch "\b$([regex]::Escape($requiredClangFormatVersi $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' + $_.FullName -notmatch '\\(?:\.git|\.vs|build|Tests|vcpkg_installed)\\' -and $_.Extension -in '.c','.cc','.cpp','.cxx','.h','.hh','.hpp','.inl' } if ($sourceFiles.Count -eq 0) { From 7da21e78ae37b656bf1210d6c9c5ede78b933b03 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Tue, 8 Sep 2026 10:23:42 -0700 Subject: [PATCH 13/15] Workaround for some mingw issues --- .github/workflows/mingw.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/mingw.yml b/.github/workflows/mingw.yml index 0f386b12..705e69a0 100644 --- a/.github/workflows/mingw.yml +++ b/.github/workflows/mingw.yml @@ -49,10 +49,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/directxtktest path: Tests @@ -102,6 +102,7 @@ jobs: -DBUILD_SHARED_LIBS=${{ matrix.shared }} -DBUILD_GAMEINPUT=${{ matrix.gameinput }} -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 }} From 248b3cb1392be0d16cbb1bbf11514c24d06a9093 Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Tue, 8 Sep 2026 10:32:51 -0700 Subject: [PATCH 14/15] Update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e85cf023..3d6b0eb6 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 11 C++ code for Win32 desktop applications for Windows 8.1 or later, Xbox One, and Universal Windows Platform (UWP) apps for Windows 10 and Windows 11. -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). From 298f2d73c0a00b0c7703d81bd2fe0df6fb7fd15c Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Tue, 8 Sep 2026 10:53:09 -0700 Subject: [PATCH 15/15] Update readme --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 3d6b0eb6..e50d05a5 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,13 @@ FOR SECURITY ADVISORIES, see [GitHub](https://github.com/microsoft/DirectXTK/sec For a full change history, see [CHANGELOG.md](https://github.com/microsoft/DirectXTK/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 _directxtk_desktop_win10_ and _directxtk_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/directxtk). * The CMake projects require 3.21 or later.