diff --git a/FriedLiver/CompiledShaders/PhongLighting.hlsl.PhongPS.p b/FriedLiver/CompiledShaders/PhongLighting.hlsl.PhongPS.p new file mode 100644 index 00000000..0e153ba1 Binary files /dev/null and b/FriedLiver/CompiledShaders/PhongLighting.hlsl.PhongPS.p differ diff --git a/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadFloatPS.p b/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadFloatPS.p new file mode 100644 index 00000000..32833664 Binary files /dev/null and b/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadFloatPS.p differ diff --git a/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadRGBAPS.p b/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadRGBAPS.p new file mode 100644 index 00000000..31298d26 Binary files /dev/null and b/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadRGBAPS.p differ diff --git a/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadVS.p b/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadVS.p new file mode 100644 index 00000000..7a1a3195 Binary files /dev/null and b/FriedLiver/CompiledShaders/QuadDrawer.hlsl.QuadVS.p differ diff --git a/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.EmptyVS.p b/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.EmptyVS.p new file mode 100644 index 00000000..2bf11c88 Binary files /dev/null and b/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.EmptyVS.p differ diff --git a/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.RGBDRendererGS.p b/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.RGBDRendererGS.p new file mode 100644 index 00000000..c5b96dc5 Binary files /dev/null and b/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.RGBDRendererGS.p differ diff --git a/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.RGBDRendererRawDepthPS.p b/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.RGBDRendererRawDepthPS.p new file mode 100644 index 00000000..f307903c Binary files /dev/null and b/FriedLiver/CompiledShaders/RGBDRenderer.hlsl.RGBDRendererRawDepthPS.p differ diff --git a/FriedLiver/CompiledShaders/RayIntervalSplatting.hlsl.PS.p b/FriedLiver/CompiledShaders/RayIntervalSplatting.hlsl.PS.p new file mode 100644 index 00000000..70c0004f Binary files /dev/null and b/FriedLiver/CompiledShaders/RayIntervalSplatting.hlsl.PS.p differ diff --git a/FriedLiver/CompiledShaders/RayIntervalSplatting.hlsl.VS.p b/FriedLiver/CompiledShaders/RayIntervalSplatting.hlsl.VS.p new file mode 100644 index 00000000..ef2970a2 Binary files /dev/null and b/FriedLiver/CompiledShaders/RayIntervalSplatting.hlsl.VS.p differ diff --git a/FriedLiver/FriedLiver.vcxproj b/FriedLiver/FriedLiver.vcxproj index aaf1ed0c..4db5bef5 100644 --- a/FriedLiver/FriedLiver.vcxproj +++ b/FriedLiver/FriedLiver.vcxproj @@ -1,5 +1,5 @@  - + Debug @@ -15,24 +15,25 @@ Win32Proj DepthWithColor.D3D FriedLiver + 10.0.16299.0 Application true Unicode - v120 + v141 Application false true Unicode - v120 + v141 - + @@ -72,7 +73,7 @@ 4819 - d3d11.lib;d3dcompiler.lib;d3dx11d.lib;d3dx9d.lib;dxerr.lib;dxguid.lib;winmm.lib;comctl32.lib;Shlwapi.lib;cudart.lib;cublas.lib;FreeImage.lib;zlib64.lib;%(AdditionalDependencies) + d3d11.lib;d3dcompiler.lib;dxguid.lib;winmm.lib;comctl32.lib;Shlwapi.lib;cudart.lib;cublas.lib;FreeImage.lib;zlib64.lib;usp10.lib;Imm32.lib;version.lib;%(AdditionalDependencies) Console true ../opencv/lib/;%(AdditionalLibraryDirectories) @@ -106,7 +107,7 @@ /Zm113 %(AdditionalOptions) - d3d11.lib;d3dcompiler.lib;d3dx11.lib;d3dx9.lib;dxerr.lib;dxguid.lib;winmm.lib;comctl32.lib;Shlwapi.lib;cudart.lib;cublas.lib;FreeImage.lib;zlib64.lib;%(AdditionalDependencies) + d3d11.lib;d3dcompiler.lib;dxguid.lib;winmm.lib;comctl32.lib;Shlwapi.lib;cudart.lib;cublas.lib;FreeImage.lib;zlib64.lib;usp10.lib;Imm32.lib;version.lib;%(AdditionalDependencies) true true Console @@ -119,7 +120,7 @@ 64 Include\cutil\inc;$(SolutionDir) - compute_35,sm_35 + compute_30,sm_30 62 true O3 @@ -173,14 +174,20 @@ + + - + + + + + @@ -257,6 +264,14 @@ + + NotUsing + NotUsing + + + NotUsing + NotUsing + NotUsing NotUsing @@ -265,11 +280,15 @@ NotUsing NotUsing - + NotUsing NotUsing - + + NotUsing + NotUsing + + NotUsing NotUsing @@ -281,6 +300,10 @@ NotUsing NotUsing + + NotUsing + NotUsing + NotUsing NotUsing @@ -289,6 +312,10 @@ NotUsing NotUsing + + NotUsing + NotUsing + NotUsing NotUsing @@ -343,7 +370,10 @@ - + + false + Document + 0 @@ -372,6 +402,6 @@ - + \ No newline at end of file diff --git a/FriedLiver/FriedLiver.vcxproj.filters b/FriedLiver/FriedLiver.vcxproj.filters index 92a2e11f..572395e3 100644 --- a/FriedLiver/FriedLiver.vcxproj.filters +++ b/FriedLiver/FriedLiver.vcxproj.filters @@ -6,9 +6,6 @@ DXUT - - DXUT - DXUT @@ -149,6 +146,24 @@ Sensors + + DXUT + + + DXUT + + + DXUT + + + DXUT + + + DXUT + + + DXUT + @@ -159,9 +174,6 @@ DXUT - - DXUT - DXUT @@ -399,6 +411,27 @@ Sensors + + DXUT + + + DXUT + + + DXUT + + + DXUT + + + DXUT + + + DXUT + + + DXUT + diff --git a/FriedLiver/FriedLiver.vcxproj.user b/FriedLiver/FriedLiver.vcxproj.user new file mode 100644 index 00000000..be250787 --- /dev/null +++ b/FriedLiver/FriedLiver.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DDSTextureLoader.cpp b/FriedLiver/Source/DXUT/Core/DDSTextureLoader.cpp new file mode 100644 index 00000000..fad01411 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DDSTextureLoader.cpp @@ -0,0 +1,1825 @@ +//-------------------------------------------------------------------------------------- +// File: DDSTextureLoader.cpp +// +// Functions for loading a DDS texture and creating a Direct3D runtime resource for it +// +// Note these functions are useful as a light-weight runtime loader for DDS files. For +// a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#include "dxut.h" + +#include "DDSTextureLoader.h" + +#include +#include +#include + +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#pragma comment(lib,"dxguid.lib") +#endif + +using namespace DirectX; + +//-------------------------------------------------------------------------------------- +// Macros +//-------------------------------------------------------------------------------------- +#ifndef MAKEFOURCC + #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ + ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \ + ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 )) +#endif /* defined(MAKEFOURCC) */ + +//-------------------------------------------------------------------------------------- +// DDS file structure definitions +// +// See DDS.h in the 'Texconv' sample and the 'DirectXTex' library +//-------------------------------------------------------------------------------------- +#pragma pack(push,1) + +const uint32_t DDS_MAGIC = 0x20534444; // "DDS " + +struct DDS_PIXELFORMAT +{ + uint32_t size; + uint32_t flags; + uint32_t fourCC; + uint32_t RGBBitCount; + uint32_t RBitMask; + uint32_t GBitMask; + uint32_t BBitMask; + uint32_t ABitMask; +}; + +#define DDS_FOURCC 0x00000004 // DDPF_FOURCC +#define DDS_RGB 0x00000040 // DDPF_RGB +#define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE +#define DDS_ALPHA 0x00000002 // DDPF_ALPHA +#define DDS_BUMPDUDV 0x00080000 // DDPF_BUMPDUDV + +#define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH + +#define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT +#define DDS_WIDTH 0x00000004 // DDSD_WIDTH + +#define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX +#define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX +#define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY +#define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY +#define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ +#define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ + +#define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\ + DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\ + DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ ) + +#define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP + +enum DDS_MISC_FLAGS2 +{ + DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L, +}; + +struct DDS_HEADER +{ + uint32_t size; + uint32_t flags; + uint32_t height; + uint32_t width; + uint32_t pitchOrLinearSize; + uint32_t depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags + uint32_t mipMapCount; + uint32_t reserved1[11]; + DDS_PIXELFORMAT ddspf; + uint32_t caps; + uint32_t caps2; + uint32_t caps3; + uint32_t caps4; + uint32_t reserved2; +}; + +struct DDS_HEADER_DXT10 +{ + DXGI_FORMAT dxgiFormat; + uint32_t resourceDimension; + uint32_t miscFlag; // see D3D11_RESOURCE_MISC_FLAG + uint32_t arraySize; + uint32_t miscFlags2; +}; + +#pragma pack(pop) + +//-------------------------------------------------------------------------------------- +namespace +{ + struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; + + typedef std::unique_ptr ScopedHandle; + + inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; } + + template + inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_ const char (&name)[TNameLength]) + { + #if defined(_DEBUG) || defined(PROFILE) + resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name); + #else + UNREFERENCED_PARAMETER(resource); + UNREFERENCED_PARAMETER(name); + #endif + } + + //-------------------------------------------------------------------------------------- + HRESULT LoadTextureDataFromFile( + _In_z_ const wchar_t* fileName, + std::unique_ptr& ddsData, + const DDS_HEADER** header, + const uint8_t** bitData, + size_t* bitSize) + { + if (!header || !bitData || !bitSize) + { + return E_POINTER; + } + + // open the file +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) + ScopedHandle hFile(safe_handle(CreateFile2(fileName, + GENERIC_READ, + FILE_SHARE_READ, + OPEN_EXISTING, + nullptr))); +#else + ScopedHandle hFile(safe_handle(CreateFileW(fileName, + GENERIC_READ, + FILE_SHARE_READ, + nullptr, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + nullptr))); +#endif + + if (!hFile) + { + return HRESULT_FROM_WIN32(GetLastError()); + } + + // Get the file size + FILE_STANDARD_INFO fileInfo; + if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo))) + { + return HRESULT_FROM_WIN32(GetLastError()); + } + + // File is too big for 32-bit allocation, so reject read + if (fileInfo.EndOfFile.HighPart > 0) + { + return E_FAIL; + } + + // Need at least enough data to fill the header and magic number to be a valid DDS + if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t))) + { + return E_FAIL; + } + + // create enough space for the file data + ddsData.reset(new (std::nothrow) uint8_t[fileInfo.EndOfFile.LowPart]); + if (!ddsData) + { + return E_OUTOFMEMORY; + } + + // read the data in + DWORD BytesRead = 0; + if (!ReadFile(hFile.get(), + ddsData.get(), + fileInfo.EndOfFile.LowPart, + &BytesRead, + nullptr + )) + { + return HRESULT_FROM_WIN32(GetLastError()); + } + + if (BytesRead < fileInfo.EndOfFile.LowPart) + { + return E_FAIL; + } + + // DDS files always start with the same magic number ("DDS ") + uint32_t dwMagicNumber = *reinterpret_cast(ddsData.get()); + if (dwMagicNumber != DDS_MAGIC) + { + return E_FAIL; + } + + 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)) + { + return E_FAIL; + } + + // Check for DX10 extension + bool bDXT10Header = false; + 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 < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) + { + return E_FAIL; + } + + bDXT10Header = true; + } + + // setup the pointers in the process request + *header = hdr; + ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER) + + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); + *bitData = ddsData.get() + offset; + *bitSize = fileInfo.EndOfFile.LowPart - offset; + + return S_OK; + } + + + //-------------------------------------------------------------------------------------- + // Return the BPP for a particular format + //-------------------------------------------------------------------------------------- + size_t BitsPerPixel(_In_ DXGI_FORMAT fmt) + { + switch (fmt) + { + 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_R32G32B32_TYPELESS: + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: + return 96; + + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_TYPELESS: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + case DXGI_FORMAT_R32G8X24_TYPELESS: + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: + case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: + case DXGI_FORMAT_Y416: + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + return 64; + + case DXGI_FORMAT_R10G10B10A2_TYPELESS: + case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_TYPELESS: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_R16G16_TYPELESS: + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_D32_FLOAT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + case DXGI_FORMAT_R24G8_TYPELESS: + case DXGI_FORMAT_D24_UNORM_S8_UINT: + case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: + case DXGI_FORMAT_X24_TYPELESS_G8_UINT: + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + case DXGI_FORMAT_AYUV: + case DXGI_FORMAT_Y410: + case DXGI_FORMAT_YUY2: + return 32; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + return 24; + + case DXGI_FORMAT_R8G8_TYPELESS: + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8_SINT: + case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_D16_UNORM: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16_SINT: + case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: + case DXGI_FORMAT_A8P8: + case DXGI_FORMAT_B4G4R4A4_UNORM: + return 16; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + case DXGI_FORMAT_NV11: + return 12; + + case DXGI_FORMAT_R8_TYPELESS: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_A8_UNORM: + case DXGI_FORMAT_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + return 8; + + 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_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return 8; + + default: + return 0; + } + } + + + //-------------------------------------------------------------------------------------- + // Get surface information for a particular format + //-------------------------------------------------------------------------------------- + void GetSurfaceInfo( + _In_ size_t width, + _In_ size_t height, + _In_ DXGI_FORMAT fmt, + size_t* outNumBytes, + _Out_opt_ size_t* outRowBytes, + _Out_opt_ size_t* outNumRows) + { + size_t numBytes = 0; + size_t rowBytes = 0; + size_t numRows = 0; + + bool bc = false; + bool packed = false; + bool planar = false; + size_t bpe = 0; + switch (fmt) + { + 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: + bc = true; + bpe = 8; + break; + + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + bc = true; + bpe = 16; + break; + + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_YUY2: + packed = true; + bpe = 4; + break; + + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + packed = true; + bpe = 8; + break; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + planar = true; + bpe = 2; + break; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + planar = true; + bpe = 4; + break; + } + + if (bc) + { + size_t numBlocksWide = 0; + if (width > 0) + { + numBlocksWide = std::max(1, (width + 3) / 4); + } + size_t numBlocksHigh = 0; + if (height > 0) + { + numBlocksHigh = std::max(1, (height + 3) / 4); + } + rowBytes = numBlocksWide * bpe; + numRows = numBlocksHigh; + numBytes = rowBytes * numBlocksHigh; + } + else if (packed) + { + rowBytes = ((width + 1) >> 1) * bpe; + numRows = height; + numBytes = rowBytes * height; + } + else if (fmt == DXGI_FORMAT_NV11) + { + rowBytes = ((width + 3) >> 2) * 4; + numRows = height * 2; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data + numBytes = rowBytes * numRows; + } + else if (planar) + { + rowBytes = ((width + 1) >> 1) * bpe; + numBytes = (rowBytes * height) + ((rowBytes * height + 1) >> 1); + numRows = height + ((height + 1) >> 1); + } + else + { + size_t bpp = BitsPerPixel(fmt); + rowBytes = (width * bpp + 7) / 8; // round up to nearest byte + numRows = height; + numBytes = rowBytes * height; + } + + if (outNumBytes) + { + *outNumBytes = numBytes; + } + if (outRowBytes) + { + *outRowBytes = rowBytes; + } + if (outNumRows) + { + *outNumRows = numRows; + } + } + + + //-------------------------------------------------------------------------------------- + #define ISBITMASK( r,g,b,a ) ( ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a ) + + DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf) + { + if (ddpf.flags & DDS_RGB) + { + // Note that sRGB formats are written using the "DX10" extended header + + switch (ddpf.RGBBitCount) + { + case 32: + if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) + { + return DXGI_FORMAT_R8G8B8A8_UNORM; + } + + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) + { + return DXGI_FORMAT_B8G8R8A8_UNORM; + } + + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000)) + { + return DXGI_FORMAT_B8G8R8X8_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0x00000000) aka D3DFMT_X8B8G8R8 + + // Note that many common DDS reader/writers (including D3DX) swap the + // the RED/BLUE masks for 10:10:10:2 formats. We assume + // below that the 'backwards' header mask is being used since it is most + // likely written by D3DX. The more robust solution is to use the 'DX10' + // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly + + // For 'correct' writers, this should be 0x000003ff,0x000ffc00,0x3ff00000 for RGB data + if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000)) + { + return DXGI_FORMAT_R10G10B10A2_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x000003ff,0x000ffc00,0x3ff00000,0xc0000000) aka D3DFMT_A2R10G10B10 + + if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R16G16_UNORM; + } + + if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000)) + { + // Only 32-bit color channel format in D3D9 was R32F + return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114 + } + break; + + case 24: + // No 24bpp DXGI formats aka D3DFMT_R8G8B8 + break; + + case 16: + if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000)) + { + return DXGI_FORMAT_B5G5R5A1_UNORM; + } + if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000)) + { + return DXGI_FORMAT_B5G6R5_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0x0000) aka D3DFMT_X1R5G5B5 + + if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) + { + return DXGI_FORMAT_B4G4R4A4_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0x0000) aka D3DFMT_X4R4G4B4 + + // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc. + break; + } + } + else if (ddpf.flags & DDS_LUMINANCE) + { + if (8 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension + } + + // No DXGI format maps to ISBITMASK(0x0f,0x00,0x00,0xf0) aka D3DFMT_A4L4 + + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) + { + return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16 + } + } + + if (16 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension + } + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) + { + return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension + } + } + } + else if (ddpf.flags & DDS_ALPHA) + { + if (8 == ddpf.RGBBitCount) + { + return DXGI_FORMAT_A8_UNORM; + } + } + else if (ddpf.flags & DDS_BUMPDUDV) + { + if (16 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x00ff, 0xff00, 0x0000, 0x0000)) + { + return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension + } + } + + if (32 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) + { + return DXGI_FORMAT_R8G8B8A8_SNORM; // D3DX10/11 writes this out as DX10 extension + } + if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R16G16_SNORM; // D3DX10/11 writes this out as DX10 extension + } + + // No DXGI format maps to ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000) aka D3DFMT_A2W10V10U10 + } + } + else if (ddpf.flags & DDS_FOURCC) + { + if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC) + { + return DXGI_FORMAT_BC1_UNORM; + } + if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC) + { + return DXGI_FORMAT_BC2_UNORM; + } + if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC) + { + return DXGI_FORMAT_BC3_UNORM; + } + + // While pre-multiplied alpha isn't directly supported by the DXGI formats, + // they are basically the same as these BC formats so they can be mapped + if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC) + { + return DXGI_FORMAT_BC2_UNORM; + } + if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC) + { + return DXGI_FORMAT_BC3_UNORM; + } + + if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC) + { + return DXGI_FORMAT_BC4_UNORM; + } + if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC) + { + return DXGI_FORMAT_BC4_UNORM; + } + if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC) + { + return DXGI_FORMAT_BC4_SNORM; + } + + if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC) + { + return DXGI_FORMAT_BC5_UNORM; + } + if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC) + { + return DXGI_FORMAT_BC5_UNORM; + } + if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC) + { + return DXGI_FORMAT_BC5_SNORM; + } + + // BC6H and BC7 are written using the "DX10" extended header + + if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC) + { + return DXGI_FORMAT_R8G8_B8G8_UNORM; + } + if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC) + { + return DXGI_FORMAT_G8R8_G8B8_UNORM; + } + + if (MAKEFOURCC('Y', 'U', 'Y', '2') == ddpf.fourCC) + { + return DXGI_FORMAT_YUY2; + } + + // Check for D3DFORMAT enums being set here + switch (ddpf.fourCC) + { + case 36: // D3DFMT_A16B16G16R16 + return DXGI_FORMAT_R16G16B16A16_UNORM; + + case 110: // D3DFMT_Q16W16V16U16 + return DXGI_FORMAT_R16G16B16A16_SNORM; + + case 111: // D3DFMT_R16F + return DXGI_FORMAT_R16_FLOAT; + + case 112: // D3DFMT_G16R16F + return DXGI_FORMAT_R16G16_FLOAT; + + case 113: // D3DFMT_A16B16G16R16F + return DXGI_FORMAT_R16G16B16A16_FLOAT; + + case 114: // D3DFMT_R32F + return DXGI_FORMAT_R32_FLOAT; + + case 115: // D3DFMT_G32R32F + return DXGI_FORMAT_R32G32_FLOAT; + + case 116: // D3DFMT_A32B32G32R32F + return DXGI_FORMAT_R32G32B32A32_FLOAT; + } + } + + return DXGI_FORMAT_UNKNOWN; + } + + + //-------------------------------------------------------------------------------------- + DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format) + { + switch (format) + { + 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_BC2_UNORM: + return DXGI_FORMAT_BC2_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_B8G8R8X8_UNORM: + return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + + case DXGI_FORMAT_BC7_UNORM: + return DXGI_FORMAT_BC7_UNORM_SRGB; + + default: + return format; + } + } + + + //-------------------------------------------------------------------------------------- + HRESULT FillInitData( + _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_ size_t maxsize, + _In_ size_t bitSize, + _In_reads_bytes_(bitSize) const uint8_t* bitData, + _Out_ size_t& twidth, + _Out_ size_t& theight, + _Out_ size_t& tdepth, + _Out_ size_t& skipMip, + _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData) + { + if (!bitData || !initData) + { + return E_POINTER; + } + + skipMip = 0; + twidth = 0; + theight = 0; + tdepth = 0; + + size_t NumBytes = 0; + size_t RowBytes = 0; + const uint8_t* pSrcBits = bitData; + const uint8_t* pEndBits = bitData + bitSize; + + size_t index = 0; + for (size_t j = 0; j < arraySize; j++) + { + size_t w = width; + size_t h = height; + size_t d = depth; + for (size_t i = 0; i < mipCount; i++) + { + GetSurfaceInfo(w, + h, + format, + &NumBytes, + &RowBytes, + nullptr + ); + + if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize)) + { + if (!twidth) + { + twidth = w; + theight = h; + tdepth = d; + } + + assert(index < mipCount * arraySize); + _Analysis_assume_(index < mipCount * arraySize); + initData[index].pSysMem = (const void*)pSrcBits; + initData[index].SysMemPitch = static_cast(RowBytes); + initData[index].SysMemSlicePitch = static_cast(NumBytes); + ++index; + } + else if (!j) + { + // Count number of skipped mipmaps (first item only) + ++skipMip; + } + + if (pSrcBits + (NumBytes*d) > pEndBits) + { + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + pSrcBits += NumBytes * d; + + w = w >> 1; + h = h >> 1; + d = d >> 1; + if (w == 0) + { + w = 1; + } + if (h == 0) + { + h = 1; + } + if (d == 0) + { + d = 1; + } + } + } + + return (index > 0) ? S_OK : E_FAIL; + } + + + //-------------------------------------------------------------------------------------- + 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_ bool forceSRGB, + _In_ bool isCubeMap, + _In_reads_opt_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) + { + if (!d3dDevice) + return E_POINTER; + + HRESULT hr = E_FAIL; + + if (forceSRGB) + { + format = MakeSRGB(format); + } + + switch (resDim) + { + 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 & ~D3D11_RESOURCE_MISC_TEXTURECUBE; + + ID3D11Texture1D* tex = nullptr; + hr = d3dDevice->CreateTexture1D(&desc, + initData, + &tex + ); + if (SUCCEEDED(hr) && tex != 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 = (!mipCount) ? -1 : desc.MipLevels; + SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); + } + else + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; + SRVDesc.Texture1D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, + &SRVDesc, + textureView + ); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + 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 & ~D3D11_RESOURCE_MISC_TEXTURECUBE; + } + + ID3D11Texture2D* tex = nullptr; + hr = d3dDevice->CreateTexture2D(&desc, + initData, + &tex + ); + if (SUCCEEDED(hr) && tex != 0) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; + + if (isCubeMap) + { + if (arraySize > 6) + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; + SRVDesc.TextureCubeArray.MipLevels = (!mipCount) ? -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) ? -1 : desc.MipLevels; + } + } + else if (arraySize > 1) + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; + SRVDesc.Texture2DArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); + } + else + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, + &SRVDesc, + textureView + ); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + } + + if (texture != 0) + { + *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 & ~D3D11_RESOURCE_MISC_TEXTURECUBE; + + ID3D11Texture3D* tex = nullptr; + hr = d3dDevice->CreateTexture3D(&desc, + initData, + &tex + ); + if (SUCCEEDED(hr) && tex != 0) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; + + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; + SRVDesc.Texture3D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + + hr = d3dDevice->CreateShaderResourceView(tex, + &SRVDesc, + textureView + ); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "DDSTextureLoader"); + tex->Release(); + } + } + } + break; + } + + return hr; + } + + + //-------------------------------------------------------------------------------------- + HRESULT CreateTextureFromDDS( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) + { + HRESULT hr = S_OK; + + 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; + + size_t mipCount = header->mipMapCount; + if (0 == mipCount) + { + mipCount = 1; + } + + if ((header->ddspf.flags & DDS_FOURCC) && + (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) + { + auto d3d10ext = reinterpret_cast((const char*)header + sizeof(DDS_HEADER)); + + arraySize = d3d10ext->arraySize; + if (arraySize == 0) + { + return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + } + + switch (d3d10ext->dxgiFormat) + { + case DXGI_FORMAT_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + case DXGI_FORMAT_A8P8: + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + + default: + if (BitsPerPixel(d3d10ext->dxgiFormat) == 0) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + } + + format = d3d10ext->dxgiFormat; + + switch (d3d10ext->resourceDimension) + { + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + // D3DX writes 1D textures with a fixed Height of 1 + if ((header->flags & DDS_HEIGHT) && height != 1) + { + return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + } + height = depth = 1; + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: + if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE) + { + arraySize *= 6; + isCubeMap = true; + } + depth = 1; + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: + if (!(header->flags & DDS_HEADER_FLAGS_VOLUME)) + { + return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + } + + if (arraySize > 1) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + break; + + default: + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + resDim = d3d10ext->resourceDimension; + } + else + { + format = GetDXGIFormat(header->ddspf); + + if (format == DXGI_FORMAT_UNKNOWN) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + if (header->flags & DDS_HEADER_FLAGS_VOLUME) + { + resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D; + } + else + { + if (header->caps2 & DDS_CUBEMAP) + { + // We require all six faces to be defined + if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + arraySize = 6; + isCubeMap = true; + } + + depth = 1; + resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D; + + // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture + } + + assert(BitsPerPixel(format) != 0); + } + + // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements) + if (mipCount > D3D11_REQ_MIP_LEVELS) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + switch (resDim) + { + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || + (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: + 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)) + { + 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)) + { + 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)) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + break; + + default: + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + bool autogen = false; + if (mipCount == 1 && d3dContext != 0 && textureView != 0) // Must have context and shader-view to auto generate mipmaps + { + // See if format is supported for auto-gen mipmaps (varies by feature level) + UINT fmtSupport = 0; + 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)) + { + autogen = true; + } + } + } + + if (autogen) + { + // Create texture with auto-generated mipmaps + ID3D11Resource* tex = nullptr; + hr = CreateD3DResources(d3dDevice, resDim, width, height, depth, 0, arraySize, + format, usage, + bindFlags | D3D11_BIND_RENDER_TARGET, + cpuAccessFlags, + miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS, forceSRGB, + isCubeMap, nullptr, &tex, textureView); + if (SUCCEEDED(hr)) + { + size_t numBytes = 0; + size_t rowBytes = 0; + GetSurfaceInfo(width, height, format, &numBytes, &rowBytes, nullptr); + + if (numBytes > bitSize) + { + (*textureView)->Release(); + *textureView = nullptr; + tex->Release(); + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + D3D11_SHADER_RESOURCE_VIEW_DESC desc; + (*textureView)->GetDesc(&desc); + + UINT mipLevels = 1; + + 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; + default: + (*textureView)->Release(); + *textureView = nullptr; + tex->Release(); + return E_UNEXPECTED; + } + + if (arraySize > 1) + { + const uint8_t* pSrcBits = bitData; + const uint8_t* pEndBits = bitData + bitSize; + for (UINT item = 0; item < arraySize; ++item) + { + if ((pSrcBits + numBytes) > pEndBits) + { + (*textureView)->Release(); + *textureView = nullptr; + tex->Release(); + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + UINT res = D3D11CalcSubresource(0, item, mipLevels); + d3dContext->UpdateSubresource(tex, res, nullptr, pSrcBits, static_cast(rowBytes), static_cast(numBytes)); + pSrcBits += numBytes; + } + } + else + { + d3dContext->UpdateSubresource(tex, 0, nullptr, bitData, static_cast(rowBytes), static_cast(numBytes)); + } + + d3dContext->GenerateMips(*textureView); + + if (texture) + { + *texture = tex; + } + else + { + tex->Release(); + } + } + } + else + { + // Create the texture + std::unique_ptr initData(new (std::nothrow) D3D11_SUBRESOURCE_DATA[mipCount * arraySize]); + if (!initData) + { + return E_OUTOFMEMORY; + } + + size_t skipMip = 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()); + + if (SUCCEEDED(hr)) + { + hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, + format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + isCubeMap, initData.get(), texture, textureView); + + if (FAILED(hr) && !maxsize && (mipCount > 1)) + { + // Retry with a maxsize determined by feature level + switch (d3dDevice->GetFeatureLevel()) + { + case D3D_FEATURE_LEVEL_9_1: + case D3D_FEATURE_LEVEL_9_2: + if (isCubeMap) + { + maxsize = 512 /*D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION*/; + } + else + { + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) + ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ + : 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + } + break; + + case D3D_FEATURE_LEVEL_9_3: + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) + ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ + : 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1 + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) + ? 2048 /*D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ + : 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + } + + 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, + format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + isCubeMap, initData.get(), texture, textureView); + } + } + } + } + + return hr; + } + + + //-------------------------------------------------------------------------------------- + DDS_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header) + { + if (header->ddspf.flags & DDS_FOURCC) + { + if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC) + { + auto d3d10ext = reinterpret_cast((const char*)header + sizeof(DDS_HEADER)); + 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; + } + } + else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC) + || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC)) + { + return DDS_ALPHA_MODE_PREMULTIPLIED; + } + } + + return DDS_ALPHA_MODE_UNKNOWN; + } +} // 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) +{ + return CreateDDSTextureFromMemoryEx(d3dDevice, nullptr, ddsData, ddsDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromMemoryEx(d3dDevice, d3dContext, ddsData, ddsDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + 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, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromMemoryEx(d3dDevice, nullptr, ddsData, ddsDataSize, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + if (alphaMode) + { + *alphaMode = DDS_ALPHA_MODE_UNKNOWN; + } + + if (!d3dDevice || !ddsData || (!texture && !textureView)) + { + return E_INVALIDARG; + } + + // Validate DDS file in memory + if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER))) + { + return E_FAIL; + } + + uint32_t dwMagicNumber = *(const uint32_t*)(ddsData); + if (dwMagicNumber != DDS_MAGIC) + { + return E_FAIL; + } + + 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)) + { + return E_FAIL; + } + + // Check for DX10 extension + bool bDXT10Header = false; + if ((header->ddspf.flags & DDS_FOURCC) && + (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) + { + // Must be long enough for both headers and magic value + if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) + { + return E_FAIL; + } + + bDXT10Header = true; + } + + ptrdiff_t offset = sizeof(uint32_t) + + sizeof(DDS_HEADER) + + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); + + HRESULT hr = CreateTextureFromDDS(d3dDevice, d3dContext, header, + ddsData + offset, ddsDataSize - offset, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView); + if (SUCCEEDED(hr)) + { + if (texture != 0 && *texture != 0) + { + SetDebugObjectName(*texture, "DDSTextureLoader"); + } + + if (textureView != 0 && *textureView != 0) + { + SetDebugObjectName(*textureView, "DDSTextureLoader"); + } + + if (alphaMode) + *alphaMode = GetAlphaMode(header); + } + + return hr; +} + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromFileEx(d3dDevice, d3dContext, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + 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, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + if (alphaMode) + { + *alphaMode = DDS_ALPHA_MODE_UNKNOWN; + } + + if (!d3dDevice || !fileName || (!texture && !textureView)) + { + return E_INVALIDARG; + } + + 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 + ); + if (FAILED(hr)) + { + return hr; + } + + hr = CreateTextureFromDDS(d3dDevice, d3dContext, header, + bitData, bitSize, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView); + + if (SUCCEEDED(hr)) + { +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) + if (texture != 0 || textureView != 0) + { + CHAR strFileA[MAX_PATH]; + int result = WideCharToMultiByte(CP_ACP, + WC_NO_BEST_FIT_CHARS, + fileName, + -1, + strFileA, + MAX_PATH, + nullptr, + FALSE + ); + if (result > 0) + { + const CHAR* pstrName = strrchr(strFileA, '\\'); + if (!pstrName) + { + pstrName = strFileA; + } + else + { + pstrName++; + } + + if (texture != 0 && *texture != 0) + { + (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + + if (textureView != 0 && *textureView != 0) + { + (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + } + } +#endif + + if (alphaMode) + *alphaMode = GetAlphaMode(header); + } + + return hr; +} diff --git a/FriedLiver/Source/DXUT/Core/DDSTextureLoader.h b/FriedLiver/Source/DXUT/Core/DDSTextureLoader.h new file mode 100644 index 00000000..0b5cb19d --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DDSTextureLoader.h @@ -0,0 +1,129 @@ +//-------------------------------------------------------------------------------------- +// File: DDSTextureLoader.h +// +// Functions for loading a DDS texture and creating a Direct3D runtime resource for it +// +// Note these functions are useful as a light-weight runtime loader for DDS files. For +// a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#pragma once + +#include +#include + + +namespace DirectX +{ + enum DDS_ALPHA_MODE + { + 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, + }; + + // Standard version + HRESULT 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); + + HRESULT 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); + + // Standard version with optional auto-gen mipmap support + HRESULT CreateDDSTextureFromMemory( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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); + + HRESULT CreateDDSTextureFromFile( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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); + + // Extended version + HRESULT 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_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + HRESULT 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_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + // Extended version with optional auto-gen mipmap support + HRESULT CreateDDSTextureFromMemoryEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + HRESULT CreateDDSTextureFromFileEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); +} \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT.cpp b/FriedLiver/Source/DXUT/Core/DXUT.cpp index d57eef55..7daa85b5 100644 --- a/FriedLiver/Source/DXUT/Core/DXUT.cpp +++ b/FriedLiver/Source/DXUT/Core/DXUT.cpp @@ -2,22 +2,20 @@ // File: DXUT.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" + +#ifndef NDEBUG +#include +#endif + #define DXUT_MIN_WINDOW_SIZE_X 200 #define DXUT_MIN_WINDOW_SIZE_Y 200 #define DXUT_COUNTER_STAT_LENGTH 2048 -#undef min // use __min instead inside this source file -#undef max // use __max instead inside this source file -#ifndef ARRAYSIZE -extern "C++" // templates cannot be declared to have 'C' linkage -template -char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N]; - -#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A))) -#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A) -#endif //-------------------------------------------------------------------------------------- // Thread safety @@ -32,8 +30,10 @@ bool g_bThreadSafe = true; class DXUTLock { public: - inline DXUTLock() { if( g_bThreadSafe ) EnterCriticalSection( &g_cs ); } - inline ~DXUTLock() { if( g_bThreadSafe ) LeaveCriticalSection( &g_cs ); } +#pragma prefast( suppress:26166, "g_bThreadSafe controls behavior" ) + inline _Acquires_lock_(g_cs) DXUTLock() noexcept { if( g_bThreadSafe ) EnterCriticalSection( &g_cs ); } +#pragma prefast( suppress:26165, "g_bThreadSafe controls behavior" ) + inline _Releases_lock_(g_cs) ~DXUTLock() { if( g_bThreadSafe ) LeaveCriticalSection( &g_cs ); } }; //-------------------------------------------------------------------------------------- @@ -47,6 +47,7 @@ class DXUTLock #define GETP_ACCESSOR( x, y ) inline x* Get##y() { DXUTLock l; return &m_state.m_##y; }; #define GETP_SETP_ACCESSOR( x, y ) SETP_ACCESSOR( x, y ) GETP_ACCESSOR( x, y ) + //-------------------------------------------------------------------------------------- // Stores timer callback info //-------------------------------------------------------------------------------------- @@ -60,6 +61,7 @@ struct DXUT_TIMER UINT nID; }; + //-------------------------------------------------------------------------------------- // Stores DXUT state and data access is done with thread safety (if g_bThreadSafe==true) //-------------------------------------------------------------------------------------- @@ -68,16 +70,9 @@ class DXUTState protected: struct STATE { - // D3D9 specific - IDirect3D9* m_D3D9; // the main D3D9 object - IDirect3DDevice9* m_D3D9Device; // the D3D9 rendering device DXUTDeviceSettings* m_CurrentDeviceSettings; // current device settings - D3DSURFACE_DESC m_BackBufferSurfaceDesc9; // D3D9 back buffer surface description - D3DCAPS9 m_Caps; // D3D caps for current device - - // D3D11 specific - IDXGIFactory1* m_DXGIFactory; // DXGI Factory object - IDXGIAdapter1* m_DXGIAdapter; // The DXGI adapter object for the D3D11 device + IDXGIFactory1* m_DXGIFactory; // DXGI Factory object + IDXGIAdapter1* m_DXGIAdapter; // The DXGI adapter object for the D3D11 device IDXGIOutput** m_DXGIOutputArray; // The array of output obj for the D3D11 adapter obj UINT m_DXGIOutputArraySize; // Number of elements in m_D3D11OutputArray IDXGISwapChain* m_DXGISwapChain; // the D3D11 swapchain @@ -86,15 +81,34 @@ class DXUTState bool m_DoNotStoreBufferSize; // Do not store the buffer size on WM_SIZE messages // D3D11 specific - bool m_D3D11Available; // if true, then D3D11 is available - ID3D11Device* m_D3D11Device; // the D3D11 rendering device + ID3D11Device* m_D3D11Device; // the D3D11 rendering device ID3D11DeviceContext* m_D3D11DeviceContext; // the D3D11 immediate device context - D3D_FEATURE_LEVEL m_D3D11FeatureLevel; // the D3D11 feature level that this device supports + D3D_FEATURE_LEVEL m_D3D11FeatureLevel; // the D3D11 feature level that this device supports ID3D11Texture2D* m_D3D11DepthStencil; // the D3D11 depth stencil texture (optional) ID3D11DepthStencilView* m_D3D11DepthStencilView; // the D3D11 depth stencil view (optional) ID3D11RenderTargetView* m_D3D11RenderTargetView; // the D3D11 render target view ID3D11RasterizerState* m_D3D11RasterizerState; // the D3D11 Rasterizer state + // D3D11.1 specific + ID3D11Device1* m_D3D11Device1; // the D3D11.1 rendering device + ID3D11DeviceContext1* m_D3D11DeviceContext1; // the D3D11.1 immediate device context + + // D3D11.2 specific + ID3D11Device2* m_D3D11Device2; // the D3D11.2 rendering device + ID3D11DeviceContext2* m_D3D11DeviceContext2; // the D3D11.2 immediate device context + +#ifdef USE_DIRECT3D11_3 + // D3D11.3 specific + ID3D11Device3* m_D3D11Device3; // the D3D11.3 rendering device + ID3D11DeviceContext3* m_D3D11DeviceContext3; // the D3D11.3 immediate device context +#endif + +#ifdef USE_DIRECT3D11_4 + // D3D11.4 specific + ID3D11Device4* m_D3D11Device4; // the D3D11.4 rendering device + ID3D11DeviceContext4* m_D3D11DeviceContext4; // the D3D11.4 immediate device context +#endif + // General HWND m_HWNDFocus; // the main app focus window HWND m_HWNDDeviceFullScreen; // the main app device window in fullscreen mode @@ -132,10 +146,6 @@ class DXUTState TOGGLEKEYS m_StartupToggleKeys; // ToggleKey settings upon startup so they can be restored later FILTERKEYS m_StartupFilterKeys; // FilterKey settings upon startup so they can be restored later - bool m_AppSupportsD3D9Override; // true if app sets via DXUTSetD3DVersionSupport() - bool m_AppSupportsD3D11Override; // true if app sets via DXUTSetD3DVersionSupport() - bool m_UseD3DVersionOverride; // true if the app ever calls DXUTSetD3DVersionSupport() - bool m_HandleEscape; // if true, then DXUT will handle escape to quit bool m_HandleAltEnter; // if true, then DXUT will handle alt-enter to toggle fullscreen bool m_HandlePause; // if true, then DXUT will handle pause to toggle time pausing @@ -152,11 +162,11 @@ class DXUTState bool m_DXUTInited; // if true, then DXUTInit() has succeeded bool m_WindowCreated; // if true, then DXUTCreateWindow() or DXUTSetWindow() has succeeded - bool m_DeviceCreated; // if true, then DXUTCreateDevice() or DXUTSetD3D*Device() has succeeded + bool m_DeviceCreated; // if true, then DXUTCreateDevice() has succeeded bool m_DXUTInitCalled; // if true, then DXUTInit() was called bool m_WindowCreateCalled; // if true, then DXUTCreateWindow() or DXUTSetWindow() was called - bool m_DeviceCreateCalled; // if true, then DXUTCreateDevice() or DXUTSetD3D*Device() was called + bool m_DeviceCreateCalled; // if true, then DXUTCreateDevice() was called bool m_DeviceObjectsCreated; // if true, then DeviceCreated callback has been called (if non-NULL) bool m_DeviceObjectsReset; // if true, then DeviceReset callback has been called (if non-NULL) @@ -179,7 +189,6 @@ class DXUTState bool m_SaveScreenShot; // command line save screen shot bool m_ExitAfterScreenShot; // command line exit after screen shot - int m_OverrideForceAPI; // if != -1, then override to use this Direct3D API version int m_OverrideAdapterOrdinal; // if != -1, then override to use this adapter ordinal bool m_OverrideWindowed; // if true, then force to start windowed int m_OverrideOutput; // if != -1, then override to use the particular output on the adapter @@ -190,14 +199,14 @@ class DXUTState int m_OverrideHeight; // if != 0, then override to this height bool m_OverrideForceHAL; // if true, then force to HAL device (failing if one doesn't exist) bool m_OverrideForceREF; // if true, then force to REF device (failing if one doesn't exist) + bool m_OverrideForceWARP; // if true, then force to WARP device (failing if one doesn't exist) bool m_OverrideConstantFrameTime; // if true, then force to constant frame time float m_OverrideConstantTimePerFrame; // the constant time per frame in seconds if m_OverrideConstantFrameTime==true int m_OverrideQuitAfterFrame; // if != 0, then it will force the app to quit after that frame int m_OverrideForceVsync; // if == 0, then it will force the app to use D3DPRESENT_INTERVAL_IMMEDIATE, if == 1 force use of D3DPRESENT_INTERVAL_DEFAULT - bool m_OverrideRelaunchMCE; // if true, then force relaunch of MCE at exit bool m_AppCalledWasKeyPressed; // true if the app ever calls DXUTWasKeyPressed(). Allows for optimzation - bool m_ReleasingSwapChain; // if true, the app is releasing its swapchain - bool m_IsInGammaCorrectMode; // Tell DXUTRes and DXUTMisc that we are in gamma correct mode + bool m_ReleasingSwapChain; // if true, the app is releasing its swapchain + bool m_IsInGammaCorrectMode; // Tell DXUTRes and DXUTMisc that we are in gamma correct mode LPDXUTCALLBACKMODIFYDEVICESETTINGS m_ModifyDeviceSettingsFunc; // modify Direct3D device settings callback LPDXUTCALLBACKDEVICEREMOVED m_DeviceRemovedFunc; // Direct3D device removed callback @@ -206,13 +215,6 @@ class DXUTState LPDXUTCALLBACKMOUSE m_MouseFunc; // mouse callback LPDXUTCALLBACKMSGPROC m_WindowMsgFunc; // window messages callback - LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE m_IsD3D9DeviceAcceptableFunc; // D3D9 is device acceptable callback - LPDXUTCALLBACKD3D9DEVICECREATED m_D3D9DeviceCreatedFunc; // D3D9 device created callback - LPDXUTCALLBACKD3D9DEVICERESET m_D3D9DeviceResetFunc; // D3D9 device reset callback - LPDXUTCALLBACKD3D9DEVICELOST m_D3D9DeviceLostFunc; // D3D9 device lost callback - LPDXUTCALLBACKD3D9DEVICEDESTROYED m_D3D9DeviceDestroyedFunc; // D3D9 device destroyed callback - LPDXUTCALLBACKD3D9FRAMERENDER m_D3D9FrameRenderFunc; // D3D9 frame render callback - LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE m_IsD3D11DeviceAcceptableFunc; // D3D11 is device acceptable callback LPDXUTCALLBACKD3D11DEVICECREATED m_D3D11DeviceCreatedFunc; // D3D11 device created callback LPDXUTCALLBACKD3D11SWAPCHAINRESIZED m_D3D11SwapChainResizedFunc; // D3D11 SwapChain reset callback @@ -220,7 +222,6 @@ class DXUTState LPDXUTCALLBACKD3D11DEVICEDESTROYED m_D3D11DeviceDestroyedFunc; // D3D11 device destroyed callback LPDXUTCALLBACKD3D11FRAMERENDER m_D3D11FrameRenderFunc; // D3D11 frame render callback - void* m_ModifyDeviceSettingsFuncUserContext; // user context for modify Direct3D device settings callback void* m_DeviceRemovedFuncUserContext; // user context for Direct3D device removed callback void* m_FrameMoveFuncUserContext; // user context for frame move callback @@ -228,13 +229,6 @@ class DXUTState void* m_MouseFuncUserContext; // user context for mouse callback void* m_WindowMsgFuncUserContext; // user context for window messages callback - void* m_IsD3D9DeviceAcceptableFuncUserContext; // user context for is D3D9 device acceptable callback - void* m_D3D9DeviceCreatedFuncUserContext; // user context for D3D9 device created callback - void* m_D3D9DeviceResetFuncUserContext; // user context for D3D9 device reset callback - void* m_D3D9DeviceLostFuncUserContext; // user context for D3D9 device lost callback - void* m_D3D9DeviceDestroyedFuncUserContext; // user context for D3D9 device destroyed callback - void* m_D3D9FrameRenderFuncUserContext; // user context for D3D9 frame render callback - void* m_IsD3D11DeviceAcceptableFuncUserContext; // user context for is D3D11 device acceptable callback void* m_D3D11DeviceCreatedFuncUserContext; // user context for D3D11 device created callback void* m_D3D11SwapChainResizedFuncUserContext; // user context for D3D11 SwapChain resized callback @@ -246,7 +240,7 @@ class DXUTState bool m_LastKeys[256]; // array of last key state bool m_MouseButtons[5]; // array of mouse states - CGrowableArray* m_TimerList; // list of DXUT_TIMER structs + std::vector* m_TimerList; // list of DXUT_TIMER structs WCHAR m_StaticFrameStats[256]; // static part of frames stats WCHAR m_FPSStats[64]; // fps stats WCHAR m_FrameStats[256]; // frame stats (fps, width, etc) @@ -257,13 +251,20 @@ class DXUTState STATE m_state; public: - DXUTState() { Create(); } - ~DXUTState() { Destroy(); } + DXUTState() noexcept : m_state{} + { + Create(); + } + + ~DXUTState() + { + Destroy(); + } - void Create() + void Create() { g_bThreadSafe = true; - InitializeCriticalSectionAndSpinCount( &g_cs, 1000 ); + (void)InitializeCriticalSectionAndSpinCount( &g_cs, 1000 ); ZeroMemory( &m_state, sizeof( STATE ) ); m_state.m_OverrideStartX = -1; @@ -272,7 +273,6 @@ class DXUTState m_state.m_ScreenShotName[0] = 0; m_state.m_SaveScreenShot = false; m_state.m_ExitAfterScreenShot = false; - m_state.m_OverrideForceAPI = -1; m_state.m_OverrideAdapterOrdinal = -1; m_state.m_OverrideOutput = -1; m_state.m_OverrideForceVsync = -1; @@ -285,7 +285,7 @@ class DXUTState m_state.m_HandleAltEnter = true; m_state.m_HandlePause = true; m_state.m_IsInGammaCorrectMode = true; - m_state.m_FPS = 1.0f; + m_state.m_FPS = 1.0f; m_state.m_MessageWhenD3D11NotAvailable = true; } @@ -299,12 +299,6 @@ class DXUTState // Macros to define access functions for thread safe access into m_state GET_SET_ACCESSOR( DXUTDeviceSettings*, CurrentDeviceSettings ); - // D3D9 specific - GET_SET_ACCESSOR( IDirect3D9*, D3D9 ); - GET_SET_ACCESSOR( IDirect3DDevice9*, D3D9Device ); - GETP_SETP_ACCESSOR( D3DSURFACE_DESC, BackBufferSurfaceDesc9 ); - GETP_SETP_ACCESSOR( D3DCAPS9, Caps ); - // D3D11 specific GET_SET_ACCESSOR( IDXGIFactory1*, DXGIFactory ); GET_SET_ACCESSOR( IDXGIAdapter1*, DXGIAdapter ); @@ -315,8 +309,6 @@ class DXUTState GET_SET_ACCESSOR( bool, RenderingOccluded ); GET_SET_ACCESSOR( bool, DoNotStoreBufferSize ); - // D3D11 specific - GET_SET_ACCESSOR( bool, D3D11Available ); GET_SET_ACCESSOR( ID3D11Device*, D3D11Device ); GET_SET_ACCESSOR( ID3D11DeviceContext*, D3D11DeviceContext ); GET_SET_ACCESSOR( D3D_FEATURE_LEVEL, D3D11FeatureLevel ); @@ -325,6 +317,21 @@ class DXUTState GET_SET_ACCESSOR( ID3D11RenderTargetView*, D3D11RenderTargetView ); GET_SET_ACCESSOR( ID3D11RasterizerState*, D3D11RasterizerState ); + GET_SET_ACCESSOR( ID3D11Device1*, D3D11Device1 ); + GET_SET_ACCESSOR( ID3D11DeviceContext1*, D3D11DeviceContext1 ); + + GET_SET_ACCESSOR(ID3D11Device2*, D3D11Device2); + GET_SET_ACCESSOR(ID3D11DeviceContext2*, D3D11DeviceContext2); + +#ifdef USE_DIRECT3D11_3 + GET_SET_ACCESSOR(ID3D11Device3*, D3D11Device3); + GET_SET_ACCESSOR(ID3D11DeviceContext3*, D3D11DeviceContext3); +#endif + +#ifdef USE_DIRECT3D11_4 + GET_SET_ACCESSOR(ID3D11Device4*, D3D11Device4); + GET_SET_ACCESSOR(ID3D11DeviceContext4*, D3D11DeviceContext4); +#endif GET_SET_ACCESSOR( HWND, HWNDFocus ); GET_SET_ACCESSOR( HWND, HWNDDeviceFullScreen ); @@ -332,7 +339,6 @@ class DXUTState GET_SET_ACCESSOR( HMONITOR, AdapterMonitor ); GET_SET_ACCESSOR( HMENU, Menu ); - GET_SET_ACCESSOR( UINT, FullScreenBackBufferWidthAtModeChange ); GET_SET_ACCESSOR( UINT, FullScreenBackBufferHeightAtModeChange ); GET_SET_ACCESSOR( UINT, WindowBackBufferWidthAtModeChange ); @@ -363,10 +369,6 @@ class DXUTState GET_SET_ACCESSOR( TOGGLEKEYS, StartupToggleKeys ); GET_SET_ACCESSOR( FILTERKEYS, StartupFilterKeys ); - GET_SET_ACCESSOR( bool, AppSupportsD3D9Override ); - GET_SET_ACCESSOR( bool, AppSupportsD3D11Override ); - GET_SET_ACCESSOR( bool, UseD3DVersionOverride ); - GET_SET_ACCESSOR( bool, HandleEscape ); GET_SET_ACCESSOR( bool, HandleAltEnter ); GET_SET_ACCESSOR( bool, HandlePause ); @@ -408,9 +410,7 @@ class DXUTState GET_ACCESSOR( WCHAR*, ScreenShotName ); GET_SET_ACCESSOR( bool, SaveScreenShot ); GET_SET_ACCESSOR( bool, ExitAfterScreenShot ); - - GET_SET_ACCESSOR( int, OverrideForceAPI ); GET_SET_ACCESSOR( int, OverrideAdapterOrdinal ); GET_SET_ACCESSOR( bool, OverrideWindowed ); GET_SET_ACCESSOR( int, OverrideOutput ); @@ -421,11 +421,11 @@ class DXUTState GET_SET_ACCESSOR( int, OverrideHeight ); GET_SET_ACCESSOR( bool, OverrideForceHAL ); GET_SET_ACCESSOR( bool, OverrideForceREF ); + GET_SET_ACCESSOR( bool, OverrideForceWARP ); GET_SET_ACCESSOR( bool, OverrideConstantFrameTime ); GET_SET_ACCESSOR( float, OverrideConstantTimePerFrame ); GET_SET_ACCESSOR( int, OverrideQuitAfterFrame ); GET_SET_ACCESSOR( int, OverrideForceVsync ); - GET_SET_ACCESSOR( bool, OverrideRelaunchMCE ); GET_SET_ACCESSOR( bool, ReleasingSwapChain ); GET_SET_ACCESSOR( bool, IsInGammaCorrectMode ); @@ -436,13 +436,6 @@ class DXUTState GET_SET_ACCESSOR( LPDXUTCALLBACKMOUSE, MouseFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKMSGPROC, WindowMsgFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE, IsD3D9DeviceAcceptableFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICECREATED, D3D9DeviceCreatedFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICERESET, D3D9DeviceResetFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICELOST, D3D9DeviceLostFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICEDESTROYED, D3D9DeviceDestroyedFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9FRAMERENDER, D3D9FrameRenderFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE, IsD3D11DeviceAcceptableFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKD3D11DEVICECREATED, D3D11DeviceCreatedFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKD3D11SWAPCHAINRESIZED, D3D11SwapChainResizedFunc ); @@ -457,13 +450,6 @@ class DXUTState GET_SET_ACCESSOR( void*, MouseFuncUserContext ); GET_SET_ACCESSOR( void*, WindowMsgFuncUserContext ); - GET_SET_ACCESSOR( void*, IsD3D9DeviceAcceptableFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceCreatedFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceResetFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceLostFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceDestroyedFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9FrameRenderFuncUserContext ); - GET_SET_ACCESSOR( void*, IsD3D11DeviceAcceptableFuncUserContext ); GET_SET_ACCESSOR( void*, D3D11DeviceCreatedFuncUserContext ); GET_SET_ACCESSOR( void*, D3D11DeviceDestroyedFuncUserContext ); @@ -471,7 +457,7 @@ class DXUTState GET_SET_ACCESSOR( void*, D3D11SwapChainReleasingFuncUserContext ); GET_SET_ACCESSOR( void*, D3D11FrameRenderFuncUserContext ); - GET_SET_ACCESSOR( CGrowableArray*, TimerList ); + GET_SET_ACCESSOR( std::vector*, TimerList ); GET_ACCESSOR( bool*, Keys ); GET_ACCESSOR( bool*, LastKeys ); GET_ACCESSOR( bool*, MouseButtons ); @@ -486,14 +472,14 @@ class DXUTState //-------------------------------------------------------------------------------------- // Global state //-------------------------------------------------------------------------------------- -DXUTState* g_pDXUTState = NULL; +DXUTState* g_pDXUTState = nullptr; HRESULT WINAPI DXUTCreateState() { - if( g_pDXUTState == NULL ) + if( !g_pDXUTState ) { - g_pDXUTState = new DXUTState; - if( NULL == g_pDXUTState ) + g_pDXUTState = new (std::nothrow) DXUTState; + if( !g_pDXUTState ) return E_OUTOFMEMORY; } return S_OK; @@ -507,17 +493,17 @@ void WINAPI DXUTDestroyState() class DXUTMemoryHelper { public: - DXUTMemoryHelper() { DXUTCreateState(); } + DXUTMemoryHelper() noexcept { DXUTCreateState(); } ~DXUTMemoryHelper() { DXUTDestroyState(); } }; - DXUTState& GetDXUTState() { // This class will auto create the memory when its first accessed and delete it after the program exits WinMain. // However the application can also call DXUTCreateState() & DXUTDestroyState() independantly if its wants static DXUTMemoryHelper memory; - assert( g_pDXUTState != NULL ); + assert( g_pDXUTState ); + _Analysis_assume_( g_pDXUTState ); return *g_pDXUTState; } @@ -525,117 +511,81 @@ DXUTState& GetDXUTState() //-------------------------------------------------------------------------------------- // Internal functions forward declarations //-------------------------------------------------------------------------------------- -void DXUTParseCommandLine( __inout WCHAR* strCommandLine, - bool bIgnoreFirstCommand = true ); -bool DXUTIsNextArg( __inout WCHAR*& strCmdLine, __in const WCHAR* strArg ); -bool DXUTGetCmdParam( __inout WCHAR*& strCmdLine, __out WCHAR* strFlag ); -void DXUTAllowShortcutKeys( bool bAllowKeys ); +void DXUTParseCommandLine( _In_z_ WCHAR* strCommandLine, + _In_ bool bIgnoreFirstCommand = true ); +bool DXUTIsNextArg( _Inout_ WCHAR*& strCmdLine, _In_ const WCHAR* strArg ); +bool DXUTGetCmdParam( _Inout_ WCHAR*& strCmdLine, _Out_cap_(cchDest) WCHAR* strFlag, _In_ int cchDest ); +void DXUTAllowShortcutKeys( _In_ bool bAllowKeys ); void DXUTUpdateStaticFrameStats(); void DXUTUpdateFrameStats(); -LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); +LRESULT CALLBACK DXUTStaticWndProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); void DXUTHandleTimers(); -void DXUTDisplayErrorMessage( HRESULT hr ); -int DXUTMapButtonToArrayIndex( BYTE vButton ); +void DXUTDisplayErrorMessage( _In_ HRESULT hr ); +int DXUTMapButtonToArrayIndex( _In_ BYTE vButton ); -HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, - IDirect3DDevice9* pd3d9DeviceFromApp, - ID3D11Device* pd3d11DeviceFromApp, - bool bForceRecreate, - bool bClipWindowToSingleAdapter ); +HRESULT DXUTChangeDevice( _In_ DXUTDeviceSettings* pNewDeviceSettings, + _In_ bool bClipWindowToSingleAdapter ); -bool DXUTCanDeviceBeReset( DXUTDeviceSettings* pOldDeviceSettings, - DXUTDeviceSettings* pNewDeviceSettings, - IDirect3DDevice9* pd3d9DeviceFromApp, - ID3D11Device* pd3d11DeviceFromApp ); +bool DXUTCanDeviceBeReset( _In_ DXUTDeviceSettings* pOldDeviceSettings, + _In_ DXUTDeviceSettings* pNewDeviceSettings, + _In_ ID3D11Device* pd3d11DeviceFromApp ); HRESULT DXUTDelayLoadDXGI(); -HRESULT DXUTDelayLoadD3D9(); -HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL = D3D_FEATURE_LEVEL(0) ); -void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pDeviceSettings ); +HRESULT DXUTSnapDeviceSettingsToEnumDevice( _In_ DXUTDeviceSettings* pDeviceSettings, _In_ bool forceEnum, _In_ D3D_FEATURE_LEVEL forceFL = D3D_FEATURE_LEVEL(0) ); +void DXUTUpdateDeviceSettingsWithOverrides( _Inout_ DXUTDeviceSettings* pDeviceSettings ); void DXUTCheckForDXGIFullScreenSwitch(); -void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullscreen ); +void DXUTResizeDXGIBuffers( _In_ UINT Width, _In_ UINT Height, _In_ BOOL bFullscreen ); void DXUTCheckForDXGIBufferChange(); void DXUTCheckForWindowSizeChange(); void DXUTCheckForWindowChangingMonitors(); -void DXUTCleanup3DEnvironment( bool bReleaseSettings ); -HMONITOR DXUTGetMonitorFromAdapter( DXUTDeviceSettings* pDeviceSettings ); -HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal ); -HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal ); +void DXUTCleanup3DEnvironment( _In_ bool bReleaseSettings ); +HMONITOR DXUTGetMonitorFromAdapter( _In_ DXUTDeviceSettings* pDeviceSettings ); +HRESULT DXUTGetAdapterOrdinalFromMonitor( _In_ HMONITOR hMonitor, _Out_ UINT* pAdapterOrdinal ); +HRESULT DXUTGetOutputOrdinalFromMonitor( _In_ HMONITOR hMonitor, _Out_ UINT* pOutputOrdinal ); HRESULT DXUTHandleDeviceRemoved(); void DXUTUpdateBackBufferDesc(); void DXUTSetupCursor(); -// Direct3D 9 -HRESULT DXUTCreate3DEnvironment9( IDirect3DDevice9* pd3dDeviceFromApp ); -HRESULT DXUTReset3DEnvironment9(); -void DXUTRender3DEnvironment9(); -void DXUTCleanup3DEnvironment9( bool bReleaseSettings = true ); -HRESULT DXUTSetD3D9DeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark ); -void DXUTUpdateD3D9DeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, - D3DADAPTER_IDENTIFIER9* pAdapterIdentifier ); -HRESULT DXUTFindD3D9AdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat, - BOOL Windowed, D3DFORMAT* pAdapterFormat ); - // Direct3D 11 -HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, DXUTDeviceSettings* pDeviceSettings ); -HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3dDeviceFromApp ); +HRESULT DXUTCreateD3D11Views( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dDeviceContext, _In_ DXUTDeviceSettings* pDeviceSettings ); +HRESULT DXUTCreate3DEnvironment11(); HRESULT DXUTReset3DEnvironment11(); -void DXUTRender3DEnvironment11(); -void DXUTCleanup3DEnvironment11( bool bReleaseSettings = true ); -void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* pAdapterDesc ); +void DXUTUpdateD3D11DeviceStats( _In_ D3D_DRIVER_TYPE DeviceType, _In_ D3D_FEATURE_LEVEL featureLevel, _In_ DXGI_ADAPTER_DESC* pAdapterDesc ); //-------------------------------------------------------------------------------------- // Internal helper functions //-------------------------------------------------------------------------------------- -bool DXUTIsD3D9( DXUTDeviceSettings* pDeviceSettings ) { return (pDeviceSettings && pDeviceSettings->ver == DXUT_D3D9_DEVICE ); }; -bool DXUTIsCurrentDeviceD3D9() { DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); return DXUTIsD3D9(pDeviceSettings); }; -UINT DXUTGetBackBufferWidthFromDS( DXUTDeviceSettings* pNewDeviceSettings ) +UINT DXUTGetBackBufferWidthFromDS( _In_ DXUTDeviceSettings* pNewDeviceSettings ) { - if( DXUTIsD3D9( pNewDeviceSettings ) ) - return pNewDeviceSettings->d3d9.pp.BackBufferWidth; - else - return pNewDeviceSettings->d3d11.sd.BufferDesc.Width; + return pNewDeviceSettings->d3d11.sd.BufferDesc.Width; } -UINT DXUTGetBackBufferHeightFromDS( DXUTDeviceSettings* pNewDeviceSettings ) +UINT DXUTGetBackBufferHeightFromDS( _In_ DXUTDeviceSettings* pNewDeviceSettings ) { - if( DXUTIsD3D9(pNewDeviceSettings) ) - return pNewDeviceSettings->d3d9.pp.BackBufferHeight; - else - return pNewDeviceSettings->d3d11.sd.BufferDesc.Height; + return pNewDeviceSettings->d3d11.sd.BufferDesc.Height; } -bool DXUTGetIsWindowedFromDS( DXUTDeviceSettings* pNewDeviceSettings ) +bool DXUTGetIsWindowedFromDS( _In_ DXUTDeviceSettings* pNewDeviceSettings ) { if (!pNewDeviceSettings) return true; - if( DXUTIsD3D9(pNewDeviceSettings) ) - return pNewDeviceSettings->d3d9.pp.Windowed ? true : false; - else - return pNewDeviceSettings->d3d11.sd.Windowed ? true : false; + return pNewDeviceSettings->d3d11.sd.Windowed ? true : false; } //-------------------------------------------------------------------------------------- // External state access functions //-------------------------------------------------------------------------------------- -BOOL WINAPI DXUTGetMSAASwapChainCreated() { +bool WINAPI DXUTGetMSAASwapChainCreated() +{ DXUTDeviceSettings *psettings = GetDXUTState().GetCurrentDeviceSettings(); - if (psettings->ver == DXUT_D3D11_DEVICE) { - return psettings->d3d11.sd.SampleDesc.Count > 1; - }else if (psettings->ver == DXUT_D3D9_DEVICE) { - return (psettings->d3d9.pp.MultiSampleType >= D3DMULTISAMPLE_2_SAMPLES); - } - else return false; + if ( !psettings ) + return false; + return (psettings->d3d11.sd.SampleDesc.Count > 1); } -IDirect3DDevice9* WINAPI DXUTGetD3D9Device() { return GetDXUTState().GetD3D9Device(); } -const D3DSURFACE_DESC* WINAPI DXUTGetD3D9BackBufferSurfaceDesc() { return GetDXUTState().GetBackBufferSurfaceDesc9(); } -const D3DCAPS9* WINAPI DXUTGetD3D9DeviceCaps() { return GetDXUTState().GetCaps(); } -ID3D11Device* WINAPI DXUTGetD3D11Device() { return GetDXUTState().GetD3D11Device(); } -D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel() { return GetDXUTState().GetD3D11FeatureLevel(); } -ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext() { return GetDXUTState().GetD3D11DeviceContext(); } +D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel() { return GetDXUTState().GetD3D11FeatureLevel(); } IDXGISwapChain* WINAPI DXUTGetDXGISwapChain() { return GetDXUTState().GetDXGISwapChain(); } ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView() { return GetDXUTState().GetD3D11RenderTargetView(); } ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView() { return GetDXUTState().GetD3D11DepthStencilView(); } @@ -648,8 +598,8 @@ HWND WINAPI DXUTGetHWNDDeviceWindowed() { return GetDXUTState RECT WINAPI DXUTGetWindowClientRect() { RECT rc; GetClientRect( DXUTGetHWND(), &rc ); return rc; } LONG WINAPI DXUTGetWindowWidth() { RECT rc = DXUTGetWindowClientRect(); return ((LONG)rc.right - rc.left); } LONG WINAPI DXUTGetWindowHeight() { RECT rc = DXUTGetWindowClientRect(); return ((LONG)rc.bottom - rc.top); } -RECT WINAPI DXUTGetWindowClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetWindowBackBufferWidthAtModeChange(), GetDXUTState().GetWindowBackBufferHeightAtModeChange() }; return rc; } -RECT WINAPI DXUTGetFullsceenClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetFullScreenBackBufferWidthAtModeChange(), GetDXUTState().GetFullScreenBackBufferHeightAtModeChange() }; return rc; } +RECT WINAPI DXUTGetWindowClientRectAtModeChange() { RECT rc = { 0, 0, static_cast( GetDXUTState().GetWindowBackBufferWidthAtModeChange() ), static_cast( GetDXUTState().GetWindowBackBufferHeightAtModeChange() ) }; return rc; } +RECT WINAPI DXUTGetFullsceenClientRectAtModeChange() { RECT rc = { 0, 0, static_cast( GetDXUTState().GetFullScreenBackBufferWidthAtModeChange() ), static_cast( GetDXUTState().GetFullScreenBackBufferHeightAtModeChange() ) }; return rc; } double WINAPI DXUTGetTime() { return GetDXUTState().GetTime(); } float WINAPI DXUTGetElapsedTime() { return GetDXUTState().GetElapsedTime(); } float WINAPI DXUTGetFPS() { return GetDXUTState().GetFPS(); } @@ -663,41 +613,46 @@ bool WINAPI DXUTGetShowMsgBoxOnError() { return GetDXUTState bool WINAPI DXUTGetAutomation() { return GetDXUTState().GetAutomation(); } bool WINAPI DXUTIsWindowed() { return DXUTGetIsWindowedFromDS( GetDXUTState().GetCurrentDeviceSettings() ); } bool WINAPI DXUTIsInGammaCorrectMode() { return GetDXUTState().GetIsInGammaCorrectMode(); } -IDirect3D9* WINAPI DXUTGetD3D9Object() { DXUTDelayLoadD3D9(); return GetDXUTState().GetD3D9(); } -IDXGIFactory1* WINAPI DXUTGetDXGIFactory() { DXUTDelayLoadDXGI(); return GetDXUTState().GetDXGIFactory(); } -bool WINAPI DXUTIsD3D11Available() { DXUTDelayLoadDXGI(); return GetDXUTState().GetD3D11Available(); } -bool WINAPI DXUTIsAppRenderingWithD3D9() { return (GetDXUTState().GetD3D9Device() != NULL); } -bool WINAPI DXUTIsAppRenderingWithD3D11() { return (GetDXUTState().GetD3D11Device() != NULL); } +IDXGIFactory1* WINAPI DXUTGetDXGIFactory() { DXUTDelayLoadDXGI(); return GetDXUTState().GetDXGIFactory(); } + +ID3D11Device* WINAPI DXUTGetD3D11Device() { return GetDXUTState().GetD3D11Device(); } +ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext() { return GetDXUTState().GetD3D11DeviceContext(); } +ID3D11Device1* WINAPI DXUTGetD3D11Device1() { return GetDXUTState().GetD3D11Device1(); } +ID3D11DeviceContext1* WINAPI DXUTGetD3D11DeviceContext1() { return GetDXUTState().GetD3D11DeviceContext1(); } + +ID3D11Device2* WINAPI DXUTGetD3D11Device2() { return GetDXUTState().GetD3D11Device2(); } +ID3D11DeviceContext2* WINAPI DXUTGetD3D11DeviceContext2() { return GetDXUTState().GetD3D11DeviceContext2(); } + +#ifdef USE_DIRECT3D11_3 +ID3D11Device3* WINAPI DXUTGetD3D11Device3() { return GetDXUTState().GetD3D11Device3(); } +ID3D11DeviceContext3* WINAPI DXUTGetD3D11DeviceContext3() { return GetDXUTState().GetD3D11DeviceContext3(); } +#endif + +#ifdef USE_DIRECT3D11_4 +ID3D11Device4* WINAPI DXUTGetD3D11Device4() { return GetDXUTState().GetD3D11Device4(); } +ID3D11DeviceContext4* WINAPI DXUTGetD3D11DeviceContext4() { return GetDXUTState().GetD3D11DeviceContext4(); } +#endif //-------------------------------------------------------------------------------------- // External callback setup functions //-------------------------------------------------------------------------------------- // General callbacks -void WINAPI DXUTSetCallbackDeviceChanging( LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, void* pUserContext ) { GetDXUTState().SetModifyDeviceSettingsFunc( pCallback ); GetDXUTState().SetModifyDeviceSettingsFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackDeviceRemoved( LPDXUTCALLBACKDEVICEREMOVED pCallback, void* pUserContext ) { GetDXUTState().SetDeviceRemovedFunc( pCallback ); GetDXUTState().SetDeviceRemovedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackFrameMove( LPDXUTCALLBACKFRAMEMOVE pCallback, void* pUserContext ) { GetDXUTState().SetFrameMoveFunc( pCallback ); GetDXUTState().SetFrameMoveFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackKeyboard( LPDXUTCALLBACKKEYBOARD pCallback, void* pUserContext ) { GetDXUTState().SetKeyboardFunc( pCallback ); GetDXUTState().SetKeyboardFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackMouse( LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove, void* pUserContext ) { GetDXUTState().SetMouseFunc( pCallback ); GetDXUTState().SetNotifyOnMouseMove( bIncludeMouseMove ); GetDXUTState().SetMouseFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackMsgProc( LPDXUTCALLBACKMSGPROC pCallback, void* pUserContext ) { GetDXUTState().SetWindowMsgFunc( pCallback ); GetDXUTState().SetWindowMsgFuncUserContext( pUserContext ); } - -// Direct3D 9 callbacks -void WINAPI DXUTSetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE pCallback, void* pUserContext ) { GetDXUTState().SetIsD3D9DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D9DeviceAcceptableFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceCreated( LPDXUTCALLBACKD3D9DEVICECREATED pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D9DeviceCreatedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceReset( LPDXUTCALLBACKD3D9DEVICERESET pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceResetFunc( pCallback ); GetDXUTState().SetD3D9DeviceResetFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceLost( LPDXUTCALLBACKD3D9DEVICELOST pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceLostFunc( pCallback ); GetDXUTState().SetD3D9DeviceLostFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceDestroyed( LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D9DeviceDestroyedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9FrameRender( LPDXUTCALLBACKD3D9FRAMERENDER pCallback, void* pUserContext ) { GetDXUTState().SetD3D9FrameRenderFunc( pCallback ); GetDXUTState().SetD3D9FrameRenderFuncUserContext( pUserContext ); } -void DXUTGetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE* ppCallback, void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D9DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D9DeviceAcceptableFuncUserContext(); } +void WINAPI DXUTSetCallbackDeviceChanging( _In_ LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetModifyDeviceSettingsFunc( pCallback ); GetDXUTState().SetModifyDeviceSettingsFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackDeviceRemoved( _In_ LPDXUTCALLBACKDEVICEREMOVED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetDeviceRemovedFunc( pCallback ); GetDXUTState().SetDeviceRemovedFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackFrameMove( _In_ LPDXUTCALLBACKFRAMEMOVE pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetFrameMoveFunc( pCallback ); GetDXUTState().SetFrameMoveFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackKeyboard( _In_ LPDXUTCALLBACKKEYBOARD pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetKeyboardFunc( pCallback ); GetDXUTState().SetKeyboardFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackMouse( _In_ LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove, _In_opt_ void* pUserContext ) { GetDXUTState().SetMouseFunc( pCallback ); GetDXUTState().SetNotifyOnMouseMove( bIncludeMouseMove ); GetDXUTState().SetMouseFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackMsgProc( _In_ LPDXUTCALLBACKMSGPROC pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetWindowMsgFunc( pCallback ); GetDXUTState().SetWindowMsgFuncUserContext( pUserContext ); } // Direct3D 11 callbacks -void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, void* pUserContext ) { GetDXUTState().SetIsD3D11DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D11DeviceAcceptableFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11DeviceCreated( LPDXUTCALLBACKD3D11DEVICECREATED pCallback, void* pUserContext ) { GetDXUTState().SetD3D11DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D11DeviceCreatedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11SwapChainResized( LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, void* pUserContext ) { GetDXUTState().SetD3D11SwapChainResizedFunc( pCallback ); GetDXUTState().SetD3D11SwapChainResizedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11FrameRender( LPDXUTCALLBACKD3D11FRAMERENDER pCallback, void* pUserContext ) { GetDXUTState().SetD3D11FrameRenderFunc( pCallback ); GetDXUTState().SetD3D11FrameRenderFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, void* pUserContext ) { GetDXUTState().SetD3D11SwapChainReleasingFunc( pCallback ); GetDXUTState().SetD3D11SwapChainReleasingFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, void* pUserContext ) { GetDXUTState().SetD3D11DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D11DeviceDestroyedFuncUserContext( pUserContext ); } -void DXUTGetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE* ppCallback, void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D11DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D11DeviceAcceptableFuncUserContext(); } +void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetIsD3D11DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D11DeviceAcceptableFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11DeviceCreated( _In_ LPDXUTCALLBACKD3D11DEVICECREATED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D11DeviceCreatedFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11SwapChainResized( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11SwapChainResizedFunc( pCallback ); GetDXUTState().SetD3D11SwapChainResizedFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11FrameRender( _In_ LPDXUTCALLBACKD3D11FRAMERENDER pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11FrameRenderFunc( pCallback ); GetDXUTState().SetD3D11FrameRenderFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11SwapChainReleasingFunc( pCallback ); GetDXUTState().SetD3D11SwapChainReleasingFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( _In_ LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D11DeviceDestroyedFuncUserContext( pUserContext ); } +void DXUTGetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE* ppCallback, _Outptr_ void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D11DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D11DeviceAcceptableFuncUserContext(); } //-------------------------------------------------------------------------------------- @@ -706,16 +661,13 @@ void DXUTGetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE // Possible command line parameters are: // -forcefeaturelevel:fl forces app to use a specified direct3D11 feature level // -screenshotexit:filename save a screenshot to the filename.bmp and exit. -// -forceapi:# forces app to use specified Direct3D API version (fails if the application doesn't support this API or if no device is found) // -adapter:# forces app to use this adapter # (fails if the adapter doesn't exist) -// -output:# [D3D11 only] forces app to use a particular output on the adapter (fails if the output doesn't exist) +// -output:# forces app to use a particular output on the adapter (fails if the output doesn't exist) // -windowed forces app to start windowed // -fullscreen forces app to start full screen // -forcehal forces app to use HAL (fails if HAL doesn't exist) // -forceref forces app to use REF (fails if REF doesn't exist) -// -forcepurehwvp [D3D9 only] forces app to use pure HWVP (fails if device doesn't support it) -// -forcehwvp [D3D9 only] forces app to use HWVP (fails if device doesn't support it) -// -forceswvp [D3D9 only] forces app to use SWVP +// -forcewarp forces app to use WARP (fails if WARP doesn't exist) // -forcevsync:# if # is 0, then vsync is disabled // -width:# forces app to use # for width. for full screen, it will pick the closest possible supported mode // -height:# forces app to use # for height. for full screen, it will pick the closest possible supported mode @@ -725,16 +677,20 @@ void DXUTGetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE // -quitafterframe:x forces app to quit after # frames // -noerrormsgboxes prevents the display of message boxes generated by the framework so the application can be run without user interaction // -nostats prevents the display of the stats -// -relaunchmce re-launches the MCE UI after the app exits // -automation a hint to other components that automation is active //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTInit( bool bParseCommandLine, bool bShowMsgBoxOnError, - __in_opt WCHAR* strExtraCommandLineParams, + WCHAR* strExtraCommandLineParams, bool bThreadSafeDXUT ) { g_bThreadSafe = bThreadSafeDXUT; + HRESULT hr = CoInitializeEx( nullptr, COINIT_MULTITHREADED ); + if ( FAILED(hr) ) + return hr; + GetDXUTState().SetDXUTInitCalled( true ); // Not always needed, but lets the app create GDI dialogs @@ -742,15 +698,18 @@ HRESULT WINAPI DXUTInit( bool bParseCommandLine, // Save the current sticky/toggle/filter key settings so DXUT can restore them later STICKYKEYS sk = {sizeof(STICKYKEYS), 0}; - SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0); + if ( !SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0) ) + memset( &sk, 0, sizeof(sk) ); GetDXUTState().SetStartupStickyKeys( sk ); TOGGLEKEYS tk = {sizeof(TOGGLEKEYS), 0}; - SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0); + if ( !SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0) ) + memset( &tk, 0, sizeof(tk) ); GetDXUTState().SetStartupToggleKeys( tk ); FILTERKEYS fk = {sizeof(FILTERKEYS), 0}; - SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0); + if ( !SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0) ) + memset( &fk, 0, sizeof(fk) ); GetDXUTState().SetStartupFilterKeys( fk ); GetDXUTState().SetShowMsgBoxOnError( bShowMsgBoxOnError ); @@ -772,16 +731,17 @@ HRESULT WINAPI DXUTInit( bool bParseCommandLine, //-------------------------------------------------------------------------------------- // Parses the command line for parameters. See DXUTInit() for list //-------------------------------------------------------------------------------------- -void DXUTParseCommandLine(__inout WCHAR* strCommandLine, +_Use_decl_annotations_ +void DXUTParseCommandLine(WCHAR* strCommandLine, bool bIgnoreFirstCommand ) { WCHAR* strCmdLine; WCHAR strFlag[MAX_PATH]; int nNumArgs; - LPWSTR* pstrArgList = CommandLineToArgvW( strCommandLine, &nNumArgs ); - int iArgStart = 0; - if( bIgnoreFirstCommand ) + auto pstrArgList = CommandLineToArgvW( strCommandLine, &nNumArgs ); + int iArgStart = 0; + if( bIgnoreFirstCommand ) iArgStart = 1; for( int iArg = iArgStart; iArg < nNumArgs; iArg++ ) { @@ -794,9 +754,20 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"forcefeaturelevel" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { - if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_11_0", MAX_PATH) == 0 ) { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + if (_wcsnicmp(strFlag, L"D3D_FEATURE_LEVEL_12_1", MAX_PATH) == 0) { + GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_12_1); + } + else if (_wcsnicmp(strFlag, L"D3D_FEATURE_LEVEL_12_0", MAX_PATH) == 0) { + GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_12_0); + } + else +#endif + if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_11_1", MAX_PATH) == 0 ) { + GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_11_1); + }else if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_11_0", MAX_PATH) == 0 ) { GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_11_0); }else if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_10_1", MAX_PATH) == 0 ) { GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_10_1); @@ -809,25 +780,13 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, }else if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_9_1", MAX_PATH) == 0 ) { GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_9_1); } - - continue; } } - if( DXUTIsNextArg( strCmdLine, L"forceapi" ) ) - { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) - { - int nAPIVersion = _wtoi( strFlag ); - GetDXUTState().SetOverrideForceAPI( nAPIVersion ); - continue; - } - } - if( DXUTIsNextArg( strCmdLine, L"adapter" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nAdapter = _wtoi( strFlag ); GetDXUTState().SetOverrideAdapterOrdinal( nAdapter ); @@ -843,7 +802,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"output" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int Output = _wtoi( strFlag ); GetDXUTState().SetOverrideOutput( Output ); @@ -863,11 +822,11 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, continue; } if( DXUTIsNextArg( strCmdLine, L"screenshotexit" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { GetDXUTState().SetExitAfterScreenShot( true ); GetDXUTState().SetSaveScreenShot( true ); - swprintf_s( GetDXUTState().GetScreenShotName(), 256, L"%s.bmp", strFlag ); + swprintf_s( GetDXUTState().GetScreenShotName(), 256, L"%ls.bmp", strFlag ); continue; } } @@ -876,10 +835,15 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, GetDXUTState().SetOverrideForceREF( true ); continue; } + if( DXUTIsNextArg( strCmdLine, L"forcewarp" ) ) + { + GetDXUTState().SetOverrideForceWARP( true ); + continue; + } if( DXUTIsNextArg( strCmdLine, L"forcevsync" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nOn = _wtoi( strFlag ); GetDXUTState().SetOverrideForceVsync( nOn ); @@ -889,7 +853,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"width" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nWidth = _wtoi( strFlag ); GetDXUTState().SetOverrideWidth( nWidth ); @@ -899,7 +863,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"height" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nHeight = _wtoi( strFlag ); GetDXUTState().SetOverrideHeight( nHeight ); @@ -909,7 +873,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"startx" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nX = _wtoi( strFlag ); GetDXUTState().SetOverrideStartX( nX ); @@ -919,7 +883,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"starty" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nY = _wtoi( strFlag ); GetDXUTState().SetOverrideStartY( nY ); @@ -930,8 +894,8 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"constantframetime" ) ) { float fTimePerFrame; - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) - fTimePerFrame = ( float )wcstod( strFlag, NULL ); + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) + fTimePerFrame = ( float )wcstod( strFlag, nullptr ); else fTimePerFrame = 0.0333f; GetDXUTState().SetOverrideConstantFrameTime( true ); @@ -942,7 +906,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"quitafterframe" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nFrame = _wtoi( strFlag ); GetDXUTState().SetOverrideQuitAfterFrame( nFrame ); @@ -962,12 +926,6 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, continue; } - if( DXUTIsNextArg( strCmdLine, L"relaunchmce" ) ) - { - GetDXUTState().SetOverrideRelaunchMCE( true ); - continue; - } - if( DXUTIsNextArg( strCmdLine, L"automation" ) ) { GetDXUTState().SetAutomation( true ); @@ -982,7 +940,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, strSpace++; *strSpace = 0; - DXUTOutputDebugString( L"Unrecognized flag: %s", strFlag ); + DXUTOutputDebugString( L"Unrecognized flag: %ls", strFlag ); strCmdLine += wcslen( strFlag ); } @@ -993,10 +951,11 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, //-------------------------------------------------------------------------------------- // Helper function for DXUTParseCommandLine //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool DXUTIsNextArg( WCHAR*& strCmdLine, const WCHAR* strArg ) { - int nArgLen = ( int )wcslen( strArg ); - int nCmdLen = ( int )wcslen( strCmdLine ); + size_t nArgLen = wcslen( strArg ); + size_t nCmdLen = wcslen( strCmdLine ); if( nCmdLen >= nArgLen && _wcsnicmp( strCmdLine, strArg, nArgLen ) == 0 && @@ -1015,17 +974,23 @@ bool DXUTIsNextArg( WCHAR*& strCmdLine, const WCHAR* strArg ) // Example: if strCmdLine=="-width:1024 -forceref" // then after: strCmdLine==" -forceref" and strFlag=="1024" //-------------------------------------------------------------------------------------- -bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag ) +_Use_decl_annotations_ +bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag, int cchDest ) { if( *strCmdLine == L':' ) { strCmdLine++; // Skip ':' - // Place NULL terminator in strFlag after current token - wcscpy_s( strFlag, MAX_PATH, strCmdLine ); + // Place nul terminator in strFlag after current token + wcscpy_s( strFlag, cchDest, strCmdLine ); + WCHAR* strSpace = strFlag; - while( *strSpace && ( *strSpace > L' ' ) ) - strSpace++; + int count = 0; + while( *strSpace && ( *strSpace > L' ' ) && (count < cchDest) ) + { + ++strSpace; + ++count; + } *strSpace = 0; // Update strCmdLine @@ -1046,7 +1011,9 @@ bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag ) // call it with the default parameters. Instead of calling this, you can // call DXUTSetWindow() to use an existing window. //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateWindow( unsigned int defaultWidth = 640, unsigned int defaultHeight = 480, const WCHAR* strWindowTitle /*= L"Direct3D Window"*/, bool allowWindowResize /*= true*/, HINSTANCE hInstance /*= NULL*/, HICON hIcon /*= NULL*/, HMENU hMenu /*= NULL*/, int x /*= CW_USEDEFAULT*/, int y /*= CW_USEDEFAULT*/ ) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstance, + HICON hIcon, HMENU hMenu, int x, int y ) { HRESULT hr; @@ -1070,15 +1037,15 @@ HRESULT WINAPI DXUTCreateWindow( unsigned int defaultWidth = 640, unsigned int d return hr; } - if( DXUTGetHWNDFocus() == NULL ) + if( !DXUTGetHWNDFocus() ) { - if( hInstance == NULL ) - hInstance = ( HINSTANCE )GetModuleHandle( NULL ); + if( !hInstance ) + hInstance = ( HINSTANCE )GetModuleHandle( nullptr ); GetDXUTState().SetHInstance( hInstance ); WCHAR szExePath[MAX_PATH]; - GetModuleFileName( NULL, szExePath, MAX_PATH ); - if( hIcon == NULL ) // If the icon is NULL, then use the first one found in the exe + GetModuleFileName( nullptr, szExePath, MAX_PATH ); + if( !hIcon ) // If the icon is NULL, then use the first one found in the exe hIcon = ExtractIcon( hInstance, szExePath, 0 ); // Register the windows class @@ -1089,9 +1056,9 @@ HRESULT WINAPI DXUTCreateWindow( unsigned int defaultWidth = 640, unsigned int d wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = hIcon; - wndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); + wndClass.hCursor = LoadCursor( nullptr, IDC_ARROW ); wndClass.hbrBackground = ( HBRUSH )GetStockObject( BLACK_BRUSH ); - wndClass.lpszMenuName = NULL; + wndClass.lpszMenuName = nullptr; wndClass.lpszClassName = L"Direct3DWindowClass"; if( !RegisterClass( &wndClass ) ) @@ -1112,8 +1079,8 @@ HRESULT WINAPI DXUTCreateWindow( unsigned int defaultWidth = 640, unsigned int d GetDXUTState().SetWindowCreatedWithDefaultPositions( true ); // Find the window's initial size, but it might be changed later - int nDefaultWidth = defaultWidth; - int nDefaultHeight = defaultHeight; + int nDefaultWidth = 800; + int nDefaultHeight = 600; if( GetDXUTState().GetOverrideWidth() != 0 ) nDefaultWidth = GetDXUTState().GetOverrideWidth(); if( GetDXUTState().GetOverrideHeight() != 0 ) @@ -1121,18 +1088,16 @@ HRESULT WINAPI DXUTCreateWindow( unsigned int defaultWidth = 640, unsigned int d RECT rc; SetRect( &rc, 0, 0, nDefaultWidth, nDefaultHeight ); - AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, ( hMenu != NULL ) ? true : false ); + AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, ( hMenu ) ? true : false ); WCHAR* strCachedWindowTitle = GetDXUTState().GetWindowTitle(); wcscpy_s( strCachedWindowTitle, 256, strWindowTitle ); // Create the render window - DWORD dwStyle = WS_OVERLAPPEDWINDOW; - if (!allowWindowResize) dwStyle = WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX; - HWND hWnd = CreateWindow( L"Direct3DWindowClass", strWindowTitle, dwStyle, + HWND hWnd = CreateWindow( L"Direct3DWindowClass", strWindowTitle, WS_OVERLAPPEDWINDOW, x, y, ( rc.right - rc.left ), ( rc.bottom - rc.top ), 0, hMenu, hInstance, 0 ); - if( hWnd == NULL ) + if( !hWnd ) { DWORD dwError = GetLastError(); return DXUT_ERR_MSGBOX( L"CreateWindow", HRESULT_FROM_WIN32(dwError) ); @@ -1153,6 +1118,7 @@ HRESULT WINAPI DXUTCreateWindow( unsigned int defaultWidth = 640, unsigned int d // has not already been called, it will call it with the default parameters. // Instead of calling this, you can call DXUTCreateWindow() to create a new window. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hWndDeviceWindowed, bool bHandleMessages ) { HRESULT hr; @@ -1163,10 +1129,10 @@ HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hW GetDXUTState().SetWindowCreateCalled( true ); - // To avoid confusion, we do not allow any HWND to be NULL here. The + // To avoid confusion, we do not allow any HWND to be nullptr here. The // caller must pass in valid HWND for all three parameters. The same // HWND may be used for more than one parameter. - if( hWndFocus == NULL || hWndDeviceFullScreen == NULL || hWndDeviceWindowed == NULL ) + if( !hWndFocus || !hWndDeviceFullScreen || !hWndDeviceWindowed ) return DXUT_ERR_MSGBOX( L"DXUTSetWindow", E_INVALIDARG ); // If subclassing the window, set the pointer to the local window procedure @@ -1213,6 +1179,7 @@ HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hW //-------------------------------------------------------------------------------------- // Handles window messages //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { @@ -1287,6 +1254,8 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM xPos, yPos, GetDXUTState().GetMouseFuncUserContext() ); } + // TODO - WM_POINTER for touch when on Windows 8.0 + // Pass all messages to the app's MsgProc callback, and don't // process further messages if the apps says not to. LPDXUTCALLBACKMSGPROC pCallbackMsgProc = GetDXUTState().GetWindowMsgFunc(); @@ -1302,8 +1271,7 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM switch( uMsg ) { case WM_PAINT: - { - + { // Handle paint messages when the app is paused if( DXUTIsRenderingPaused() && GetDXUTState().GetDeviceObjectsCreated() && GetDXUTState().GetDeviceObjectsReset() ) @@ -1312,49 +1280,13 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM double fTime = DXUTGetTime(); float fElapsedTime = DXUTGetElapsedTime(); - if( DXUTIsCurrentDeviceD3D9() ) - { - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice ) - { - LPDXUTCALLBACKD3D9FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D9FrameRenderFunc(); - if( pCallbackFrameRender != NULL ) - pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, - GetDXUTState().GetD3D9FrameRenderFuncUserContext() ); - - hr = pd3dDevice->Present( NULL, NULL, NULL, NULL ); - if( D3DERR_DEVICELOST == hr ) - { - GetDXUTState().SetDeviceLost( true ); - } - else if( D3DERR_DRIVERINTERNALERROR == hr ) - { - // When D3DERR_DRIVERINTERNALERROR is returned from Present(), - // the application can do one of the following: - // - // - End, with the pop-up window saying that the application cannot continue - // because of problems in the display adapter and that the user should - // contact the adapter manufacturer. - // - // - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same - // path as recovering from a lost device. If IDirect3DDevice9::Reset fails with - // D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message - // that the user should contact the adapter manufacturer. - // - // The framework attempts the path of resetting the device - // - GetDXUTState().SetDeviceLost( true ); - } - } - } - else { - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); - ID3D11DeviceContext *pDeferred = DXUTGetD3D11DeviceContext(); + auto pd3dDevice = DXUTGetD3D11Device(); + auto pDeferred = DXUTGetD3D11DeviceContext(); if( pd3dDevice ) { LPDXUTCALLBACKD3D11FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D11FrameRenderFunc(); - if( pCallbackFrameRender != NULL && + if( pCallbackFrameRender && !GetDXUTState().GetRenderingOccluded() ) { pCallbackFrameRender( pd3dDevice,pDeferred, fTime, fElapsedTime, @@ -1367,8 +1299,8 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM else dwFlags = GetDXUTState().GetCurrentDeviceSettings()->d3d11.PresentFlags; - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - hr = pSwapChain->Present( 0, GetDXUTState().GetCurrentDeviceSettings()->d3d11.PresentFlags ); + auto pSwapChain = DXUTGetDXGISwapChain(); + hr = pSwapChain->Present( 0, dwFlags ); if( DXGI_STATUS_OCCLUDED == hr ) { // There is a window covering our entire rendering area. @@ -1451,10 +1383,8 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM } } } - break; - case WM_GETMINMAXINFO: ( ( MINMAXINFO* )lParam )->ptMinTrackSize.x = DXUT_MIN_WINDOW_SIZE_X; ( ( MINMAXINFO* )lParam )->ptMinTrackSize.y = DXUT_MIN_WINDOW_SIZE_Y; @@ -1473,41 +1403,11 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM GetDXUTState().SetInSizeMove( false ); break; - case WM_MOUSEMOVE: - if( DXUTIsActive() && !DXUTIsWindowed() ) - { - if( DXUTIsCurrentDeviceD3D9() ) - { - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice ) - { - POINT ptCursor; - GetCursorPos( &ptCursor ); - pd3dDevice->SetCursorPosition( ptCursor.x, ptCursor.y, 0 ); - } - } - else - { - // For D3D11, no processing is necessary. D3D11 cursor - // is handled in the traditional Windows manner. - } - } - break; - case WM_SETCURSOR: if( DXUTIsActive() && !DXUTIsWindowed() ) { - if( DXUTIsCurrentDeviceD3D9() ) - { - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice && GetDXUTState().GetShowCursorWhenFullScreen() ) - pd3dDevice->ShowCursor( true ); - } - else - { - if( !GetDXUTState().GetShowCursorWhenFullScreen() ) - SetCursor( NULL ); - } + if( !GetDXUTState().GetShowCursorWhenFullScreen() ) + SetCursor( nullptr ); return true; // prevent Windows from setting cursor to window class cursor } @@ -1526,14 +1426,9 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM // is minimized and thus making the pause count wrong if( GetDXUTState().GetMinimizedWhileFullscreen() ) { - if( DXUTIsD3D9( GetDXUTState().GetCurrentDeviceSettings() ) ) - DXUTPause( false, false ); // Unpause since we're no longer minimized GetDXUTState().SetMinimizedWhileFullscreen( false ); - if( DXUTIsAppRenderingWithD3D11() ) - { - DXUTToggleFullScreen(); - } + DXUTToggleFullScreen(); } // Upon returning to this app, potentially disable shortcut keys @@ -1552,9 +1447,7 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM if( !DXUTIsWindowed() ) { // Going from full screen to a minimized state - ClipCursor( NULL ); // don't limit the cursor anymore - if( DXUTIsD3D9( GetDXUTState().GetCurrentDeviceSettings() ) ) - DXUTPause( true, true ); // Pause while we're minimized (take care not to pause twice by handling this message twice) + ClipCursor( nullptr ); // don't limit the cursor anymore GetDXUTState().SetMinimizedWhileFullscreen( true ); } @@ -1592,9 +1485,6 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM case WM_POWERBROADCAST: switch( wParam ) { -#ifndef PBT_APMQUERYSUSPEND -#define PBT_APMQUERYSUSPEND 0x0000 -#endif case PBT_APMQUERYSUSPEND: // At this point, the app should save any data for open // network connections, files, etc., and prepare to go into @@ -1602,9 +1492,6 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM // to handle this if desired. return true; -#ifndef PBT_APMRESUMESUSPEND -#define PBT_APMRESUMESUSPEND 0x0007 -#endif case PBT_APMRESUMESUSPEND: // At this point, the app should recover any data, network // connections, files, etc., and resume running from when @@ -1633,31 +1520,6 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM } break; - case WM_SYSKEYDOWN: - { - switch( wParam ) - { - case VK_RETURN: - { - if( GetDXUTState().GetHandleAltEnter() && DXUTIsAppRenderingWithD3D9() ) - { - // Toggle full screen upon alt-enter - DWORD dwMask = ( 1 << 29 ); - if( ( lParam & dwMask ) != 0 ) // Alt is down also - { - // Toggle the full screen/window mode - DXUTPause( true, true ); - DXUTToggleFullScreen(); - DXUTPause( false, false ); - return 0; - } - } - - } - } - break; - } - case WM_KEYDOWN: { switch( wParam ) @@ -1690,13 +1552,13 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM { HMENU hMenu; hMenu = GetMenu( hWnd ); - if( hMenu != NULL ) + if( hMenu ) DestroyMenu( hMenu ); DestroyWindow( hWnd ); - UnregisterClass( L"Direct3DWindowClass", NULL ); - GetDXUTState().SetHWNDFocus( NULL ); - GetDXUTState().SetHWNDDeviceFullScreen( NULL ); - GetDXUTState().SetHWNDDeviceWindowed( NULL ); + UnregisterClass( L"Direct3DWindowClass", nullptr ); + GetDXUTState().SetHWNDFocus( nullptr ); + GetDXUTState().SetHWNDDeviceFullScreen( nullptr ); + GetDXUTState().SetHWNDDeviceWindowed( nullptr ); return 0; } @@ -1708,7 +1570,7 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM // Don't allow the F10 key to act as a shortcut to the menu bar // by not passing these messages to the DefWindowProc only when // there's no menu present - if( !GetDXUTState().GetCallDefWindowProc() || GetDXUTState().GetMenu() == NULL && + if( !GetDXUTState().GetCallDefWindowProc() || !GetDXUTState().GetMenu() && ( uMsg == WM_SYSKEYDOWN || uMsg == WM_SYSKEYUP ) && wParam == VK_F10 ) return 0; else @@ -1717,10 +1579,10 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM //-------------------------------------------------------------------------------------- -// Handles app's message loop and rendering when idle. If DXUTCreateDevice() or DXUTSetD3D*Device() +// Handles app's message loop and rendering when idle. If DXUTCreateDevice() // has not already been called, it will call DXUTCreateWindow() with the default parameters. //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) +HRESULT WINAPI DXUTMainLoop( _In_opt_ HACCEL hAccel ) { HRESULT hr; @@ -1734,7 +1596,7 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) GetDXUTState().SetInsideMainloop( true ); - // If DXUTCreateDevice() or DXUTSetD3D*Device() has not already been called, + // If DXUTCreateDevice() has not already been called, // then call DXUTCreateDevice() with the default parameters. if( !GetDXUTState().GetDeviceCreated() ) { @@ -1745,7 +1607,7 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) return E_FAIL; // DXUTCreateDevice() must first succeed for this function to succeed } - hr = DXUTCreateDevice(D3D_FEATURE_LEVEL_10_0, true, 640, 480); + hr = DXUTCreateDevice(D3D_FEATURE_LEVEL_10_0, true, 800, 600); if( FAILED( hr ) ) { if( ( GetDXUTState().GetExitCode() == 0 ) || ( GetDXUTState().GetExitCode() == 10 ) ) @@ -1758,7 +1620,7 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) // DXUTInit() must have been called and succeeded for this function to proceed // DXUTCreateWindow() or DXUTSetWindow() must have been called and succeeded for this function to proceed - // DXUTCreateDevice() or DXUTCreateDeviceFromSettings() or DXUTSetD3D*Device() must have been called and succeeded for this function to proceed + // DXUTCreateDevice() or DXUTCreateDeviceFromSettings() must have been called and succeeded for this function to proceed if( !GetDXUTState().GetDXUTInited() || !GetDXUTState().GetWindowCreated() || !GetDXUTState().GetDeviceCreated() ) { if( ( GetDXUTState().GetExitCode() == 0 ) || ( GetDXUTState().GetExitCode() == 10 ) ) @@ -1770,17 +1632,17 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) bool bGotMsg; MSG msg; msg.message = WM_NULL; - PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE ); + PeekMessage( &msg, nullptr, 0U, 0U, PM_NOREMOVE ); while( WM_QUIT != msg.message ) { // Use PeekMessage() so we can use idle time to render the scene. - bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 ); + bGotMsg = ( PeekMessage( &msg, nullptr, 0U, 0U, PM_REMOVE ) != 0 ); if( bGotMsg ) { // Translate and dispatch the message - if( hAccel == NULL || hWnd == NULL || + if( !hAccel || !hWnd || 0 == TranslateAccelerator( hWnd, hAccel, &msg ) ) { TranslateMessage( &msg ); @@ -1795,7 +1657,7 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) } // Cleanup the accelerator table - if( hAccel != NULL ) + if( hAccel ) DestroyAcceleratorTable( hAccel ); GetDXUTState().SetInsideMainloop( false ); @@ -1809,13 +1671,14 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) // Direct3D section //====================================================================================== //====================================================================================== -HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed, int nSuggestedWidth, int nSuggestedHeight) { - HRESULT hr = S_OK; - +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed, int nSuggestedWidth, int nSuggestedHeight) +{ + HRESULT hr = S_OK; // Not allowed to call this from inside the device callbacks if( GetDXUTState().GetInsideDeviceCallback() ) - return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL ); + return DXUT_ERR_MSGBOX( L"DXUTCreateDevice", E_FAIL ); GetDXUTState().SetDeviceCreateCalled( true ); @@ -1835,91 +1698,77 @@ HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed, int nS return hr; } - DXUTDeviceSettings deviceSettings ; + DXUTDeviceSettings deviceSettings; DXUTApplyDefaultDeviceSettings(&deviceSettings); deviceSettings.MinimumFeatureLevel = reqFL; deviceSettings.d3d11.sd.BufferDesc.Width = nSuggestedWidth; deviceSettings.d3d11.sd.BufferDesc.Height = nSuggestedHeight; deviceSettings.d3d11.sd.Windowed = bWindowed; - deviceSettings.d3d9.pp.Windowed = bWindowed; - deviceSettings.d3d9.pp.BackBufferWidth= nSuggestedWidth; - deviceSettings.d3d9.pp.BackBufferHeight = nSuggestedHeight; - - bool bAppSupportsD3D9 = DXUTDoesAppSupportD3D9(); - bool bAppSupportsD3D11 = DXUTDoesAppSupportD3D11(); - - if (bAppSupportsD3D11) { - deviceSettings.ver = DXUT_D3D11_DEVICE; - } - else if (bAppSupportsD3D9) { - deviceSettings.ver = DXUT_D3D9_DEVICE; - } - DXUTUpdateDeviceSettingsWithOverrides(&deviceSettings); + GetDXUTState().SetWindowBackBufferWidthAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Width); + GetDXUTState().SetWindowBackBufferHeightAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Height); + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Width); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Height); + // Change to a Direct3D device created from the new device settings. // If there is an existing device, then either reset or recreated the scene - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, true ); + hr = DXUTChangeDevice( &deviceSettings, true ); - if ( hr == DXUTERR_NODIRECT3D11 && GetDXUTState().GetMessageWhenD3D11NotAvailable() ) { - + if ( hr == DXUTERR_NODIRECT3D && GetDXUTState().GetMessageWhenD3D11NotAvailable() ) + { OSVERSIONINFOEX osv; memset( &osv, 0, sizeof(osv) ); osv.dwOSVersionInfoSize = sizeof(osv); +#pragma warning( suppress : 4996 28159 ) GetVersionEx( (LPOSVERSIONINFO)&osv ); - if ( ( osv.dwMajorVersion > 6 ) || ( osv.dwMajorVersion == 6 && osv.dwMinorVersion >= 1 ) || ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 && osv.dwBuildNumber > 6002 ) ) { - MessageBox( 0, L"Direct3D 11 components were not found.", L"Error", MB_ICONEXCLAMATION ); // This should not happen, but is here for completeness as the system could be // corrupted or some future OS version could pull D3D11.DLL for some reason } else if ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 && osv.dwBuildNumber == 6002 ) { - MessageBox( 0, L"Direct3D 11 components were not found, but are available for"\ L" this version of Windows.\n"\ L"For details see Microsoft Knowledge Base Article #971644\n"\ L"http://go.microsoft.com/fwlink/?LinkId=160189", L"Error", MB_ICONEXCLAMATION ); - } else if ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 ) { MessageBox( 0, L"Direct3D 11 components were not found. Please install the latest Service Pack.\n"\ L"For details see Microsoft Knowledge Base Article #935791\n"\ L"http://support.microsoft.com/kb/935791/", L"Error", MB_ICONEXCLAMATION ); - } else { MessageBox( 0, L"Direct3D 11 is not supported on this OS.", L"Error", MB_ICONEXCLAMATION ); } - - - } - if( FAILED( hr ) ) return hr; return hr; } + //-------------------------------------------------------------------------------------- // Tells the framework to change to a device created from the passed in device settings // If DXUTCreateWindow() has not already been called, it will call it with the // default parameters. Instead of calling this, you can call DXUTCreateDevice() -// or DXUTSetD3D*Device() //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bPreserveInput, - bool bClipWindowToSingleAdapter ) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bClipWindowToSingleAdapter ) { + if ( !pDeviceSettings ) + return E_INVALIDARG; + HRESULT hr; GetDXUTState().SetDeviceCreateCalled( true ); @@ -1939,12 +1788,17 @@ HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings if( FAILED( hr ) ) return hr; } + DXUTUpdateDeviceSettingsWithOverrides(pDeviceSettings); - + GetDXUTState().SetWindowBackBufferWidthAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Width); + GetDXUTState().SetWindowBackBufferHeightAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Height); + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Width); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Height); + // Change to a Direct3D device created from the new device settings. // If there is an existing device, then either reset or recreate the scene - hr = DXUTChangeDevice( pDeviceSettings, NULL, NULL, false, bClipWindowToSingleAdapter ); + hr = DXUTChangeDevice( pDeviceSettings, bClipWindowToSingleAdapter ); if( FAILED( hr ) ) return hr; @@ -1958,46 +1812,33 @@ HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings // also remembers and restores the window state if toggling between windowed and fullscreen // as well as sets the proper window and system state for switching to the new device. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, - IDirect3DDevice9* pd3d9DeviceFromApp, - ID3D11Device* pd3d11DeviceFromApp, - bool bForceRecreate, bool bClipWindowToSingleAdapter ) + bool bClipWindowToSingleAdapter ) { + if ( GetDXUTState().GetReleasingSwapChain() ) + return S_FALSE; + HRESULT hr = S_OK; DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if( !pNewDeviceSettings ) return S_FALSE; - - - if ( pNewDeviceSettings->ver == DXUT_D3D11_DEVICE ) { - hr = DXUTDelayLoadDXGI(); - } - - - if ( pNewDeviceSettings->ver == DXUT_D3D9_DEVICE || - ( FAILED( hr ) && DXUTDoesAppSupportD3D9() ) ) { - hr = DXUTDelayLoadD3D9(); - pNewDeviceSettings->ver = DXUT_D3D9_DEVICE; - if ( !FAILED( hr ) ) { - pNewDeviceSettings->ver = DXUT_D3D9_DEVICE; - } - } + hr = DXUTDelayLoadDXGI(); if( FAILED( hr ) ) return hr; // Make a copy of the pNewDeviceSettings on the heap - DXUTDeviceSettings* pNewDeviceSettingsOnHeap = new DXUTDeviceSettings; - if( pNewDeviceSettingsOnHeap == NULL ) + DXUTDeviceSettings* pNewDeviceSettingsOnHeap = new (std::nothrow) DXUTDeviceSettings; + if( !pNewDeviceSettingsOnHeap ) return E_OUTOFMEMORY; memcpy( pNewDeviceSettingsOnHeap, pNewDeviceSettings, sizeof( DXUTDeviceSettings ) ); pNewDeviceSettings = pNewDeviceSettingsOnHeap; - GetDXUTState().SetCurrentDeviceSettings(pNewDeviceSettingsOnHeap); - DXUTSnapDeviceSettingsToEnumDevice(pNewDeviceSettingsOnHeap, false); + hr = DXUTSnapDeviceSettingsToEnumDevice(pNewDeviceSettingsOnHeap, false); if( FAILED( hr ) ) // the call will fail if no valid devices were found { @@ -2008,19 +1849,19 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, // If the ModifyDeviceSettings callback is non-NULL, then call it to let the app // change the settings or reject the device change by returning false. LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings = GetDXUTState().GetModifyDeviceSettingsFunc(); - if( pCallbackModifyDeviceSettings && pd3d9DeviceFromApp == NULL ) + if( pCallbackModifyDeviceSettings ) { bool bContinue = pCallbackModifyDeviceSettings( pNewDeviceSettings, GetDXUTState().GetModifyDeviceSettingsFuncUserContext() ); if( !bContinue ) { // The app rejected the device change by returning false, so just use the current device if there is one. - if( pOldDeviceSettings == NULL ) + if( !pOldDeviceSettings ) DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES ); SAFE_DELETE( pNewDeviceSettings ); return E_ABORT; } - if( GetDXUTState().GetD3D9() == NULL && GetDXUTState().GetDXGIFactory() == NULL ) // if DXUTShutdown() was called in the modify callback, just return + if( !GetDXUTState().GetDXGIFactory() ) // if DXUTShutdown() was called in the modify callback, just return { SAFE_DELETE( pNewDeviceSettings ); return S_FALSE; @@ -2039,13 +1880,6 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, DXUTPause( true, true ); - // When a WM_SIZE message is received, it calls DXUTCheckForWindowSizeChange(). - // A WM_SIZE message might be sent when adjusting the window, so tell - // DXUTCheckForWindowSizeChange() to ignore size changes temporarily - if( DXUTIsCurrentDeviceD3D9() ) - GetDXUTState().SetIgnoreSizeChange( true ); - - // Take note if the backbuffer width & height are 0 now as they will change after pd3dDevice->Reset() bool bKeepCurrentWindowSize = false; if( DXUTGetBackBufferWidthFromDS( pNewDeviceSettings ) == 0 && @@ -2056,125 +1890,30 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, // Before reset ///////////////////////// - // If we are using D3D9, adjust window style when switching from windowed to fullscreen and - // vice versa. Note that this is not necessary in D3D11 because DXGI handles this. If both - // DXUT and DXGI handle this, incorrect behavior would result. - if( DXUTIsCurrentDeviceD3D9() ) + if( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) ) { - if( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) ) - { - // Going to windowed mode - - if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) - { - // Going from fullscreen -> windowed - GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - - // Restore windowed mode style - SetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE, GetDXUTState().GetWindowedStyleAtModeChange() ); - } - - // If different device windows are used for windowed mode and fullscreen mode, - // hide the fullscreen window so that it doesn't obscure the screen. - if( DXUTGetHWNDDeviceFullScreen() != DXUTGetHWNDDeviceWindowed() ) - ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE ); - - // If using the same window for windowed and fullscreen mode, reattach menu if one exists - if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() ) - { - if( GetDXUTState().GetMenu() != NULL ) - SetMenu( DXUTGetHWNDDeviceWindowed(), GetDXUTState().GetMenu() ); - } - } - else + // Going to windowed mode + if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) { - // Going to fullscreen mode - - if( pOldDeviceSettings == NULL || ( pOldDeviceSettings && DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) ) - { - // Transistioning to full screen mode from a standard window so - // save current window position/size/style now in case the user toggles to windowed mode later - WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement(); - ZeroMemory( pwp, sizeof( WINDOWPLACEMENT ) ); - pwp->length = sizeof( WINDOWPLACEMENT ); - GetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp ); - bool bIsTopmost = ( ( GetWindowLong( DXUTGetHWNDDeviceWindowed(), - GWL_EXSTYLE ) & WS_EX_TOPMOST ) != 0 ); - GetDXUTState().SetTopmostWhileWindowed( bIsTopmost ); - DWORD dwStyle = GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ); - dwStyle &= ~WS_MAXIMIZE & ~WS_MINIMIZE; // remove minimize/maximize style - GetDXUTState().SetWindowedStyleAtModeChange( dwStyle ); - if( pOldDeviceSettings ) - { - GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - } - } - - // Hide the window to avoid animation of blank windows - ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE ); - - // Set FS window style - SetWindowLong( DXUTGetHWNDDeviceFullScreen(), GWL_STYLE, WS_POPUP | WS_SYSMENU ); - - // If using the same window for windowed and fullscreen mode, save and remove menu - if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() ) - { - HMENU hMenu = GetMenu( DXUTGetHWNDDeviceFullScreen() ); - GetDXUTState().SetMenu( hMenu ); - SetMenu( DXUTGetHWNDDeviceFullScreen(), NULL ); - } - - WINDOWPLACEMENT wpFullscreen; - ZeroMemory( &wpFullscreen, sizeof( WINDOWPLACEMENT ) ); - wpFullscreen.length = sizeof( WINDOWPLACEMENT ); - GetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen ); - if( ( wpFullscreen.flags & WPF_RESTORETOMAXIMIZED ) != 0 ) - { - // Restore the window to normal if the window was maximized then minimized. This causes the - // WPF_RESTORETOMAXIMIZED flag to be set which will cause SW_RESTORE to restore the - // window from minimized to maxmized which isn't what we want - wpFullscreen.flags &= ~WPF_RESTORETOMAXIMIZED; - wpFullscreen.showCmd = SW_RESTORE; - SetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen ); - } + // Going from fullscreen -> windowed + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( + pOldDeviceSettings ) ); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( + pOldDeviceSettings ) ); } } else { - if( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) ) - { - // Going to windowed mode - if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) - { - // Going from fullscreen -> windowed - GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - //DXGI should handle this, but in the case where switching from d3d9 full screen to windowed d3d11 it does not. - SetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE, GetDXUTState().GetWindowedStyleAtModeChange() ); - - } - } - else + // Going to fullscreen mode + if( !pOldDeviceSettings || ( pOldDeviceSettings && DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) ) { - // Going to fullscreen mode - if( pOldDeviceSettings == NULL || ( pOldDeviceSettings && DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) ) + // Transistioning to full screen mode from a standard window so + if( pOldDeviceSettings ) { - // Transistioning to full screen mode from a standard window so - if( pOldDeviceSettings ) - { - GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - } + GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( + pOldDeviceSettings ) ); + GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( + pOldDeviceSettings ) ); } } } @@ -2183,12 +1922,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, DXUTCleanup3DEnvironment( false ); // Create the D3D device and call the app's device callbacks - if( DXUTIsD3D9( pNewDeviceSettings ) ) { - hr = DXUTCreate3DEnvironment9( pd3d9DeviceFromApp ); - } - else { - hr = DXUTCreate3DEnvironment11( pd3d11DeviceFromApp ); - } + hr = DXUTCreate3DEnvironment11(); if( FAILED( hr ) ) { SAFE_DELETE( pOldDeviceSettings ); @@ -2220,7 +1954,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, // It is important to adjust the window size // after resetting the device rather than beforehand to ensure // that the monitor resolution is correct and does not limit the size of the new window. - WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement(); + auto pwp = GetDXUTState().GetWindowedPlacement(); SetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp ); // Also restore the z-order of window to previous state @@ -2243,8 +1977,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, // Window is currently minimized. To tell if it needs to resize, // get the client rect of window when its restored the // hard way using GetWindowPlacement() - WINDOWPLACEMENT wp; - ZeroMemory( &wp, sizeof( WINDOWPLACEMENT ) ); + WINDOWPLACEMENT wp = {}; wp.length = sizeof( WINDOWPLACEMENT ); GetWindowPlacement( DXUTGetHWNDDeviceWindowed(), &wp ); @@ -2265,8 +1998,8 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, { // Use wp.rcNormalPosition to get the client rect, but wp.rcNormalPosition // includes the window frame so subtract it - RECT rcFrame = {0}; - AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != NULL ); + RECT rcFrame = {}; + AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != 0 ); LONG nFrameWidth = rcFrame.right - rcFrame.left; LONG nFrameHeight = rcFrame.bottom - rcFrame.top; nClientWidth = ( UINT )( wp.rcNormalPosition.right - wp.rcNormalPosition.left - nFrameWidth ); @@ -2364,7 +2097,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, rcResizedWindow.top = 0; rcResizedWindow.bottom = nClientHeight; AdjustWindowRect( &rcResizedWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), - GetDXUTState().GetMenu() != NULL ); + GetDXUTState().GetMenu() != 0 ); int nWindowWidth = rcResizedWindow.right - rcResizedWindow.left; int nWindowHeight = rcResizedWindow.bottom - rcResizedWindow.top; @@ -2397,10 +2130,10 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, else { // Make a window rect with a client rect that is the same size as the backbuffer - RECT rcWindow = {0}; + RECT rcWindow = {}; rcWindow.right = (long)( DXUTGetBackBufferWidthFromDS(pNewDeviceSettings) ); rcWindow.bottom = (long)( DXUTGetBackBufferHeightFromDS(pNewDeviceSettings) ); - AdjustWindowRect( &rcWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != NULL ); + AdjustWindowRect( &rcWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != 0 ); // Resize the window. It is important to adjust the window size // after resetting the device rather than beforehand to ensure @@ -2423,11 +2156,11 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, { // If its different, then resize the backbuffer again. This time create a backbuffer that matches the // client rect of the current window w/o resizing the window. - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferWidth = 0; else deviceSettings.d3d11.sd.BufferDesc.Width = 0; - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferHeight = 0; else deviceSettings.d3d11.sd.BufferDesc.Height = 0; + auto deviceSettings = DXUTGetDeviceSettings(); + deviceSettings.d3d11.sd.BufferDesc.Width = 0; + deviceSettings.d3d11.sd.BufferDesc.Height = 0; - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, bClipWindowToSingleAdapter ); + hr = DXUTChangeDevice( &deviceSettings, bClipWindowToSingleAdapter ); if( FAILED( hr ) ) { SAFE_DELETE( pOldDeviceSettings ); @@ -2440,8 +2173,8 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, } //if (DXUTGetIsWindowedFromDS( pNewDeviceSettings )) { - // RECT rcFrame = {0}; - // AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != NULL ); + // RECT rcFrame = {}; + // AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() ); // } // Make the window visible @@ -2468,959 +2201,136 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, //-------------------------------------------------------------------------------------- HRESULT DXUTDelayLoadDXGI() { - IDXGIFactory1* pDXGIFactory = GetDXUTState().GetDXGIFactory(); - if( pDXGIFactory == NULL ) + auto pDXGIFactory = GetDXUTState().GetDXGIFactory(); + if( !pDXGIFactory ) { - DXUT_Dynamic_CreateDXGIFactory1( __uuidof( IDXGIFactory1 ), ( LPVOID* )&pDXGIFactory ); - GetDXUTState().SetDXGIFactory( pDXGIFactory ); - if( pDXGIFactory == NULL ) - { - // If still NULL, then DXGI is not availible - GetDXUTState().SetD3D11Available( false ); - return DXUTERR_NODIRECT3D11; - } - - // DXGI 1.1 implies Direct3D 11 - - GetDXUTState().SetD3D11Available( true ); - } - - return S_OK; -} - + HRESULT hr = DXUT_Dynamic_CreateDXGIFactory1( IID_PPV_ARGS(&pDXGIFactory) ); + if ( FAILED(hr) ) + return hr; -//-------------------------------------------------------------------------------------- -// Creates a Direct3D object if one has not already been created -//-------------------------------------------------------------------------------------- -HRESULT DXUTDelayLoadD3D9() -{ - IDirect3D9* pD3D = GetDXUTState().GetD3D9(); - if( pD3D == NULL ) - { - // This may fail if Direct3D 9 isn't installed - // This may also fail if the Direct3D headers are somehow out of sync with the installed Direct3D DLLs - pD3D = DXUT_Dynamic_Direct3DCreate9( D3D_SDK_VERSION ); - if( pD3D == NULL ) + GetDXUTState().SetDXGIFactory( pDXGIFactory ); + if( !pDXGIFactory ) { - // If still NULL, then D3D9 is not availible return DXUTERR_NODIRECT3D; } - GetDXUTState().SetD3D9( pD3D ); + // DXGI 1.1 implies Direct3D 11 } return S_OK; } - //-------------------------------------------------------------------------------------- // Updates the device settings with default values.. //-------------------------------------------------------------------------------------- -void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pDeviceSettings ) +void DXUTUpdateDeviceSettingsWithOverrides( _Inout_ DXUTDeviceSettings* pDeviceSettings ) { // Override with settings from the command line if( GetDXUTState().GetOverrideWidth() != 0 ) { - pDeviceSettings->d3d9.pp.BackBufferWidth = GetDXUTState().GetOverrideWidth(); pDeviceSettings->d3d11.sd.BufferDesc.Width = GetDXUTState().GetOverrideWidth(); } if( GetDXUTState().GetOverrideHeight() != 0 ) { - pDeviceSettings->d3d9.pp.BackBufferHeight = GetDXUTState().GetOverrideHeight(); pDeviceSettings->d3d11.sd.BufferDesc.Height = GetDXUTState().GetOverrideHeight(); } if( GetDXUTState().GetOverrideAdapterOrdinal() != -1 ) { - pDeviceSettings->d3d9.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal(); pDeviceSettings->d3d11.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal(); } if( GetDXUTState().GetOverrideFullScreen() ) { - pDeviceSettings->d3d9.pp.Windowed = FALSE; pDeviceSettings->d3d11.sd.Windowed = FALSE; } - if( GetDXUTState().GetOverrideWindowed() ) { - pDeviceSettings->d3d9.pp.Windowed = TRUE; + if( GetDXUTState().GetOverrideWindowed() ) + { pDeviceSettings->d3d11.sd.Windowed = TRUE; } if( GetDXUTState().GetOverrideForceHAL() ) { - pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_HAL; pDeviceSettings->d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; } if( GetDXUTState().GetOverrideForceREF() ) { - pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF; pDeviceSettings->d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; } + if( GetDXUTState().GetOverrideForceWARP() ) + { + pDeviceSettings->d3d11.DriverType = D3D_DRIVER_TYPE_WARP; + pDeviceSettings->d3d11.sd.Windowed = TRUE; + } + if( GetDXUTState().GetOverrideForceVsync() == 0 ) { - pDeviceSettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; pDeviceSettings->d3d11.SyncInterval = 0; } else if( GetDXUTState().GetOverrideForceVsync() == 1 ) { - pDeviceSettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; pDeviceSettings->d3d11.SyncInterval = 1; } - - if( GetDXUTState().GetOverrideForceAPI() != -1 ) + + if (GetDXUTState().GetOverrideForceFeatureLevel() != 0) { - if( GetDXUTState().GetOverrideForceAPI() == 9 ) - { - pDeviceSettings->ver = DXUT_D3D9_DEVICE; - } - else if( GetDXUTState().GetOverrideForceAPI() == 11 ) - { - pDeviceSettings->ver = DXUT_D3D11_DEVICE; - } - } - - if (GetDXUTState().GetOverrideForceFeatureLevel() != 0) { - pDeviceSettings->d3d11.DeviceFeatureLevel = (D3D_FEATURE_LEVEL)GetDXUTState().GetOverrideForceFeatureLevel(); + pDeviceSettings->d3d11.DeviceFeatureLevel = GetDXUTState().GetOverrideForceFeatureLevel(); } } //-------------------------------------------------------------------------------------- -// Allows the app to explictly state if it supports D3D9 or D3D11. Typically -// calling this is not needed as DXUT will auto-detect this based on the callbacks set. +// Sets the viewport, render target view, and depth stencil view. //-------------------------------------------------------------------------------------- -void WINAPI DXUTSetD3DVersionSupport( bool bAppCanUseD3D9, bool bAppCanUseD3D11 ) +HRESULT WINAPI DXUTSetupD3D11Views( _In_ ID3D11DeviceContext* pd3dDeviceContext ) { - GetDXUTState().SetUseD3DVersionOverride( true ); - GetDXUTState().SetAppSupportsD3D9Override( bAppCanUseD3D9 ); - GetDXUTState().SetAppSupportsD3D11Override( bAppCanUseD3D11 ); -} + HRESULT hr = S_OK; + + // Setup the viewport to match the backbuffer + D3D11_VIEWPORT vp; + vp.Width = (FLOAT)DXUTGetDXGIBackBufferSurfaceDesc()->Width; + vp.Height = (FLOAT)DXUTGetDXGIBackBufferSurfaceDesc()->Height; + vp.MinDepth = 0; + vp.MaxDepth = 1; + vp.TopLeftX = 0; + vp.TopLeftY = 0; + pd3dDeviceContext->RSSetViewports( 1, &vp ); + // Set the render targets + auto pRTV = GetDXUTState().GetD3D11RenderTargetView(); + auto pDSV = GetDXUTState().GetD3D11DepthStencilView(); + pd3dDeviceContext->OMSetRenderTargets( 1, &pRTV, pDSV ); -//-------------------------------------------------------------------------------------- -// Returns true if app has registered any D3D9 callbacks or -// used the DXUTSetD3DVersionSupport API and passed true for bAppCanUseD3D9 -//-------------------------------------------------------------------------------------- -bool WINAPI DXUTDoesAppSupportD3D9() -{ - if( GetDXUTState().GetUseD3DVersionOverride() ) - return GetDXUTState().GetAppSupportsD3D9Override(); - else - return GetDXUTState().GetIsD3D9DeviceAcceptableFunc() || - GetDXUTState().GetD3D9DeviceCreatedFunc() || - GetDXUTState().GetD3D9DeviceResetFunc() || - GetDXUTState().GetD3D9DeviceLostFunc() || - GetDXUTState().GetD3D9DeviceDestroyedFunc() || - GetDXUTState().GetD3D9FrameRenderFunc(); + return hr; } //-------------------------------------------------------------------------------------- -// Returns true if app has registered any D3D11 callbacks or -// used the DXUTSetD3DVersionSupport API and passed true for bAppCanUseD3D11 -//-------------------------------------------------------------------------------------- -bool WINAPI DXUTDoesAppSupportD3D11() -{ - if( GetDXUTState().GetUseD3DVersionOverride() ) - return GetDXUTState().GetAppSupportsD3D11Override(); - else - return GetDXUTState().GetIsD3D11DeviceAcceptableFunc() || - GetDXUTState().GetD3D11DeviceCreatedFunc() || - GetDXUTState().GetD3D11SwapChainResizedFunc() || - GetDXUTState().GetD3D11FrameRenderFunc() || - GetDXUTState().GetD3D11SwapChainReleasingFunc() || - GetDXUTState().GetD3D11DeviceDestroyedFunc(); -} - - -//====================================================================================== -//====================================================================================== -// Direct3D 9 section -//====================================================================================== -//====================================================================================== - - -//-------------------------------------------------------------------------------------- -// Passes a previously created Direct3D9 device for use by the framework. -// If DXUTCreateWindow() has not already been called, it will call it with the -// default parameters. Instead of calling this, you can call DXUTCreateDevice() or -// DXUTCreateDeviceFromSettings() -//-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTSetD3D9Device( IDirect3DDevice9* pd3dDevice ) -{ - HRESULT hr; - - if( pd3dDevice == NULL ) - return DXUT_ERR_MSGBOX( L"DXUTSetD3D9Device", E_INVALIDARG ); - - // Not allowed to call this from inside the device callbacks - if( GetDXUTState().GetInsideDeviceCallback() ) - return DXUT_ERR_MSGBOX( L"DXUTSetD3D9Device", E_FAIL ); - - GetDXUTState().SetDeviceCreateCalled( true ); - - // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, - // then call DXUTCreateWindow() with the default parameters. - if( !GetDXUTState().GetWindowCreated() ) - { - // If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail. - // DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed - if( GetDXUTState().GetWindowCreateCalled() ) - return E_FAIL; - - // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then - // automatically call DXUTCreateWindow() with default params - hr = DXUTCreateWindow(); - if( FAILED( hr ) ) - return hr; - } - - DXUTDeviceSettings DeviceSettings; - ZeroMemory( &DeviceSettings, sizeof( DXUTDeviceSettings ) ); - DeviceSettings.ver = DXUT_D3D9_DEVICE; - - // Get the present params from the swap chain - IDirect3DSurface9* pBackBuffer = NULL; - hr = pd3dDevice->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ); - if( SUCCEEDED( hr ) ) - { - IDirect3DSwapChain9* pSwapChain = NULL; - hr = pBackBuffer->GetContainer( IID_IDirect3DSwapChain9, ( void** )&pSwapChain ); - if( SUCCEEDED( hr ) ) - { - pSwapChain->GetPresentParameters( &DeviceSettings.d3d9.pp ); - SAFE_RELEASE( pSwapChain ); - } - - SAFE_RELEASE( pBackBuffer ); - } - - D3DDEVICE_CREATION_PARAMETERS d3dCreationParams; - pd3dDevice->GetCreationParameters( &d3dCreationParams ); - - // Fill out the rest of the device settings struct - DeviceSettings.d3d9.AdapterOrdinal = d3dCreationParams.AdapterOrdinal; - DeviceSettings.d3d9.DeviceType = d3dCreationParams.DeviceType; - DXUTFindD3D9AdapterFormat( DeviceSettings.d3d9.AdapterOrdinal, DeviceSettings.d3d9.DeviceType, - DeviceSettings.d3d9.pp.BackBufferFormat, DeviceSettings.d3d9.pp.Windowed, - &DeviceSettings.d3d9.AdapterFormat ); - DeviceSettings.d3d9.BehaviorFlags = d3dCreationParams.BehaviorFlags; - - // Change to the Direct3D device passed in - hr = DXUTChangeDevice( &DeviceSettings, pd3dDevice, NULL, false, false ); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -// Creates the 3D environment -//-------------------------------------------------------------------------------------- -HRESULT DXUTCreate3DEnvironment9( IDirect3DDevice9* pd3dDeviceFromApp ) -{ - HRESULT hr = S_OK; - - IDirect3DDevice9* pd3dDevice = NULL; - DXUTDeviceSettings* pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - assert( pNewDeviceSettings != NULL ); - - // Only create a Direct3D device if one hasn't been supplied by the app - if( pd3dDeviceFromApp == NULL ) - { - // Try to create the device with the chosen settings - IDirect3D9* pD3D = DXUTGetD3D9Object(); - assert( pD3D != NULL ); - hr = pD3D->CreateDevice( pNewDeviceSettings->d3d9.AdapterOrdinal, pNewDeviceSettings->d3d9.DeviceType, - DXUTGetHWNDFocus(), pNewDeviceSettings->d3d9.BehaviorFlags, - &pNewDeviceSettings->d3d9.pp, &pd3dDevice ); - if( hr == D3DERR_DEVICELOST ) - { - GetDXUTState().SetDeviceLost( true ); - return S_OK; - } - else if( FAILED( hr ) ) - { - DXUT_ERR( L"CreateDevice", hr ); - return DXUTERR_CREATINGDEVICE; - } - } - else - { - pd3dDeviceFromApp->AddRef(); - pd3dDevice = pd3dDeviceFromApp; - } - - GetDXUTState().SetD3D9Device( pd3dDevice ); - - // If switching to REF, set the exit code to 10. If switching to HAL and exit code was 10, then set it back to 0. - if( pNewDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF && GetDXUTState().GetExitCode() == 0 ) - GetDXUTState().SetExitCode( 10 ); - else if( pNewDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_HAL && GetDXUTState().GetExitCode() == 10 ) - GetDXUTState().SetExitCode( 0 ); - - // Update back buffer desc before calling app's device callbacks - DXUTUpdateBackBufferDesc(); - - // Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state) - DXUTSetupCursor(); - - // Update GetDXUTState()'s copy of D3D caps - D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps(); - pd3dDevice->GetDeviceCaps( pd3dCaps ); - - // Update the device stats text - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - assert( pd3dEnum != NULL ); - CD3D9EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d9.AdapterOrdinal ); - DXUTUpdateD3D9DeviceStats( pNewDeviceSettings->d3d9.DeviceType, - pNewDeviceSettings->d3d9.BehaviorFlags, - &pAdapterInfo->AdapterIdentifier ); - - // Call the app's device created callback if non-NULL - const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc(); - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICECREATED pCallbackDeviceCreated = GetDXUTState().GetD3D9DeviceCreatedFunc(); - hr = S_OK; - if( pCallbackDeviceCreated != NULL ) - hr = pCallbackDeviceCreated( DXUTGetD3D9Device(), pBackBufferSurfaceDesc, - GetDXUTState().GetD3D9DeviceCreatedFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D9Device() == NULL ) // Handle DXUTShutdown from inside callback - return E_FAIL; - if( FAILED( hr ) ) - { - DXUT_ERR( L"DeviceCreated callback", hr ); - return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_CREATINGDEVICEOBJECTS; - } - GetDXUTState().SetDeviceObjectsCreated( true ); - - // Call the app's device reset callback if non-NULL - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICERESET pCallbackDeviceReset = GetDXUTState().GetD3D9DeviceResetFunc(); - hr = S_OK; - if( pCallbackDeviceReset != NULL ) - hr = pCallbackDeviceReset( DXUTGetD3D9Device(), pBackBufferSurfaceDesc, - GetDXUTState().GetD3D9DeviceResetFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D9Device() == NULL ) // Handle DXUTShutdown from inside callback - return E_FAIL; - if( FAILED( hr ) ) - { - DXUT_ERR( L"DeviceReset callback", hr ); - return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_RESETTINGDEVICEOBJECTS; - } - GetDXUTState().SetDeviceObjectsReset( true ); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -// Resets the 3D environment by: -// - Calls the device lost callback -// - Resets the device -// - Stores the back buffer description -// - Sets up the full screen Direct3D cursor if requested -// - Calls the device reset callback -//-------------------------------------------------------------------------------------- -HRESULT DXUTReset3DEnvironment9() -{ - HRESULT hr; - - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - assert( pd3dDevice != NULL ); - - // Call the app's device lost callback - if( GetDXUTState().GetDeviceObjectsReset() == true ) - { - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc(); - if( pCallbackDeviceLost != NULL ) - pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() ); - GetDXUTState().SetDeviceObjectsReset( false ); - GetDXUTState().SetInsideDeviceCallback( false ); - } - - // Reset the device - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - hr = pd3dDevice->Reset( &pDeviceSettings->d3d9.pp ); - if( FAILED( hr ) ) - { - if( hr == D3DERR_DEVICELOST ) - return D3DERR_DEVICELOST; // Reset could legitimately fail if the device is lost - else - return DXUT_ERR( L"Reset", DXUTERR_RESETTINGDEVICE ); - } - - // Update back buffer desc before calling app's device callbacks - DXUTUpdateBackBufferDesc(); - - // Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state) - DXUTSetupCursor(); - - // Call the app's OnDeviceReset callback - GetDXUTState().SetInsideDeviceCallback( true ); - const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc(); - LPDXUTCALLBACKD3D9DEVICERESET pCallbackDeviceReset = GetDXUTState().GetD3D9DeviceResetFunc(); - hr = S_OK; - if( pCallbackDeviceReset != NULL ) - hr = pCallbackDeviceReset( pd3dDevice, pBackBufferSurfaceDesc, - GetDXUTState().GetD3D9DeviceResetFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - if( FAILED( hr ) ) - { - // If callback failed, cleanup - DXUT_ERR( L"DeviceResetCallback", hr ); - if( hr != DXUTERR_MEDIANOTFOUND ) - hr = DXUTERR_RESETTINGDEVICEOBJECTS; - - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc(); - if( pCallbackDeviceLost != NULL ) - pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - return hr; - } - - // Success - GetDXUTState().SetDeviceObjectsReset( true ); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -// Render the 3D environment by: -// - Checking if the device is lost and trying to reset it if it is -// - Get the elapsed time since the last frame -// - Calling the app's framemove and render callback -// - Calling Present() -//-------------------------------------------------------------------------------------- -void DXUTRender3DEnvironment9() -{ - HRESULT hr; - - if( GetDXUTState().GetDeviceLost() || DXUTIsRenderingPaused() || !DXUTIsActive() ) - { - // Window is minimized or paused so yield CPU time to other processes - Sleep( 50 ); - } - - // If no device created yet because device was lost (ie. another fullscreen exclusive device exists), - // then wait and try to create every so often. - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( NULL == pd3dDevice ) - { - if( GetDXUTState().GetDeviceLost() ) - { - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTChangeDevice( &deviceSettings, NULL, NULL, false, true ); - } - - return; - } - - if( GetDXUTState().GetDeviceLost() && !GetDXUTState().GetRenderingPaused() ) - { - // Test the cooperative level to see if it's okay to render. - if( FAILED( hr = pd3dDevice->TestCooperativeLevel() ) ) - { - if( D3DERR_DEVICELOST == hr ) - { - // The device has been lost but cannot be reset at this time. - // So wait until it can be reset. - return; - } - - // If we are windowed, read the desktop format and - // ensure that the Direct3D device is using the same format - // since the user could have changed the desktop bitdepth - if( DXUTIsWindowed() ) - { - D3DDISPLAYMODE adapterDesktopDisplayMode; - IDirect3D9* pD3D = DXUTGetD3D9Object(); - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - pD3D->GetAdapterDisplayMode( pDeviceSettings->d3d9.AdapterOrdinal, &adapterDesktopDisplayMode ); - if( pDeviceSettings->d3d9.AdapterFormat != adapterDesktopDisplayMode.Format ) - { - - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - deviceSettings.d3d9.AdapterFormat = adapterDesktopDisplayMode.Format; - - hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); - if( FAILED( hr ) ) // the call will fail if no valid devices were found - { - DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES ); - DXUTShutdown(); - } - - // Change to a Direct3D device created from the new device settings. - // If there is an existing device, then either reset or recreate the scene - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); - if( FAILED( hr ) ) - { - // If this fails, try to go fullscreen and if this fails also shutdown. - if( FAILED( DXUTToggleFullScreen() ) ) - DXUTShutdown(); - } - - return; - } - } - - // Try to reset the device - if( FAILED( hr = DXUTReset3DEnvironment9() ) ) - { - if( D3DERR_DEVICELOST == hr ) - { - // The device was lost again, so continue waiting until it can be reset. - return; - } - else if( DXUTERR_RESETTINGDEVICEOBJECTS == hr || - DXUTERR_MEDIANOTFOUND == hr ) - { - DXUTDisplayErrorMessage( hr ); - DXUTShutdown(); - return; - } - else - { - // Reset failed, but the device wasn't lost so something bad happened, - // so recreate the device to try to recover - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( FAILED( DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ) ) ) - { - DXUTShutdown(); - return; - } - } - } - } - - GetDXUTState().SetDeviceLost( false ); - } - - // Get the app's time, in seconds. Skip rendering if no time elapsed - double fTime, fAbsTime; float fElapsedTime; - DXUTGetGlobalTimer()->GetTimeValues( &fTime, &fAbsTime, &fElapsedTime ); - - // Store the time for the app - if( GetDXUTState().GetConstantFrameTime() ) - { - fElapsedTime = GetDXUTState().GetTimePerFrame(); - fTime = DXUTGetTime() + fElapsedTime; - } - - GetDXUTState().SetTime( fTime ); - GetDXUTState().SetAbsoluteTime( fAbsTime ); - GetDXUTState().SetElapsedTime( fElapsedTime ); - - // Update the FPS stats - DXUTUpdateFrameStats(); - - DXUTHandleTimers(); - - // Animate the scene by calling the app's frame move callback - LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove = GetDXUTState().GetFrameMoveFunc(); - if( pCallbackFrameMove != NULL ) - { - pCallbackFrameMove( fTime, fElapsedTime, GetDXUTState().GetFrameMoveFuncUserContext() ); - pd3dDevice = DXUTGetD3D9Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback - return; - } - - if( !GetDXUTState().GetRenderingPaused() ) - { - // Render the scene by calling the app's render callback - LPDXUTCALLBACKD3D9FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D9FrameRenderFunc(); - if( pCallbackFrameRender != NULL ) - { - pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, - GetDXUTState().GetD3D9FrameRenderFuncUserContext() ); - pd3dDevice = DXUTGetD3D9Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback - return; - } - -#if defined(DEBUG) || defined(_DEBUG) - // The back buffer should always match the client rect - // if the Direct3D backbuffer covers the entire window - RECT rcClient; - GetClientRect( DXUTGetHWND(), &rcClient ); - if( !IsIconic( DXUTGetHWND() ) ) - { - GetClientRect( DXUTGetHWND(), &rcClient ); - assert( DXUTGetD3D9BackBufferSurfaceDesc()->Width == (UINT)rcClient.right ); - assert( DXUTGetD3D9BackBufferSurfaceDesc()->Height == (UINT)rcClient.bottom ); - } -#endif - - // Show the frame on the primary surface. - hr = pd3dDevice->Present( NULL, NULL, NULL, NULL ); - if( FAILED( hr ) ) - { - if( D3DERR_DEVICELOST == hr ) - { - GetDXUTState().SetDeviceLost( true ); - } - else if( D3DERR_DRIVERINTERNALERROR == hr ) - { - // When D3DERR_DRIVERINTERNALERROR is returned from Present(), - // the application can do one of the following: - // - // - End, with the pop-up window saying that the application cannot continue - // because of problems in the display adapter and that the user should - // contact the adapter manufacturer. - // - // - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same - // path as recovering from a lost device. If IDirect3DDevice9::Reset fails with - // D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message - // that the user should contact the adapter manufacturer. - // - // The framework attempts the path of resetting the device - // - GetDXUTState().SetDeviceLost( true ); - } - } - } - - // If the app called DXUTWasKeyPressed() then do the work - // to store the current state of the keys in bLastKeys - if( GetDXUTState().GetAppCalledWasKeyPressed() ) - { - bool* bLastKeys = GetDXUTState().GetLastKeys(); - bool* bKeys = GetDXUTState().GetKeys(); - memcpy( bLastKeys, bKeys, sizeof( bool ) * 256 ); - } - - // Update current frame # - int nFrame = GetDXUTState().GetCurrentFrameNumber(); - nFrame++; - GetDXUTState().SetCurrentFrameNumber( nFrame ); - - // Check to see if the app should shutdown due to cmdline - if( GetDXUTState().GetOverrideQuitAfterFrame() != 0 ) - { - if( nFrame > GetDXUTState().GetOverrideQuitAfterFrame() ) - DXUTShutdown(); - } - - return; -} - - -//-------------------------------------------------------------------------------------- -// Cleans up the 3D environment by: -// - Calls the device lost callback -// - Calls the device destroyed callback -// - Releases the D3D device -//-------------------------------------------------------------------------------------- -void DXUTCleanup3DEnvironment9( bool bReleaseSettings ) -{ - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice != NULL ) - { - GetDXUTState().SetInsideDeviceCallback( true ); - - // Call the app's device lost callback - if( GetDXUTState().GetDeviceObjectsReset() == true ) - { - LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc(); - if( pCallbackDeviceLost != NULL ) - pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() ); - GetDXUTState().SetDeviceObjectsReset( false ); - } - - // Call the app's device destroyed callback - if( GetDXUTState().GetDeviceObjectsCreated() == true ) - { - LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallbackDeviceDestroyed = GetDXUTState().GetD3D9DeviceDestroyedFunc(); - if( pCallbackDeviceDestroyed != NULL ) - pCallbackDeviceDestroyed( GetDXUTState().GetD3D9DeviceDestroyedFuncUserContext() ); - GetDXUTState().SetDeviceObjectsCreated( false ); - } - - GetDXUTState().SetInsideDeviceCallback( false ); - - // Release the D3D device and in debug configs, displays a message box if there - // are unrelease objects. - if( pd3dDevice ) - { - UINT references = pd3dDevice->Release(); - if( references > 0 ) - { - DXUTDisplayErrorMessage( DXUTERR_NONZEROREFCOUNT ); - DXUT_ERR( L"DXUTCleanup3DEnvironment", DXUTERR_NONZEROREFCOUNT ); - } - } - GetDXUTState().SetD3D9Device( NULL ); - - if( bReleaseSettings ) - { - DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - SAFE_DELETE(pOldDeviceSettings); - GetDXUTState().SetCurrentDeviceSettings( NULL ); - } - - D3DSURFACE_DESC* pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc9(); - ZeroMemory( pBackBufferSurfaceDesc, sizeof( D3DSURFACE_DESC ) ); - - D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps(); - ZeroMemory( pd3dCaps, sizeof( D3DCAPS9 ) ); - - GetDXUTState().SetDeviceCreated( false ); - } -} - - -//-------------------------------------------------------------------------------------- -// Gives the D3D device a cursor with image and hotspot from hCursor. -//-------------------------------------------------------------------------------------- -HRESULT DXUTSetD3D9DeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark ) -{ - HRESULT hr = E_FAIL; - ICONINFO iconinfo; - bool bBWCursor = false; - LPDIRECT3DSURFACE9 pCursorSurface = NULL; - HDC hdcColor = NULL; - HDC hdcMask = NULL; - HDC hdcScreen = NULL; - BITMAP bm; - DWORD dwWidth = 0; - DWORD dwHeightSrc = 0; - DWORD dwHeightDest = 0; - COLORREF crColor; - COLORREF crMask; - UINT x; - UINT y; - BITMAPINFO bmi; - COLORREF* pcrArrayColor = NULL; - COLORREF* pcrArrayMask = NULL; - DWORD* pBitmap; - HGDIOBJ hgdiobjOld; - - ZeroMemory( &iconinfo, sizeof( iconinfo ) ); - if( !GetIconInfo( hCursor, &iconinfo ) ) - goto End; - - if( 0 == GetObject( ( HGDIOBJ )iconinfo.hbmMask, sizeof( BITMAP ), ( LPVOID )&bm ) ) - goto End; - dwWidth = bm.bmWidth; - dwHeightSrc = bm.bmHeight; - - if( iconinfo.hbmColor == NULL ) - { - bBWCursor = TRUE; - dwHeightDest = dwHeightSrc / 2; - } - else - { - bBWCursor = FALSE; - dwHeightDest = dwHeightSrc; - } - - // Create a surface for the fullscreen cursor - if( FAILED( hr = pd3dDevice->CreateOffscreenPlainSurface( dwWidth, dwHeightDest, - D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &pCursorSurface, - NULL ) ) ) - { - goto End; - } - - pcrArrayMask = new DWORD[dwWidth * dwHeightSrc]; - - ZeroMemory( &bmi, sizeof( bmi ) ); - bmi.bmiHeader.biSize = sizeof( bmi.bmiHeader ); - bmi.bmiHeader.biWidth = dwWidth; - bmi.bmiHeader.biHeight = dwHeightSrc; - bmi.bmiHeader.biPlanes = 1; - bmi.bmiHeader.biBitCount = 32; - bmi.bmiHeader.biCompression = BI_RGB; - - hdcScreen = GetDC( NULL ); - hdcMask = CreateCompatibleDC( hdcScreen ); - if( hdcMask == NULL ) - { - hr = E_FAIL; - goto End; - } - hgdiobjOld = SelectObject( hdcMask, iconinfo.hbmMask ); - GetDIBits( hdcMask, iconinfo.hbmMask, 0, dwHeightSrc, - pcrArrayMask, &bmi, DIB_RGB_COLORS ); - SelectObject( hdcMask, hgdiobjOld ); - - if( !bBWCursor ) - { - pcrArrayColor = new DWORD[dwWidth * dwHeightDest]; - hdcColor = CreateCompatibleDC( hdcScreen ); - if( hdcColor == NULL ) - { - hr = E_FAIL; - goto End; - } - SelectObject( hdcColor, iconinfo.hbmColor ); - GetDIBits( hdcColor, iconinfo.hbmColor, 0, dwHeightDest, - pcrArrayColor, &bmi, DIB_RGB_COLORS ); - } - - // Transfer cursor image into the surface - D3DLOCKED_RECT lr; - pCursorSurface->LockRect( &lr, NULL, 0 ); - pBitmap = ( DWORD* )lr.pBits; - for( y = 0; y < dwHeightDest; y++ ) - { - for( x = 0; x < dwWidth; x++ ) - { - if( bBWCursor ) - { - crColor = pcrArrayMask[dwWidth * ( dwHeightDest - 1 - y ) + x]; - crMask = pcrArrayMask[dwWidth * ( dwHeightSrc - 1 - y ) + x]; - } - else - { - crColor = pcrArrayColor[dwWidth * ( dwHeightDest - 1 - y ) + x]; - crMask = pcrArrayMask[dwWidth * ( dwHeightDest - 1 - y ) + x]; - } - if( crMask == 0 ) - pBitmap[dwWidth * y + x] = 0xff000000 | crColor; - else - pBitmap[dwWidth * y + x] = 0x00000000; - - // It may be helpful to make the D3D cursor look slightly - // different from the Windows cursor so you can distinguish - // between the two when developing/testing code. When - // bAddWatermark is TRUE, the following code adds some - // small grey "D3D" characters to the upper-left corner of - // the D3D cursor image. - if( bAddWatermark && x < 12 && y < 5 ) - { - // 11.. 11.. 11.. .... CCC0 - // 1.1. ..1. 1.1. .... A2A0 - // 1.1. .1.. 1.1. .... A4A0 - // 1.1. ..1. 1.1. .... A2A0 - // 11.. 11.. 11.. .... CCC0 - - const WORD wMask[5] = { 0xccc0, 0xa2a0, 0xa4a0, 0xa2a0, 0xccc0 }; - if( wMask[y] & (1 << (15 - x)) ) - { - pBitmap[dwWidth*y + x] |= 0xff808080; - } - } - } - } - pCursorSurface->UnlockRect(); - - // Set the device cursor - if( FAILED( hr = pd3dDevice->SetCursorProperties( iconinfo.xHotspot, - iconinfo.yHotspot, pCursorSurface ) ) ) - { - goto End; - } - - hr = S_OK; - -End: - if( iconinfo.hbmMask != NULL ) - DeleteObject( iconinfo.hbmMask ); - if( iconinfo.hbmColor != NULL ) - DeleteObject( iconinfo.hbmColor ); - if( hdcScreen != NULL ) - ReleaseDC( NULL, hdcScreen ); - if( hdcColor != NULL ) - DeleteDC( hdcColor ); - if( hdcMask != NULL ) - DeleteDC( hdcMask ); - SAFE_DELETE_ARRAY( pcrArrayColor ); - SAFE_DELETE_ARRAY( pcrArrayMask ); - SAFE_RELEASE( pCursorSurface ); - return hr; -} - - -//-------------------------------------------------------------------------------------- -// Internal helper function to return the adapter format from the first device settings -// combo that matches the passed adapter ordinal, device type, backbuffer format, and windowed. -//-------------------------------------------------------------------------------------- -HRESULT DXUTFindD3D9AdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat, - BOOL Windowed, D3DFORMAT* pAdapterFormat ) -{ - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration( false ); - assert( pd3dEnum != NULL ); - CD3D9EnumDeviceInfo* pDeviceInfo = pd3dEnum->GetDeviceInfo( AdapterOrdinal, DeviceType ); - if( pDeviceInfo ) - { - for( int iDeviceCombo = 0; iDeviceCombo < pDeviceInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( - iDeviceCombo ); - if( pDeviceSettingsCombo->BackBufferFormat == BackBufferFormat && - pDeviceSettingsCombo->Windowed == Windowed ) - { - // Return the adapter format from the first match - *pAdapterFormat = pDeviceSettingsCombo->AdapterFormat; - return S_OK; - } - } - } - - *pAdapterFormat = BackBufferFormat; - return E_FAIL; -} - -//-------------------------------------------------------------------------------------- -// Sets the viewport, render target view, and depth stencil view. -//-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTSetupD3D11Views( ID3D11DeviceContext* pd3dDeviceContext ) -{ - HRESULT hr = S_OK; - - // Setup the viewport to match the backbuffer - D3D11_VIEWPORT vp; - vp.Width = (FLOAT)DXUTGetDXGIBackBufferSurfaceDesc()->Width; - vp.Height = (FLOAT)DXUTGetDXGIBackBufferSurfaceDesc()->Height; - vp.MinDepth = 0; - vp.MaxDepth = 1; - vp.TopLeftX = 0; - vp.TopLeftY = 0; - pd3dDeviceContext->RSSetViewports( 1, &vp ); - - // Set the render targets - ID3D11RenderTargetView* pRTV = GetDXUTState().GetD3D11RenderTargetView(); - ID3D11DepthStencilView* pDSV = GetDXUTState().GetD3D11DepthStencilView(); - pd3dDeviceContext->OMSetRenderTargets( 1, &pRTV, pDSV ); - - return hr; -} - - -//-------------------------------------------------------------------------------------- -// Creates a render target view, and depth stencil texture and view. +// Creates a render target view, and depth stencil texture and view. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, DXUTDeviceSettings* pDeviceSettings ) { HRESULT hr = S_OK; - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - ID3D11DepthStencilView* pDSV = NULL; - ID3D11RenderTargetView* pRTV = NULL; + auto pSwapChain = DXUTGetDXGISwapChain(); + ID3D11DepthStencilView* pDSV = nullptr; + ID3D11RenderTargetView* pRTV = nullptr; // Get the back buffer and desc ID3D11Texture2D* pBackBuffer; - hr = pSwapChain->GetBuffer( 0, __uuidof( *pBackBuffer ), ( LPVOID* )&pBackBuffer ); + hr = pSwapChain->GetBuffer( 0, IID_PPV_ARGS(&pBackBuffer) ); if( FAILED( hr ) ) return hr; D3D11_TEXTURE2D_DESC backBufferSurfaceDesc; pBackBuffer->GetDesc( &backBufferSurfaceDesc ); // Create the render target view - hr = pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRTV ); + hr = pd3dDevice->CreateRenderTargetView( pBackBuffer, nullptr, &pRTV ); SAFE_RELEASE( pBackBuffer ); if( FAILED( hr ) ) return hr; @@ -3430,7 +2340,7 @@ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3 if( pDeviceSettings->d3d11.AutoCreateDepthStencil ) { // Create depth stencil texture - ID3D11Texture2D* pDepthStencil = NULL; + ID3D11Texture2D* pDepthStencil = nullptr; D3D11_TEXTURE2D_DESC descDepth; descDepth.Width = backBufferSurfaceDesc.Width; descDepth.Height = backBufferSurfaceDesc.Height; @@ -3443,7 +2353,7 @@ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3 descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; - hr = pd3dDevice->CreateTexture2D( &descDepth, NULL, &pDepthStencil ); + hr = pd3dDevice->CreateTexture2D( &descDepth, nullptr, &pDepthStencil ); if( FAILED( hr ) ) return hr; DXUT_SetDebugName( pDepthStencil, "DXUT" ); @@ -3476,172 +2386,275 @@ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3 //-------------------------------------------------------------------------------------- // Creates the 3D environment //-------------------------------------------------------------------------------------- -HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3d11DeviceFromApp ) +HRESULT DXUTCreate3DEnvironment11() { HRESULT hr = S_OK; - ID3D11Device* pd3d11Device = NULL; - ID3D11DeviceContext* pd3dImmediateContext = NULL; - D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0; + ID3D11Device* pd3d11Device = nullptr; + ID3D11DeviceContext* pd3dImmediateContext = nullptr; + D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_1; - IDXGISwapChain* pSwapChain = NULL; - DXUTDeviceSettings* pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - assert( pNewDeviceSettings != NULL ); + IDXGISwapChain* pSwapChain = nullptr; + auto pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + assert( pNewDeviceSettings ); + _Analysis_assume_( pNewDeviceSettings ); - IDXGIFactory1* pDXGIFactory = DXUTGetDXGIFactory(); - assert( pDXGIFactory != NULL ); + auto pDXGIFactory = DXUTGetDXGIFactory(); + assert( pDXGIFactory ); + _Analysis_assume_( pDXGIFactory ); hr = pDXGIFactory->MakeWindowAssociation( DXUTGetHWND(), 0 ); - // Only create a Direct3D device if one hasn't been supplied by the app - if( pd3d11DeviceFromApp == NULL ) + // Try to create the device with the chosen settings + IDXGIAdapter1* pAdapter = nullptr; + + hr = S_OK; + D3D_DRIVER_TYPE ddt = pNewDeviceSettings->d3d11.DriverType; + if( pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) + { + hr = pDXGIFactory->EnumAdapters1( pNewDeviceSettings->d3d11.AdapterOrdinal, &pAdapter ); + if ( FAILED( hr) ) + { + return E_FAIL; + } + ddt = D3D_DRIVER_TYPE_UNKNOWN; + } + else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_WARP) { - // Try to create the device with the chosen settings - IDXGIAdapter1* pAdapter = NULL; + ddt = D3D_DRIVER_TYPE_WARP; + pAdapter = nullptr; + } + else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE) + { + ddt = D3D_DRIVER_TYPE_REFERENCE; + pAdapter = nullptr; + } - hr = S_OK; - D3D_DRIVER_TYPE ddt = pNewDeviceSettings->d3d11.DriverType; - if( pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) + if( SUCCEEDED( hr ) ) + { + hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, + ddt, + ( HMODULE )0, + pNewDeviceSettings->d3d11.CreateFlags, + &pNewDeviceSettings->d3d11.DeviceFeatureLevel, + 1, + D3D11_SDK_VERSION, + &pd3d11Device, + &FeatureLevel, + &pd3dImmediateContext + ); + + if ( FAILED( hr ) ) { - hr = pDXGIFactory->EnumAdapters1( pNewDeviceSettings->d3d11.AdapterOrdinal, &pAdapter ); - if ( FAILED( hr) ) + pAdapter = nullptr; + // Remote desktop does not allow you to enumerate the adapter. In this case, we let D3D11 do the enumeration. + if ( ddt == D3D_DRIVER_TYPE_UNKNOWN ) + { + hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, + D3D_DRIVER_TYPE_HARDWARE, + ( HMODULE )0, + pNewDeviceSettings->d3d11.CreateFlags, + &pNewDeviceSettings->d3d11.DeviceFeatureLevel, + 1, + D3D11_SDK_VERSION, + &pd3d11Device, + &FeatureLevel, + &pd3dImmediateContext + ); + } + if ( FAILED ( hr ) ) { - return E_FAIL; + DXUT_ERR( L"D3D11CreateDevice", hr ); + return DXUTERR_CREATINGDEVICE; } - ddt = D3D_DRIVER_TYPE_UNKNOWN; } - else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_WARP) + } + +#ifndef NDEBUG + if( SUCCEEDED( hr ) ) + { + ID3D11Debug * d3dDebug = nullptr; + if( SUCCEEDED( pd3d11Device->QueryInterface(IID_PPV_ARGS(&d3dDebug) ) ) ) { - ddt = D3D_DRIVER_TYPE_WARP; - pAdapter = NULL; + ID3D11InfoQueue* infoQueue = nullptr; + if( SUCCEEDED( d3dDebug->QueryInterface( IID_PPV_ARGS(&infoQueue) ) ) ) + { + // ignore some "expected" errors + D3D11_MESSAGE_ID denied [] = + { + D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, + }; + + D3D11_INFO_QUEUE_FILTER filter; + memset( &filter, 0, sizeof(filter) ); + filter.DenyList.NumIDs = _countof(denied); + filter.DenyList.pIDList = denied; + infoQueue->AddStorageFilterEntries( &filter ); + infoQueue->Release(); + } + d3dDebug->Release(); } - else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE) + } +#endif + + if( SUCCEEDED( hr ) ) + { + IDXGIDevice1* pDXGIDev = nullptr; + hr = pd3d11Device->QueryInterface( IID_PPV_ARGS(&pDXGIDev) ); + if( SUCCEEDED( hr ) && pDXGIDev ) { - ddt = D3D_DRIVER_TYPE_REFERENCE; - pAdapter = NULL; + if ( !pAdapter ) + { + IDXGIAdapter *pTempAdapter = nullptr; + V_RETURN( pDXGIDev->GetAdapter( &pTempAdapter ) ); + V_RETURN( pTempAdapter->QueryInterface( IID_PPV_ARGS(&pAdapter) ) ); + V_RETURN( pAdapter->GetParent( IID_PPV_ARGS(&pDXGIFactory) ) ); + SAFE_RELEASE ( pTempAdapter ); + if ( GetDXUTState().GetDXGIFactory() != pDXGIFactory ) + GetDXUTState().GetDXGIFactory()->Release(); + GetDXUTState().SetDXGIFactory( pDXGIFactory ); + } } + SAFE_RELEASE( pDXGIDev ); + GetDXUTState().SetDXGIAdapter( pAdapter ); + } - if( SUCCEEDED( hr ) ) + if( FAILED( hr ) ) + { + DXUT_ERR( L"D3D11CreateDevice", hr ); + return DXUTERR_CREATINGDEVICE; + } + + // set default render state to msaa enabled + D3D11_RASTERIZER_DESC drd = { + D3D11_FILL_SOLID, //D3D11_FILL_MODE FillMode; + D3D11_CULL_BACK,//D3D11_CULL_MODE CullMode; + FALSE, //BOOL FrontCounterClockwise; + 0, //INT DepthBias; + 0.0f,//FLOAT DepthBiasClamp; + 0.0f,//FLOAT SlopeScaledDepthBias; + TRUE,//BOOL DepthClipEnable; + FALSE,//BOOL ScissorEnable; + TRUE,//BOOL MultisampleEnable; + FALSE//BOOL AntialiasedLineEnable; + }; + ID3D11RasterizerState* pRS = nullptr; + hr = pd3d11Device->CreateRasterizerState(&drd, &pRS); + if ( FAILED( hr ) ) + { + DXUT_ERR( L"CreateRasterizerState", hr ); + return DXUTERR_CREATINGDEVICE; + } + DXUT_SetDebugName( pRS, "DXUT Default" ); + GetDXUTState().SetD3D11RasterizerState(pRS); + pd3dImmediateContext->RSSetState(pRS); + + // Enumerate its outputs. + UINT OutputCount, iOutput; + for( OutputCount = 0; ; ++OutputCount ) + { + IDXGIOutput* pOutput; + if( FAILED( pAdapter->EnumOutputs( OutputCount, &pOutput ) ) ) + break; + SAFE_RELEASE( pOutput ); + } + auto ppOutputArray = new (std::nothrow) IDXGIOutput*[OutputCount]; + if( !ppOutputArray ) + return E_OUTOFMEMORY; + for( iOutput = 0; iOutput < OutputCount; ++iOutput ) + pAdapter->EnumOutputs( iOutput, ppOutputArray + iOutput ); + GetDXUTState().SetDXGIOutputArray( ppOutputArray ); + GetDXUTState().SetDXGIOutputArraySize( OutputCount ); + + // Create the swapchain + hr = pDXGIFactory->CreateSwapChain( pd3d11Device, &pNewDeviceSettings->d3d11.sd, &pSwapChain ); + if( FAILED( hr ) ) + { + DXUT_ERR( L"CreateSwapChain", hr ); + return DXUTERR_CREATINGDEVICE; + } + + GetDXUTState().SetD3D11Device( pd3d11Device ); + GetDXUTState().SetD3D11DeviceContext( pd3dImmediateContext ); + GetDXUTState().SetD3D11FeatureLevel( FeatureLevel ); + GetDXUTState().SetDXGISwapChain( pSwapChain ); + + assert( pd3d11Device ); + _Analysis_assume_( pd3d11Device ); + + assert( pd3dImmediateContext ); + _Analysis_assume_( pd3dImmediateContext ); + + // Direct3D 11.1 + { + ID3D11Device1* pd3d11Device1 = nullptr; + hr = pd3d11Device->QueryInterface(IID_PPV_ARGS(&pd3d11Device1)); + if( SUCCEEDED( hr ) && pd3d11Device1 ) { + GetDXUTState().SetD3D11Device1( pd3d11Device1 ); - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - ddt, - ( HMODULE )0, - pNewDeviceSettings->d3d11.CreateFlags, - &pNewDeviceSettings->d3d11.DeviceFeatureLevel, - 1, - D3D11_SDK_VERSION, - &pd3d11Device, - &FeatureLevel, - &pd3dImmediateContext - ); - - if ( FAILED( hr ) ) { - pAdapter = NULL; - // Remote desktop does not allow you to enumerate the adapter. In this case, we let D3D11 do the enumeration. - if ( ddt == D3D_DRIVER_TYPE_UNKNOWN ) { - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - D3D_DRIVER_TYPE_HARDWARE, - ( HMODULE )0, - pNewDeviceSettings->d3d11.CreateFlags, - &pNewDeviceSettings->d3d11.DeviceFeatureLevel, - 1, - D3D11_SDK_VERSION, - &pd3d11Device, - &FeatureLevel, - &pd3dImmediateContext - ); - } - if ( FAILED ( hr ) ) { - DXUT_ERR( L"D3D11CreateDevice", hr ); - return DXUTERR_CREATINGDEVICE; - } + ID3D11DeviceContext1* pd3dImmediateContext1 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext1)); + if( SUCCEEDED( hr ) && pd3dImmediateContext1 ) + { + GetDXUTState().SetD3D11DeviceContext1( pd3dImmediateContext1 ); } } + } - if( SUCCEEDED( hr ) ) + // Direct3D 11.2 + { + ID3D11Device2* pd3d11Device2 = nullptr; + hr = pd3d11Device->QueryInterface(IID_PPV_ARGS(&pd3d11Device2)); + if (SUCCEEDED(hr) && pd3d11Device2) { - IDXGIDevice1* pDXGIDev = NULL; - hr = pd3d11Device->QueryInterface( __uuidof( IDXGIDevice1 ), ( LPVOID* )&pDXGIDev ); - if( SUCCEEDED( hr ) && pDXGIDev ) + GetDXUTState().SetD3D11Device2(pd3d11Device2); + + ID3D11DeviceContext2* pd3dImmediateContext2 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext2)); + if (SUCCEEDED(hr) && pd3dImmediateContext2) { - if ( pAdapter == NULL ) - { - IDXGIAdapter *pTempAdapter; - pDXGIDev->GetAdapter( &pTempAdapter ); - V_RETURN( pTempAdapter->QueryInterface( __uuidof( IDXGIAdapter1 ), (LPVOID*) &pAdapter ) ); - V_RETURN( pAdapter->GetParent( __uuidof( IDXGIFactory1 ), (LPVOID*) &pDXGIFactory ) ); - SAFE_RELEASE ( pTempAdapter ); - GetDXUTState().SetDXGIFactory( pDXGIFactory ); - } + GetDXUTState().SetD3D11DeviceContext2(pd3dImmediateContext2); } - SAFE_RELEASE( pDXGIDev ); - GetDXUTState().SetDXGIAdapter( pAdapter ); } + } - if( FAILED( hr ) ) - { - DXUT_ERR( L"D3D11CreateDevice", hr ); - return DXUTERR_CREATINGDEVICE; - } - // set default render state to msaa enabled - D3D11_RASTERIZER_DESC drd = { - D3D11_FILL_SOLID, //D3D11_FILL_MODE FillMode; - D3D11_CULL_BACK,//D3D11_CULL_MODE CullMode; - FALSE, //BOOL FrontCounterClockwise; - 0, //INT DepthBias; - 0.0f,//FLOAT DepthBiasClamp; - 0.0f,//FLOAT SlopeScaledDepthBias; - TRUE,//BOOL DepthClipEnable; - FALSE,//BOOL ScissorEnable; - TRUE,//BOOL MultisampleEnable; - FALSE//BOOL AntialiasedLineEnable; - }; - ID3D11RasterizerState* pRS = NULL; - hr = pd3d11Device->CreateRasterizerState(&drd, &pRS); - if ( FAILED( hr ) ) +#ifdef USE_DIRECT3D11_3 + // Direct3D 11.3 + { + ID3D11Device3* pd3d11Device3 = nullptr; + hr = pd3d11Device->QueryInterface( IID_PPV_ARGS(&pd3d11Device3) ); + if (SUCCEEDED(hr) && pd3d11Device3) { - DXUT_ERR( L"CreateRasterizerState", hr ); - return DXUTERR_CREATINGDEVICE; - } - DXUT_SetDebugName( pRS, "DXUT Default" ); - GetDXUTState().SetD3D11RasterizerState(pRS); - pd3dImmediateContext->RSSetState(pRS); + GetDXUTState().SetD3D11Device3(pd3d11Device3); - // Enumerate its outputs. - UINT OutputCount, iOutput; - for( OutputCount = 0; ; ++OutputCount ) - { - IDXGIOutput* pOutput; - if( FAILED( pAdapter->EnumOutputs( OutputCount, &pOutput ) ) ) - break; - SAFE_RELEASE( pOutput ); + ID3D11DeviceContext3* pd3dImmediateContext3 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext3)); + if (SUCCEEDED(hr) && pd3dImmediateContext3) + { + GetDXUTState().SetD3D11DeviceContext3(pd3dImmediateContext3); + } } - IDXGIOutput** ppOutputArray = new IDXGIOutput*[OutputCount]; - if( !ppOutputArray ) - return E_OUTOFMEMORY; - for( iOutput = 0; iOutput < OutputCount; ++iOutput ) - pAdapter->EnumOutputs( iOutput, ppOutputArray + iOutput ); - GetDXUTState().SetDXGIOutputArray( ppOutputArray ); - GetDXUTState().SetDXGIOutputArraySize( OutputCount ); + } +#endif - // Create the swapchain - hr = pDXGIFactory->CreateSwapChain( pd3d11Device, &pNewDeviceSettings->d3d11.sd, &pSwapChain ); - if( FAILED( hr ) ) +#ifdef USE_DIRECT3D11_4 + // Direct3D 11.4 + { + ID3D11Device4* pd3d11Device4 = nullptr; + hr = pd3d11Device->QueryInterface(IID_PPV_ARGS(&pd3d11Device4)); + if (SUCCEEDED(hr) && pd3d11Device4) { - DXUT_ERR( L"CreateSwapChain", hr ); - return DXUTERR_CREATINGDEVICE; + GetDXUTState().SetD3D11Device4(pd3d11Device4); + + ID3D11DeviceContext4* pd3dImmediateContext4 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext4)); + if (SUCCEEDED(hr) && pd3dImmediateContext4) + { + GetDXUTState().SetD3D11DeviceContext4(pd3dImmediateContext4); + } } } - else - { - pd3d11DeviceFromApp->AddRef(); - pd3d11Device = pd3d11DeviceFromApp; - } - - GetDXUTState().SetD3D11Device( pd3d11Device ); - GetDXUTState().SetD3D11DeviceContext( pd3dImmediateContext ); - GetDXUTState().SetD3D11FeatureLevel( FeatureLevel ); - GetDXUTState().SetDXGISwapChain( pSwapChain ); +#endif // If switching to REF, set the exit code to 11. If switching to HAL and exit code was 11, then set it back to 0. if( pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE && GetDXUTState().GetExitCode() == 0 ) @@ -3656,21 +2669,22 @@ HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3d11DeviceFromApp ) DXUTSetupCursor(); // Update the device stats text - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - assert( pd3dEnum != NULL ); - CD3D11EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d11.AdapterOrdinal ); - DXUTUpdateD3D11DeviceStats( pNewDeviceSettings->d3d11.DriverType, &pAdapterInfo->AdapterDesc ); + auto pd3dEnum = DXUTGetD3D11Enumeration(); + assert( pd3dEnum ); + _Analysis_assume_( pd3dEnum ); + auto pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d11.AdapterOrdinal ); + DXUTUpdateD3D11DeviceStats( pNewDeviceSettings->d3d11.DriverType, pNewDeviceSettings->d3d11.DeviceFeatureLevel, &pAdapterInfo->AdapterDesc ); // Call the app's device created callback if non-NULL - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); + auto pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D11DEVICECREATED pCallbackDeviceCreated = GetDXUTState().GetD3D11DeviceCreatedFunc(); + auto pCallbackDeviceCreated = GetDXUTState().GetD3D11DeviceCreatedFunc(); hr = S_OK; - if( pCallbackDeviceCreated != NULL ) + if( pCallbackDeviceCreated ) hr = pCallbackDeviceCreated( DXUTGetD3D11Device(), pBackBufferSurfaceDesc, GetDXUTState().GetD3D11DeviceCreatedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D11Device() == NULL ) // Handle DXUTShutdown from inside callback + if( !DXUTGetD3D11Device() ) // Handle DXUTShutdown from inside callback return E_FAIL; if( FAILED( hr ) ) { @@ -3687,18 +2701,15 @@ HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3d11DeviceFromApp ) return DXUTERR_CREATINGDEVICEOBJECTS; } - // Create performance counters - //DXUTCreateD3D11Counters( pd3d11Device ); - // Call the app's swap chain reset callback if non-NULL GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallbackSwapChainResized = GetDXUTState().GetD3D11SwapChainResizedFunc(); hr = S_OK; - if( pCallbackSwapChainResized != NULL ) + if( pCallbackSwapChainResized ) hr = pCallbackSwapChainResized( DXUTGetD3D11Device(), pSwapChain, pBackBufferSurfaceDesc, GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D11Device() == NULL ) // Handle DXUTShutdown from inside callback + if( !DXUTGetD3D11Device() ) // Handle DXUTShutdown from inside callback return E_FAIL; if( FAILED( hr ) ) { @@ -3727,12 +2738,14 @@ HRESULT DXUTReset3DEnvironment11() DXUTPause( true, true ); bool bDeferredDXGIAction = false; - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - assert( pSwapChain != NULL ); - + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pSwapChain = DXUTGetDXGISwapChain(); + assert( pSwapChain ); + _Analysis_assume_( pSwapChain ); + DXGI_SWAP_CHAIN_DESC SCDesc; - pSwapChain->GetDesc( &SCDesc ); + if ( FAILED( pSwapChain->GetDesc(&SCDesc)) ) + memset( &SCDesc, 0, sizeof(SCDesc) ); // Resize backbuffer and target of the swapchain in case they have changed. // For windowed mode, use the client rect as the desired size. Unlike D3D9, @@ -3755,7 +2768,7 @@ HRESULT DXUTReset3DEnvironment11() // Set the fullscreen state if( pDeviceSettings->d3d11.sd.Windowed ) { - V_RETURN( pSwapChain->SetFullscreenState( FALSE, NULL ) ); + V_RETURN( pSwapChain->SetFullscreenState( FALSE, nullptr ) ); bDeferredDXGIAction = true; } else @@ -3769,7 +2782,7 @@ HRESULT DXUTReset3DEnvironment11() // not to store the height and width so that we have the correct values when calling ResizeTarget. GetDXUTState().SetDoNotStoreBufferSize( true ); - V_RETURN( pSwapChain->SetFullscreenState( TRUE, NULL ) ); + V_RETURN( pSwapChain->SetFullscreenState( TRUE, nullptr ) ); GetDXUTState().SetDoNotStoreBufferSize( false ); V_RETURN( pSwapChain->ResizeTarget( &pDeviceSettings->d3d11.sd.BufferDesc ) ); @@ -3811,20 +2824,20 @@ HRESULT DXUTReset3DEnvironment11() // - Calling the app's framemove and render callback // - Calling Present() //-------------------------------------------------------------------------------------- -void DXUTRender3DEnvironment11() +void WINAPI DXUTRender3DEnvironment() { HRESULT hr; - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); - if( NULL == pd3dDevice ) + auto pd3dDevice = DXUTGetD3D11Device(); + if( !pd3dDevice ) return; - ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); - if( NULL == pd3dImmediateContext ) + auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); + if( !pd3dImmediateContext ) return; - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - if( NULL == pSwapChain ) + auto pSwapChain = DXUTGetDXGISwapChain(); + if( !pSwapChain ) return; if( DXUTIsRenderingPaused() || !DXUTIsActive() || GetDXUTState().GetRenderingOccluded() ) @@ -3848,8 +2861,6 @@ void DXUTRender3DEnvironment11() GetDXUTState().SetAbsoluteTime( fAbsTime ); GetDXUTState().SetElapsedTime( fElapsedTime ); - // Start Performance Counters - // Update the FPS stats DXUTUpdateFrameStats(); @@ -3857,11 +2868,11 @@ void DXUTRender3DEnvironment11() // Animate the scene by calling the app's frame move callback LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove = GetDXUTState().GetFrameMoveFunc(); - if( pCallbackFrameMove != NULL ) + if( pCallbackFrameMove ) { pCallbackFrameMove( fTime, fElapsedTime, GetDXUTState().GetFrameMoveFuncUserContext() ); pd3dDevice = DXUTGetD3D11Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback + if( !pd3dDevice ) // Handle DXUTShutdown from inside callback return; } @@ -3869,13 +2880,13 @@ void DXUTRender3DEnvironment11() { // Render the scene by calling the app's render callback LPDXUTCALLBACKD3D11FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D11FrameRenderFunc(); - if( pCallbackFrameRender != NULL && !GetDXUTState().GetRenderingOccluded() ) + if( pCallbackFrameRender && !GetDXUTState().GetRenderingOccluded() ) { pCallbackFrameRender( pd3dDevice, pd3dImmediateContext, fTime, fElapsedTime, GetDXUTState().GetD3D11FrameRenderFuncUserContext() ); pd3dDevice = DXUTGetD3D11Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback + if( !pd3dDevice ) // Handle DXUTShutdown from inside callback return; } @@ -3894,10 +2905,12 @@ void DXUTRender3DEnvironment11() #endif } - if ( GetDXUTState().GetSaveScreenShot() ) { - DXUTSnapD3D11Screenshot( GetDXUTState().GetScreenShotName(), D3DX11_IFF_BMP ); + if ( GetDXUTState().GetSaveScreenShot() ) + { + DXUTSnapD3D11Screenshot( GetDXUTState().GetScreenShotName(), false ); } - if ( GetDXUTState().GetExitAfterScreenShot() ) { + if ( GetDXUTState().GetExitAfterScreenShot() ) + { DXUTShutdown(); return; } @@ -3933,8 +2946,8 @@ void DXUTRender3DEnvironment11() { // Reset failed, but the device wasn't lost so something bad happened, // so recreate the device to try to recover - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( FAILED( DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ) ) ) + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + if( FAILED( DXUTChangeDevice( pDeviceSettings, false ) ) ) { DXUTShutdown(); return; @@ -3971,10 +2984,6 @@ void DXUTRender3DEnvironment11() nFrame++; GetDXUTState().SetCurrentFrameNumber( nFrame ); - - // Update the D3D11 counter stats - //DXUTUpdateD3D11CounterStats(); - // Check to see if the app should shutdown due to cmdline if( GetDXUTState().GetOverrideQuitAfterFrame() != 0 ) { @@ -3985,60 +2994,6 @@ void DXUTRender3DEnvironment11() return; } -void ClearD3D11DeviceContext( ID3D11DeviceContext* pd3dDeviceContext ) -{ - // Unbind all objects from the immediate context - if (pd3dDeviceContext == NULL) return; - - ID3D11ShaderResourceView* pSRVs[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - ID3D11RenderTargetView* pRTVs[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - ID3D11DepthStencilView* pDSV = NULL; - ID3D11Buffer* pBuffers[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - ID3D11SamplerState* pSamplers[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - UINT StrideOffset[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - - // Shaders - pd3dDeviceContext->VSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->HSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->DSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->GSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->PSSetShader( NULL, NULL, 0 ); - - // IA clear - pd3dDeviceContext->IASetVertexBuffers( 0, 16, pBuffers, StrideOffset, StrideOffset ); - pd3dDeviceContext->IASetIndexBuffer( NULL, DXGI_FORMAT_R16_UINT, 0 ); - pd3dDeviceContext->IASetInputLayout( NULL ); - - // Constant buffers - pd3dDeviceContext->VSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->HSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->DSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->GSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->PSSetConstantBuffers( 0, 14, pBuffers ); - - // Resources - pd3dDeviceContext->VSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->HSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->DSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->GSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->PSSetShaderResources( 0, 16, pSRVs ); - - // Samplers - pd3dDeviceContext->VSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->HSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->DSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->GSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->PSSetSamplers( 0, 16, pSamplers ); - - // Render targets - pd3dDeviceContext->OMSetRenderTargets( 8, pRTVs, pDSV ); - - // States - FLOAT blendFactor[4] = { 0,0,0,0 }; - pd3dDeviceContext->OMSetBlendState( NULL, blendFactor, 0xFFFFFFFF ); - pd3dDeviceContext->OMSetDepthStencilState( NULL, 0 ); - pd3dDeviceContext->RSSetState( NULL ); -} //-------------------------------------------------------------------------------------- // Cleans up the 3D environment by: @@ -4046,52 +3001,44 @@ void ClearD3D11DeviceContext( ID3D11DeviceContext* pd3dDeviceContext ) // - Calls the device destroyed callback // - Releases the D3D device //-------------------------------------------------------------------------------------- -void DXUTCleanup3DEnvironment11( bool bReleaseSettings ) +void DXUTCleanup3DEnvironment( _In_ bool bReleaseSettings ) { - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); + auto pd3dDevice = DXUTGetD3D11Device(); - if( pd3dDevice != NULL ) + if( pd3dDevice ) { - if (GetDXUTState().GetD3D11RasterizerState()!= NULL ) + if (GetDXUTState().GetD3D11RasterizerState()) GetDXUTState().GetD3D11RasterizerState()->Release(); - // Call ClearState to avoid tons of messy debug spew telling us that we're deleting bound objects - ID3D11DeviceContext* pImmediateContext = DXUTGetD3D11DeviceContext(); - ClearD3D11DeviceContext( pImmediateContext ); - - // Clear state and flush - pImmediateContext->ClearState(); - pImmediateContext->Flush(); - // Call the app's SwapChain lost callback GetDXUTState().SetInsideDeviceCallback( true ); if( GetDXUTState().GetDeviceObjectsReset() ) { LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallbackSwapChainReleasing = GetDXUTState().GetD3D11SwapChainReleasingFunc(); - if( pCallbackSwapChainReleasing != NULL ) + if( pCallbackSwapChainReleasing ) pCallbackSwapChainReleasing( GetDXUTState().GetD3D11SwapChainReleasingFuncUserContext() ); GetDXUTState().SetDeviceObjectsReset( false ); } // Release our old depth stencil texture and view - ID3D11Texture2D* pDS = GetDXUTState().GetD3D11DepthStencil(); + auto pDS = GetDXUTState().GetD3D11DepthStencil(); SAFE_RELEASE( pDS ); - GetDXUTState().SetD3D11DepthStencil( NULL ); - ID3D11DepthStencilView* pDSV = GetDXUTState().GetD3D11DepthStencilView(); + GetDXUTState().SetD3D11DepthStencil( nullptr ); + auto pDSV = GetDXUTState().GetD3D11DepthStencilView(); SAFE_RELEASE( pDSV ); - GetDXUTState().SetD3D11DepthStencilView( NULL ); + GetDXUTState().SetD3D11DepthStencilView( nullptr ); // Cleanup the render target view - ID3D11RenderTargetView* pRTV = GetDXUTState().GetD3D11RenderTargetView(); + auto pRTV = GetDXUTState().GetD3D11RenderTargetView(); SAFE_RELEASE( pRTV ); - GetDXUTState().SetD3D11RenderTargetView( NULL ); + GetDXUTState().SetD3D11RenderTargetView( nullptr ); // Call the app's device destroyed callback if( GetDXUTState().GetDeviceObjectsCreated() ) { - LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallbackDeviceDestroyed = GetDXUTState().GetD3D11DeviceDestroyedFunc(); - if( pCallbackDeviceDestroyed != NULL ) + auto pCallbackDeviceDestroyed = GetDXUTState().GetD3D11DeviceDestroyedFunc(); + if( pCallbackDeviceDestroyed ) pCallbackDeviceDestroyed( GetDXUTState().GetD3D11DeviceDestroyedFuncUserContext() ); GetDXUTState().SetDeviceObjectsCreated( false ); } @@ -4100,41 +3047,93 @@ void DXUTCleanup3DEnvironment11( bool bReleaseSettings ) // Release the swap chain GetDXUTState().SetReleasingSwapChain( true ); - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); + auto pSwapChain = DXUTGetDXGISwapChain(); if( pSwapChain ) { pSwapChain->SetFullscreenState( FALSE, 0 ); } SAFE_RELEASE( pSwapChain ); - GetDXUTState().SetDXGISwapChain( NULL ); + GetDXUTState().SetDXGISwapChain( nullptr ); GetDXUTState().SetReleasingSwapChain( false ); // Release the outputs. - IDXGIOutput** ppOutputArray = GetDXUTState().GetDXGIOutputArray(); + auto ppOutputArray = GetDXUTState().GetDXGIOutputArray(); UINT OutputCount = GetDXUTState().GetDXGIOutputArraySize(); for( UINT o = 0; o < OutputCount; ++o ) SAFE_RELEASE( ppOutputArray[o] ); delete[] ppOutputArray; - GetDXUTState().SetDXGIOutputArray( NULL ); + GetDXUTState().SetDXGIOutputArray( nullptr ); GetDXUTState().SetDXGIOutputArraySize( 0 ); // Release the D3D adapter. - IDXGIAdapter* pAdapter = GetDXUTState().GetDXGIAdapter(); + auto pAdapter = GetDXUTState().GetDXGIAdapter(); SAFE_RELEASE( pAdapter ); - GetDXUTState().SetDXGIAdapter( NULL ); + GetDXUTState().SetDXGIAdapter( nullptr ); - // Release the counters - //DXUTDestroyD3D11Counters(); + // Call ClearState to avoid tons of messy debug spew telling us that we're deleting bound objects + auto pImmediateContext = DXUTGetD3D11DeviceContext(); + assert( pImmediateContext ); + pImmediateContext->ClearState(); + pImmediateContext->Flush(); // Release the D3D11 immediate context (if it exists) because it has a extra ref count on it - ID3D11DeviceContext* pd3d11DeviceContext = GetDXUTState().GetD3D11DeviceContext(); - SAFE_RELEASE( pd3d11DeviceContext ); - GetDXUTState().SetD3D11DeviceContext( NULL ); + SAFE_RELEASE( pImmediateContext ); + GetDXUTState().SetD3D11DeviceContext( nullptr ); - // Release the D3D device and in debug configs, displays a message box if there - // are unrelease objects. - if( pd3dDevice ) + auto pImmediateContext1 = DXUTGetD3D11DeviceContext1(); + SAFE_RELEASE( pImmediateContext1 ); + GetDXUTState().SetD3D11DeviceContext1( nullptr ); + + auto pImmediateContext2 = DXUTGetD3D11DeviceContext2(); + SAFE_RELEASE(pImmediateContext2); + GetDXUTState().SetD3D11DeviceContext2(nullptr); + +#ifdef USE_DIRECT3D11_3 + auto pImmediateContext3 = DXUTGetD3D11DeviceContext3(); + SAFE_RELEASE(pImmediateContext3); + GetDXUTState().SetD3D11DeviceContext3(nullptr); +#endif + +#ifdef USE_DIRECT3D11_4 + auto pImmediateContext4 = DXUTGetD3D11DeviceContext4(); + SAFE_RELEASE(pImmediateContext4); + GetDXUTState().SetD3D11DeviceContext4(nullptr); +#endif + + // Report live objects + if ( pd3dDevice ) { +#ifndef NDEBUG + ID3D11Debug * d3dDebug = nullptr; + if( SUCCEEDED( pd3dDevice->QueryInterface( IID_PPV_ARGS(&d3dDebug) ) ) ) + { + d3dDebug->ReportLiveDeviceObjects( D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL ); + d3dDebug->Release(); + } +#endif + + auto pd3dDevice1 = DXUTGetD3D11Device1(); + SAFE_RELEASE( pd3dDevice1 ); + GetDXUTState().SetD3D11Device1(nullptr); + + auto pd3dDevice2 = DXUTGetD3D11Device2(); + SAFE_RELEASE(pd3dDevice2); + GetDXUTState().SetD3D11Device2(nullptr); + +#ifdef USE_DIRECT3D11_3 + auto pd3dDevice3 = DXUTGetD3D11Device3(); + SAFE_RELEASE(pd3dDevice3); + GetDXUTState().SetD3D11Device3(nullptr); +#endif + +#ifdef USE_DIRECT3D11_4 + auto pd3dDevice4 = DXUTGetD3D11Device4(); + SAFE_RELEASE(pd3dDevice4); + GetDXUTState().SetD3D11Device4(nullptr); +#endif + + // Release the D3D device and in debug configs, displays a message box if there + // are unrelease objects. UINT references = pd3dDevice->Release(); if( references > 0 ) { @@ -4142,16 +3141,27 @@ void DXUTCleanup3DEnvironment11( bool bReleaseSettings ) DXUT_ERR( L"DXUTCleanup3DEnvironment", DXUTERR_NONZEROREFCOUNT ); } } - GetDXUTState().SetD3D11Device( NULL ); + GetDXUTState().SetD3D11Device( nullptr ); + +#ifndef NDEBUG + { + IDXGIDebug* dxgiDebug = nullptr; + if ( SUCCEEDED( DXUT_Dynamic_DXGIGetDebugInterface( IID_IDXGIDebug, reinterpret_cast( &dxgiDebug ) ) ) ) + { + dxgiDebug->ReportLiveObjects( DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL ); + dxgiDebug->Release(); + } + } +#endif if( bReleaseSettings ) { - DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); SAFE_DELETE(pOldDeviceSettings); - GetDXUTState().SetCurrentDeviceSettings( NULL ); + GetDXUTState().SetCurrentDeviceSettings( nullptr ); } - DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); + auto pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); ZeroMemory( pBackBufferSurfaceDesc, sizeof( DXGI_SURFACE_DESC ) ); GetDXUTState().SetDeviceCreated( false ); @@ -4168,7 +3178,7 @@ LRESULT CALLBACK DXUTLowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lPar return CallNextHookEx( GetDXUTState().GetKeyboardHook(), nCode, wParam, lParam ); bool bEatKeystroke = false; - KBDLLHOOKSTRUCT* p = ( KBDLLHOOKSTRUCT* )lParam; + auto p = reinterpret_cast( lParam ); switch( wParam ) { case WM_KEYDOWN: @@ -4187,11 +3197,11 @@ LRESULT CALLBACK DXUTLowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lPar } - //-------------------------------------------------------------------------------------- // Controls how DXUT behaves when fullscreen and windowed mode with regard to // shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen, bool bAllowWhenWindowed ) { GetDXUTState().SetAllowShortcutKeysWhenWindowed( bAllowWhenWindowed ); @@ -4212,7 +3222,7 @@ void WINAPI DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen, bool bAllowWh // Enables/disables Windows keys, and disables or restores the StickyKeys/ToggleKeys/FilterKeys // shortcut to help prevent accidental task switching //-------------------------------------------------------------------------------------- -void DXUTAllowShortcutKeys( bool bAllowKeys ) +void DXUTAllowShortcutKeys( _In_ bool bAllowKeys ) { GetDXUTState().SetAllowShortcutKeys( bAllowKeys ); @@ -4231,24 +3241,18 @@ void DXUTAllowShortcutKeys( bool bAllowKeys ) if( GetDXUTState().GetKeyboardHook() ) { UnhookWindowsHookEx( GetDXUTState().GetKeyboardHook() ); - GetDXUTState().SetKeyboardHook( NULL ); + GetDXUTState().SetKeyboardHook( nullptr ); } } else { // Set low level keyboard hook if haven't already - if( GetDXUTState().GetKeyboardHook() == NULL ) + if( !GetDXUTState().GetKeyboardHook() ) { - // Set the low-level hook procedure. Only works on Windows 2000 and above - OSVERSIONINFO OSVersionInfo; - OSVersionInfo.dwOSVersionInfoSize = sizeof( OSVersionInfo ); - GetVersionEx( &OSVersionInfo ); - if( OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && OSVersionInfo.dwMajorVersion > 4 ) - { - HHOOK hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, DXUTLowLevelKeyboardProc, - GetModuleHandle( NULL ), 0 ); - GetDXUTState().SetKeyboardHook( hKeyboardHook ); - } + // Set the low-level hook procedure. + HHOOK hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, DXUTLowLevelKeyboardProc, + GetModuleHandle( nullptr ), 0 ); + GetDXUTState().SetKeyboardHook( hKeyboardHook ); } // Disable StickyKeys/etc shortcuts but if the accessibility feature is on, @@ -4290,6 +3294,7 @@ void DXUTAllowShortcutKeys( bool bAllowKeys ) //-------------------------------------------------------------------------------------- // Pauses time or rendering. Keeps a ref count so pausing can be layered //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI DXUTPause( bool bPauseTime, bool bPauseRendering ) { int nPauseTimeCount = GetDXUTState().GetPauseTimeCount(); @@ -4325,13 +3330,13 @@ void WINAPI DXUTPause( bool bPauseTime, bool bPauseRendering ) //-------------------------------------------------------------------------------------- // Starts a user defined timer callback //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutInSecs, UINT* pnIDEvent, void* pCallbackUserContext ) { - if( pCallbackTimer == NULL ) + if( !pCallbackTimer ) return DXUT_ERR_MSGBOX( L"DXUTSetTimer", E_INVALIDARG ); - HRESULT hr; DXUT_TIMER DXUTTimer; DXUTTimer.pCallbackTimer = pCallbackTimer; DXUTTimer.pCallbackUserContext = pCallbackUserContext; @@ -4341,17 +3346,16 @@ HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutI DXUTTimer.nID = GetDXUTState().GetTimerLastID() + 1; GetDXUTState().SetTimerLastID( DXUTTimer.nID ); - CGrowableArray * pTimerList = GetDXUTState().GetTimerList(); - if( pTimerList == NULL ) + auto pTimerList = GetDXUTState().GetTimerList(); + if( !pTimerList ) { - pTimerList = new CGrowableArray ; - if( pTimerList == NULL ) + pTimerList = new (std::nothrow) std::vector; + if( !pTimerList ) return E_OUTOFMEMORY; GetDXUTState().SetTimerList( pTimerList ); } - if( FAILED( hr = pTimerList->Add( DXUTTimer ) ) ) - return hr; + pTimerList->push_back( DXUTTimer ); if( pnIDEvent ) *pnIDEvent = DXUTTimer.nID; @@ -4363,21 +3367,21 @@ HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutI //-------------------------------------------------------------------------------------- // Stops a user defined timer callback //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTKillTimer( UINT nIDEvent ) +HRESULT WINAPI DXUTKillTimer( _In_ UINT nIDEvent ) { - CGrowableArray * pTimerList = GetDXUTState().GetTimerList(); - if( pTimerList == NULL ) + auto pTimerList = GetDXUTState().GetTimerList(); + if( !pTimerList ) return S_FALSE; bool bFound = false; - for( int i = 0; i < pTimerList->GetSize(); i++ ) + for( auto it = pTimerList->begin(); it != pTimerList->end(); ++it ) { - DXUT_TIMER DXUTTimer = pTimerList->GetAt( i ); + DXUT_TIMER DXUTTimer = *it; if( DXUTTimer.nID == nIDEvent ) { DXUTTimer.bEnabled = false; - pTimerList->SetAt( i, DXUTTimer ); + *it = DXUTTimer; bFound = true; break; } @@ -4397,14 +3401,14 @@ void DXUTHandleTimers() { float fElapsedTime = DXUTGetElapsedTime(); - CGrowableArray * pTimerList = GetDXUTState().GetTimerList(); - if( pTimerList == NULL ) + auto pTimerList = GetDXUTState().GetTimerList(); + if( !pTimerList ) return; // Walk through the list of timer callbacks - for( int i = 0; i < pTimerList->GetSize(); i++ ) + for( auto it = pTimerList->begin(); it != pTimerList->end(); ++it ) { - DXUT_TIMER DXUTTimer = pTimerList->GetAt( i ); + DXUT_TIMER DXUTTimer = *it; if( DXUTTimer.bEnabled ) { DXUTTimer.fCountdown -= fElapsedTime; @@ -4414,10 +3418,10 @@ void DXUTHandleTimers() { DXUTTimer.pCallbackTimer( DXUTTimer.nID, DXUTTimer.pCallbackUserContext ); // The callback my have changed the timer. - DXUTTimer = pTimerList->GetAt( i ); + DXUTTimer = *it; DXUTTimer.fCountdown = DXUTTimer.fTimeoutInSecs; } - pTimerList->SetAt( i, DXUTTimer ); + *it = DXUTTimer; } } } @@ -4426,7 +3430,7 @@ void DXUTHandleTimers() //-------------------------------------------------------------------------------------- // Display an custom error msg box //-------------------------------------------------------------------------------------- -void DXUTDisplayErrorMessage( HRESULT hr ) +void DXUTDisplayErrorMessage( _In_ HRESULT hr ) { WCHAR strBuffer[512]; @@ -4437,15 +3441,12 @@ void DXUTDisplayErrorMessage( HRESULT hr ) case DXUTERR_NODIRECT3D: { nExitCode = 2; - if( DXUTDoesAppSupportD3D11() && !DXUTDoesAppSupportD3D9() ) - wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 11. " ); - else - wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 9. Check that the latest version of DirectX is correctly installed on your system. Also make sure that this program was compiled with header files that match the installed DirectX DLLs." ); + wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 11. " ); break; } case DXUTERR_NOCOMPATIBLEDEVICES: nExitCode = 3; - if( GetSystemMetrics(0x1000) != 0 ) // SM_REMOTESESSION + if( GetSystemMetrics(SM_REMOTESESSION) != 0 ) wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Direct3D does not work over a remote session." ); else wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not find any compatible Direct3D devices." ); @@ -4478,7 +3479,7 @@ void DXUTDisplayErrorMessage( HRESULT hr ) //-------------------------------------------------------------------------------------- // Internal function to map MK_* to an array index //-------------------------------------------------------------------------------------- -int DXUTMapButtonToArrayIndex( BYTE vButton ) +int DXUTMapButtonToArrayIndex( _In_ BYTE vButton ) { switch( vButton ) { @@ -4501,57 +3502,52 @@ int DXUTMapButtonToArrayIndex( BYTE vButton ) } - //-------------------------------------------------------------------------------------- // Toggle between full screen and windowed //-------------------------------------------------------------------------------------- HRESULT WINAPI DXUTToggleFullScreen() { - HRESULT hr; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); + auto deviceSettings = DXUTGetDeviceSettings(); + if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + // WARP driver type doesn't support fullscreen + return S_FALSE; + } + + auto orginalDeviceSettings = DXUTGetDeviceSettings(); - if (deviceSettings.ver == DXUT_D3D11_DEVICE) { - deviceSettings.d3d11.sd.Windowed = !deviceSettings.d3d11.sd.Windowed; // datut - if (!deviceSettings.d3d11.sd.Windowed) { - DXGI_MODE_DESC adapterDesktopDisplayMode = + deviceSettings.d3d11.sd.Windowed = !deviceSettings.d3d11.sd.Windowed; + + HRESULT hr; + if (!deviceSettings.d3d11.sd.Windowed) + { + DXGI_MODE_DESC adapterDesktopDisplayMode; + hr = DXUTGetD3D11AdapterDisplayMode( deviceSettings.d3d11.AdapterOrdinal, 0, &adapterDesktopDisplayMode ); + if ( FAILED(hr) ) + { + static const DXGI_MODE_DESC s_adapterDesktopDisplayMode = { - 800, 600, { 60, 1 }, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB + 800, 600, { 0, 0 }, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB }; - DXUTGetD3D11AdapterDisplayMode( deviceSettings.d3d11.AdapterOrdinal, 0, &adapterDesktopDisplayMode ); - - - deviceSettings.d3d11.sd.BufferDesc = adapterDesktopDisplayMode; - }else { - RECT r = DXUTGetWindowClientRectAtModeChange(); - deviceSettings.d3d11.sd.BufferDesc.Height = r.bottom; - deviceSettings.d3d11.sd.BufferDesc.Width = r.right; - } - }else if (deviceSettings.ver == DXUT_D3D9_DEVICE){ - deviceSettings.d3d9.pp.Windowed = !deviceSettings.d3d9.pp.Windowed; - if (!deviceSettings.d3d9.pp.Windowed) { - D3DDISPLAYMODE adapterDesktopDisplayMode; - IDirect3D9* pD3D = DXUTGetD3D9Object(); - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - pD3D->GetAdapterDisplayMode( pDeviceSettings->d3d9.AdapterOrdinal, &adapterDesktopDisplayMode ); - deviceSettings.d3d9.pp.BackBufferWidth = adapterDesktopDisplayMode.Width; - deviceSettings.d3d9.pp.BackBufferHeight = adapterDesktopDisplayMode.Height; - deviceSettings.d3d9.pp.BackBufferFormat = adapterDesktopDisplayMode.Format; - } else { - RECT r = DXUTGetWindowClientRectAtModeChange(); - deviceSettings.d3d9.pp.BackBufferHeight= r.bottom; - deviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = 0; - deviceSettings.d3d9.pp.BackBufferWidth = r.right; + memcpy(&adapterDesktopDisplayMode, &s_adapterDesktopDisplayMode, sizeof(DXGI_MODE_DESC)); } + + deviceSettings.d3d11.sd.BufferDesc = adapterDesktopDisplayMode; + } + else + { + RECT r = DXUTGetWindowClientRectAtModeChange(); + deviceSettings.d3d11.sd.BufferDesc.Height = r.bottom; + deviceSettings.d3d11.sd.BufferDesc.Width = r.right; } - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED( hr ) && ( hr != E_ABORT ) ) { // Failed creating device, try to switch back. - HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false ); + HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, false ); if( FAILED( hr2 ) ) { // If this failed, then shutdown @@ -4564,51 +3560,41 @@ HRESULT WINAPI DXUTToggleFullScreen() //-------------------------------------------------------------------------------------- -// Toggle between HAL and WARP +// Toggle between HAL/REF and WARP //-------------------------------------------------------------------------------------- +HRESULT WINAPI DXUTToggleWARP () +{ + auto deviceSettings = DXUTGetDeviceSettings(); -HRESULT WINAPI DXUTToggleWARP () { - HRESULT hr; - - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); - - // Toggle between REF & HAL - if( DXUTIsCurrentDeviceD3D9() ) - { - - } - else + if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE || deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) { - ID3D11SwitchToRef* pD3D11STR = NULL; - ID3D11Device* pDev = DXUTGetD3D11Device(); - assert( pDev != NULL ); - hr = pDev->QueryInterface( __uuidof( *pD3D11STR ), ( LPVOID* )&pD3D11STR ); - if( SUCCEEDED( hr ) ) + if ( !deviceSettings.d3d11.sd.Windowed ) { - pD3D11STR->SetUseRef( pD3D11STR->GetUseRef() ? FALSE : TRUE ); - SAFE_RELEASE( pD3D11STR ); - return S_OK; + // WARP driver type doesn't support fullscreen + return S_FALSE; } - if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE || deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_WARP; - else if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE || deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_WARP; + } + else if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; } - hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); + HRESULT hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); if( SUCCEEDED( hr ) ) { + DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); + // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED( hr ) && ( hr != E_ABORT ) ) { // Failed creating device, try to switch back. - HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false ); + HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, false ); if( FAILED( hr2 ) ) { // If this failed, then shutdown @@ -4619,55 +3605,48 @@ HRESULT WINAPI DXUTToggleWARP () { return hr; } + + //-------------------------------------------------------------------------------------- -// Toggle between HAL and REF +// Toggle between HAL/WARP and REF //-------------------------------------------------------------------------------------- HRESULT WINAPI DXUTToggleREF() { - HRESULT hr; - - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); + auto deviceSettings = DXUTGetDeviceSettings(); - // Toggle between REF & HAL - if( DXUTIsCurrentDeviceD3D9() ) + if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) { - if( deviceSettings.d3d9.DeviceType == D3DDEVTYPE_HAL ) - deviceSettings.d3d9.DeviceType = D3DDEVTYPE_REF; - else if( deviceSettings.d3d9.DeviceType == D3DDEVTYPE_REF ) - deviceSettings.d3d9.DeviceType = D3DDEVTYPE_HAL; + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; } - else + else if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) { - ID3D11SwitchToRef* pD3D11STR = NULL; - ID3D11Device* pDev = DXUTGetD3D11Device(); - assert( pDev != NULL ); - hr = pDev->QueryInterface( __uuidof( *pD3D11STR ), ( LPVOID* )&pD3D11STR ); - if( SUCCEEDED( hr ) ) + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; + } + else if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + if ( !deviceSettings.d3d11.sd.Windowed ) { - pD3D11STR->SetUseRef( pD3D11STR->GetUseRef() ? FALSE : TRUE ); - SAFE_RELEASE( pD3D11STR ); - return S_OK; + // WARP driver type doesn't support fullscreen + return S_FALSE; } - if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; - else if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; } - - hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); + + HRESULT hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); if( SUCCEEDED( hr ) ) { + auto orginalDeviceSettings = DXUTGetDeviceSettings(); + // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED( hr ) && ( hr != E_ABORT ) ) { // Failed creating device, try to switch back. - HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false ); + HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, false ); if( FAILED( hr2 ) ) { // If this failed, then shutdown @@ -4684,48 +3663,54 @@ HRESULT WINAPI DXUTToggleREF() //-------------------------------------------------------------------------------------- void DXUTCheckForDXGIFullScreenSwitch() { - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( !DXUTIsD3D9( pDeviceSettings ) ) - { - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - assert( pSwapChain != NULL ); - DXGI_SWAP_CHAIN_DESC SCDesc; - pSwapChain->GetDesc( &SCDesc ); + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pSwapChain = DXUTGetDXGISwapChain(); + assert( pSwapChain ); + _Analysis_assume_( pSwapChain ); + DXGI_SWAP_CHAIN_DESC SCDesc; + if ( FAILED(pSwapChain->GetDesc(&SCDesc)) ) + memset( &SCDesc, 0, sizeof(SCDesc) ); - BOOL bIsWindowed = ( BOOL )DXUTIsWindowed(); - if( bIsWindowed != SCDesc.Windowed ) - { - pDeviceSettings->d3d11.sd.Windowed = SCDesc.Windowed; + BOOL bIsWindowed = ( BOOL )DXUTIsWindowed(); + if( bIsWindowed != SCDesc.Windowed ) + { + pDeviceSettings->d3d11.sd.Windowed = SCDesc.Windowed; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); + auto deviceSettings = DXUTGetDeviceSettings(); - if( bIsWindowed ) - { - GetDXUTState().SetWindowBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); - GetDXUTState().SetWindowBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); - } - else - { - GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); - GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); - } + if( bIsWindowed ) + { + GetDXUTState().SetWindowBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); + GetDXUTState().SetWindowBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); + } + else + { + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); } } } +_Use_decl_annotations_ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) { HRESULT hr = S_OK; RECT rcCurrentClient; GetClientRect( DXUTGetHWND(), &rcCurrentClient ); - DXUTDeviceSettings* pDevSettings = GetDXUTState().GetCurrentDeviceSettings(); - assert( pDevSettings != NULL ); + auto pDevSettings = GetDXUTState().GetCurrentDeviceSettings(); + assert( pDevSettings ); + _Analysis_assume_( pDevSettings ); + + auto pSwapChain = DXUTGetDXGISwapChain(); - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); + auto pd3dDevice = DXUTGetD3D11Device(); + assert( pd3dDevice ); + _Analysis_assume_( pd3dDevice ); - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); - ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); + auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); + assert( pd3dImmediateContext ); + _Analysis_assume_( pd3dImmediateContext ); // Determine if we're fullscreen pDevSettings->d3d11.sd.Windowed = !bFullScreen; @@ -4734,22 +3719,22 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallbackSwapChainReleasing = GetDXUTState().GetD3D11SwapChainReleasingFunc (); - if( pCallbackSwapChainReleasing != NULL ) + if( pCallbackSwapChainReleasing ) pCallbackSwapChainReleasing( GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); // Release our old depth stencil texture and view - ID3D11Texture2D* pDS = GetDXUTState().GetD3D11DepthStencil(); + auto pDS = GetDXUTState().GetD3D11DepthStencil(); SAFE_RELEASE( pDS ); - GetDXUTState().SetD3D11DepthStencil( NULL ); - ID3D11DepthStencilView* pDSV = GetDXUTState().GetD3D11DepthStencilView(); + GetDXUTState().SetD3D11DepthStencil( nullptr ); + auto pDSV = GetDXUTState().GetD3D11DepthStencilView(); SAFE_RELEASE( pDSV ); - GetDXUTState().SetD3D11DepthStencilView( NULL ); + GetDXUTState().SetD3D11DepthStencilView( nullptr ); // Release our old render target view - ID3D11RenderTargetView* pRTV = GetDXUTState().GetD3D11RenderTargetView(); + auto pRTV = GetDXUTState().GetD3D11RenderTargetView(); SAFE_RELEASE( pRTV ); - GetDXUTState().SetD3D11RenderTargetView( NULL ); + GetDXUTState().SetD3D11RenderTargetView( nullptr ); // Alternate between 0 and DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH when resizing buffers. // When in windowed mode, we want 0 since this allows the app to change to the desktop @@ -4792,10 +3777,10 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) // Call the app's SwapChain reset callback GetDXUTState().SetInsideDeviceCallback( true ); - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); + auto pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallbackSwapChainResized = GetDXUTState().GetD3D11SwapChainResizedFunc(); hr = S_OK; - if( pCallbackSwapChainResized != NULL ) + if( pCallbackSwapChainResized ) hr = pCallbackSwapChainResized( pd3dDevice, pSwapChain, pBackBufferSurfaceDesc, GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); @@ -4807,9 +3792,9 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) hr = DXUTERR_RESETTINGDEVICEOBJECTS; GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallbackSwapChainReleasing = + pCallbackSwapChainReleasing = GetDXUTState().GetD3D11SwapChainReleasingFunc(); - if( pCallbackSwapChainReleasing != NULL ) + if( pCallbackSwapChainReleasing ) pCallbackSwapChainReleasing( GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); DXUTPause( false, false ); @@ -4827,14 +3812,21 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) //-------------------------------------------------------------------------------------- void DXUTCheckForDXGIBufferChange() { - if(DXUTGetDXGISwapChain() != NULL && !GetDXUTState().GetReleasingSwapChain() ) + if(DXUTGetDXGISwapChain() && !GetDXUTState().GetReleasingSwapChain() ) { //DXUTgetdxgi - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); + auto pSwapChain = DXUTGetDXGISwapChain(); + assert(pSwapChain); + _Analysis_assume_(pSwapChain); +// workaround for SAL bug in DXGI header +#pragma warning(push) +#pragma warning( disable:4616 6309 6387 ) // Determine if we're fullscreen BOOL bFullScreen; - pSwapChain->GetFullscreenState( &bFullScreen, NULL ); + if ( FAILED(pSwapChain->GetFullscreenState(&bFullScreen, nullptr)) ) + bFullScreen = FALSE; +#pragma warning(pop) DXUTResizeDXGIBuffers( 0, 0, bFullScreen ); @@ -4849,31 +3841,10 @@ void DXUTCheckForWindowSizeChange() { // Skip the check for various reasons - if( GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() || - ( DXUTIsCurrentDeviceD3D9() && !DXUTIsWindowed() ) ) + if( GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() ) return; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - if( DXUTIsD3D9( &deviceSettings ) ) - { - RECT rcCurrentClient; - GetClientRect( DXUTGetHWND(), &rcCurrentClient ); - - if( ( UINT )rcCurrentClient.right != DXUTGetBackBufferWidthFromDS( &deviceSettings ) || - ( UINT )rcCurrentClient.bottom != DXUTGetBackBufferHeightFromDS( &deviceSettings ) ) - { - // A new window size will require a new backbuffer size size - // Tell DXUTChangeDevice and D3D to size according to the HWND's client rect - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferWidth = 0; else deviceSettings.d3d11.sd.BufferDesc.Width = 0; - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferHeight = 0; else deviceSettings.d3d11.sd.BufferDesc.Height = 0; - - DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); - } - } - else - { - DXUTCheckForDXGIBufferChange(); - } + DXUTCheckForDXGIBufferChange(); } @@ -4897,25 +3868,18 @@ void DXUTCheckForWindowChangingMonitors() if( SUCCEEDED( DXUTGetAdapterOrdinalFromMonitor( hWindowMonitor, &newOrdinal ) ) ) { // Find the closest valid device settings with the new ordinal - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - if( DXUTIsD3D9( &deviceSettings ) ) - { - deviceSettings.d3d9.AdapterOrdinal = newOrdinal; - } - else - { - deviceSettings.d3d11.AdapterOrdinal = newOrdinal; - UINT newOutput; - if( SUCCEEDED( DXUTGetOutputOrdinalFromMonitor( hWindowMonitor, &newOutput ) ) ) - deviceSettings.d3d11.Output = newOutput; - } + auto deviceSettings = DXUTGetDeviceSettings(); + deviceSettings.d3d11.AdapterOrdinal = newOrdinal; + UINT newOutput; + if( SUCCEEDED( DXUTGetOutputOrdinalFromMonitor( hWindowMonitor, &newOutput ) ) ) + deviceSettings.d3d11.Output = newOutput; hr = DXUTSnapDeviceSettingsToEnumDevice( &deviceSettings, false ); if( SUCCEEDED( hr ) ) { // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback if( hr == E_ABORT ) @@ -4935,113 +3899,61 @@ void DXUTCheckForWindowChangingMonitors() } -//-------------------------------------------------------------------------------------- -// Renders the scene using either D3D9 or D3D11 -//-------------------------------------------------------------------------------------- -void WINAPI DXUTRender3DEnvironment() -{ - if( DXUTIsCurrentDeviceD3D9() ) - DXUTRender3DEnvironment9(); - else - DXUTRender3DEnvironment11(); -} - - -//-------------------------------------------------------------------------------------- -// Cleans up both the D3D9 and D3D11 3D environment (but only one should be active at a time) -//-------------------------------------------------------------------------------------- -void DXUTCleanup3DEnvironment( bool bReleaseSettings ) -{ - if( DXUTGetD3D9Device() ) - DXUTCleanup3DEnvironment9( bReleaseSettings ); - if( DXUTGetD3D11Device() ) - DXUTCleanup3DEnvironment11( bReleaseSettings ); -} - - //-------------------------------------------------------------------------------------- // Returns the HMONITOR attached to an adapter/output //-------------------------------------------------------------------------------------- -HMONITOR DXUTGetMonitorFromAdapter( DXUTDeviceSettings* pDeviceSettings ) +HMONITOR DXUTGetMonitorFromAdapter( _In_ DXUTDeviceSettings* pDeviceSettings ) { - if( pDeviceSettings->ver == DXUT_D3D9_DEVICE ) - { - IDirect3D9* pD3D = DXUTGetD3D9Object(); - assert( pD3D != NULL ); - return pD3D->GetAdapterMonitor( pDeviceSettings->d3d9.AdapterOrdinal ); - } - else if( pDeviceSettings->ver == DXUT_D3D11_DEVICE ) - { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - assert( pD3DEnum != NULL ); - CD3D11EnumOutputInfo* pOutputInfo = pD3DEnum->GetOutputInfo( pDeviceSettings->d3d11.AdapterOrdinal, - pDeviceSettings->d3d11.Output ); - if( !pOutputInfo ) - return 0; - return DXUTMonitorFromRect( &pOutputInfo->Desc.DesktopCoordinates, MONITOR_DEFAULTTONEAREST ); - } - - return 0; + auto pD3DEnum = DXUTGetD3D11Enumeration(); + assert( pD3DEnum ); + _Analysis_assume_( pD3DEnum ); + auto pOutputInfo = pD3DEnum->GetOutputInfo( pDeviceSettings->d3d11.AdapterOrdinal, + pDeviceSettings->d3d11.Output ); + if( !pOutputInfo ) + return 0; + return DXUTMonitorFromRect( &pOutputInfo->Desc.DesktopCoordinates, MONITOR_DEFAULTTONEAREST ); } //-------------------------------------------------------------------------------------- // Look for an adapter ordinal that is tied to a HMONITOR //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal ) { *pAdapterOrdinal = 0; - if( DXUTIsCurrentDeviceD3D9() ) - { - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - IDirect3D9* pD3D = DXUTGetD3D9Object(); + // Get the monitor handle information + MONITORINFOEX mi; + mi.cbSize = sizeof( MONITORINFOEX ); + DXUTGetMonitorInfo( hMonitor, &mi ); - CGrowableArray * pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); iAdapter++ ) + // Search for this monitor in our enumeration hierarchy. + auto pd3dEnum = DXUTGetD3D11Enumeration(); + auto pAdapterList = pd3dEnum->GetAdapterInfoList(); + for( auto it = pAdapterList->cbegin(); it != pAdapterList->cend(); ++it ) + { + auto pAdapterInfo = *it; + for( auto jit = pAdapterInfo->outputInfoList.cbegin(); jit != pAdapterInfo->outputInfoList.cend(); ++jit ) { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); - HMONITOR hAdapterMonitor = pD3D->GetAdapterMonitor( pAdapterInfo->AdapterOrdinal ); - if( hAdapterMonitor == hMonitor ) + auto pOutputInfo = *jit; + // Convert output device name from MBCS to Unicode + if( wcsncmp( pOutputInfo->Desc.DeviceName, mi.szDevice, sizeof( mi.szDevice ) / sizeof + ( mi.szDevice[0] ) ) == 0 ) { *pAdapterOrdinal = pAdapterInfo->AdapterOrdinal; return S_OK; } } } - else - { - // Get the monitor handle information - MONITORINFOEX mi; - mi.cbSize = sizeof( MONITORINFOEX ); - DXUTGetMonitorInfo( hMonitor, &mi ); - - // Search for this monitor in our enumeration hierarchy. - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - CGrowableArray * pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); ++iAdapter ) - { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); - for( int o = 0; o < pAdapterInfo->outputInfoList.GetSize(); ++o ) - { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( o ); - // Convert output device name from MBCS to Unicode - if( wcsncmp( pOutputInfo->Desc.DeviceName, mi.szDevice, sizeof( mi.szDevice ) / sizeof - ( mi.szDevice[0] ) ) == 0 ) - { - *pAdapterOrdinal = pAdapterInfo->AdapterOrdinal; - return S_OK; - } - } - } - } - return E_FAIL; } + //-------------------------------------------------------------------------------------- // Look for a monitor ordinal that is tied to a HMONITOR (D3D11-only) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal ) { // Get the monitor handle information @@ -5050,16 +3962,17 @@ HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal DXUTGetMonitorInfo( hMonitor, &mi ); // Search for this monitor in our enumeration hierarchy. - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - CGrowableArray * pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); ++iAdapter ) + auto pd3dEnum = DXUTGetD3D11Enumeration(); + auto pAdapterList = pd3dEnum->GetAdapterInfoList(); + for( auto it = pAdapterList->cbegin(); it != pAdapterList->cend(); ++it ) { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); - for( int o = 0; o < pAdapterInfo->outputInfoList.GetSize(); ++o ) + auto pAdapterInfo = *it; + for( auto jit = pAdapterInfo->outputInfoList.cbegin(); jit != pAdapterInfo->outputInfoList.cend(); ++jit ) { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( o ); + auto pOutputInfo = *jit; DXGI_OUTPUT_DESC Desc; - pOutputInfo->m_pOutput->GetDesc( &Desc ); + if ( FAILED(pOutputInfo->m_pOutput->GetDesc(&Desc)) ) + memset( &Desc, 0, sizeof(Desc) ); if( hMonitor == Desc.Monitor ) { @@ -5072,6 +3985,7 @@ HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal return E_FAIL; } + //-------------------------------------------------------------------------------------- // This method is called when D3DERR_DEVICEREMOVED is returned from an API. DXUT // calls the application's DeviceRemoved callback to inform it of the event. The @@ -5091,7 +4005,7 @@ HRESULT DXUTHandleDeviceRemoved() if( bLookForNewDevice ) { - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); hr = DXUTSnapDeviceSettingsToEnumDevice( pDeviceSettings, false); @@ -5099,7 +4013,7 @@ HRESULT DXUTHandleDeviceRemoved() { // Change to a Direct3D device created from the new device settings // that is compatible with the removed device. - hr = DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ); + hr = DXUTChangeDevice( pDeviceSettings, false ); if( SUCCEEDED( hr ) ) return S_OK; } @@ -5115,38 +4029,23 @@ HRESULT DXUTHandleDeviceRemoved() //-------------------------------------------------------------------------------------- void DXUTUpdateBackBufferDesc() { - if( DXUTIsCurrentDeviceD3D9() ) - { - HRESULT hr; - IDirect3DSurface9* pBackBuffer; - hr = GetDXUTState().GetD3D9Device()->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ); - D3DSURFACE_DESC* pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc9(); - ZeroMemory( pBBufferSurfaceDesc, sizeof( D3DSURFACE_DESC ) ); - if( SUCCEEDED( hr ) ) - { - pBackBuffer->GetDesc( pBBufferSurfaceDesc ); - SAFE_RELEASE( pBackBuffer ); - } - } - else + HRESULT hr; + ID3D11Texture2D* pBackBuffer; + auto pSwapChain = GetDXUTState().GetDXGISwapChain(); + assert( pSwapChain ); + _Analysis_assume_( pSwapChain ); + hr = pSwapChain->GetBuffer( 0, IID_PPV_ARGS(&pBackBuffer) ); + auto pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); + ZeroMemory( pBBufferSurfaceDesc, sizeof( DXGI_SURFACE_DESC ) ); + if( SUCCEEDED( hr ) ) { - HRESULT hr; - ID3D11Texture2D* pBackBuffer; - IDXGISwapChain* pSwapChain = GetDXUTState().GetDXGISwapChain(); - assert( pSwapChain != NULL ); - hr = pSwapChain->GetBuffer( 0, __uuidof( *pBackBuffer ), ( LPVOID* )&pBackBuffer ); - DXGI_SURFACE_DESC* pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); - ZeroMemory( pBBufferSurfaceDesc, sizeof( DXGI_SURFACE_DESC ) ); - if( SUCCEEDED( hr ) ) - { - D3D11_TEXTURE2D_DESC TexDesc; - pBackBuffer->GetDesc( &TexDesc ); - pBBufferSurfaceDesc->Width = ( UINT )TexDesc.Width; - pBBufferSurfaceDesc->Height = ( UINT )TexDesc.Height; - pBBufferSurfaceDesc->Format = TexDesc.Format; - pBBufferSurfaceDesc->SampleDesc = TexDesc.SampleDesc; - SAFE_RELEASE( pBackBuffer ); - } + D3D11_TEXTURE2D_DESC TexDesc; + pBackBuffer->GetDesc( &TexDesc ); + pBBufferSurfaceDesc->Width = ( UINT )TexDesc.Width; + pBBufferSurfaceDesc->Height = ( UINT )TexDesc.Height; + pBBufferSurfaceDesc->Format = TexDesc.Format; + pBBufferSurfaceDesc->SampleDesc = TexDesc.SampleDesc; + SAFE_RELEASE( pBackBuffer ); } } @@ -5156,54 +4055,17 @@ void DXUTUpdateBackBufferDesc() //-------------------------------------------------------------------------------------- void DXUTSetupCursor() { - if( DXUTIsCurrentDeviceD3D9() ) + // Clip cursor if requested + if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() ) { - // Show the cursor again if returning to fullscreen - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( !DXUTIsWindowed() && pd3dDevice ) - { - if( GetDXUTState().GetShowCursorWhenFullScreen() ) - { - SetCursor( NULL ); // Turn off Windows cursor in full screen mode - HCURSOR hCursor = ( HCURSOR )( ULONG_PTR )GetClassLongPtr( DXUTGetHWNDDeviceFullScreen(), - GCLP_HCURSOR ); - DXUTSetD3D9DeviceCursor( pd3dDevice, hCursor, false ); - DXUTGetD3D9Device()->ShowCursor( true ); - } - else - { - SetCursor( NULL ); // Turn off Windows cursor in full screen mode - DXUTGetD3D9Device()->ShowCursor( false ); - } - } - - // Clip cursor if requested - if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() ) - { - // Confine cursor to full screen window - RECT rcWindow; - GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow ); - ClipCursor( &rcWindow ); - } - else - { - ClipCursor( NULL ); - } + // Confine cursor to full screen window + RECT rcWindow; + GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow ); + ClipCursor( &rcWindow ); } else { - // Clip cursor if requested - if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() ) - { - // Confine cursor to full screen window - RECT rcWindow; - GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow ); - ClipCursor( &rcWindow ); - } - else - { - ClipCursor( NULL ); - } + ClipCursor( nullptr ); } } @@ -5216,92 +4078,32 @@ void DXUTUpdateStaticFrameStats() if( GetDXUTState().GetNoStats() ) return; - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( NULL == pDeviceSettings ) + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + if( !pDeviceSettings ) return; - if( DXUTIsD3D9( pDeviceSettings ) ) - { - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - if( NULL == pd3dEnum ) - return; - - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, - pDeviceSettings->d3d9.AdapterFormat, pDeviceSettings->d3d9.pp.BackBufferFormat, - pDeviceSettings->d3d9.pp.Windowed ); - if( NULL == pDeviceSettingsCombo ) - return; - - WCHAR strFmt[100]; - D3DPRESENT_PARAMETERS* pPP = &pDeviceSettings->d3d9.pp; - - if( pDeviceSettingsCombo->AdapterFormat == pDeviceSettingsCombo->BackBufferFormat ) - { - wcscpy_s( strFmt, 100, DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) ); - } - else - { - swprintf_s( strFmt, 100, L"backbuf %s, adapter %s", - DXUTD3DFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ), - DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) ); - } - - WCHAR strDepthFmt[100]; - if( pPP->EnableAutoDepthStencil ) - { - swprintf_s( strDepthFmt, 100, L" (%s)", DXUTD3DFormatToString( pPP->AutoDepthStencilFormat, false ) ); - } - else - { - // No depth buffer - strDepthFmt[0] = 0; - } - - WCHAR strMultiSample[100]; - switch( pPP->MultiSampleType ) - { - case D3DMULTISAMPLE_NONMASKABLE: - wcscpy_s( strMultiSample, 100, L" (Nonmaskable Multisample)" ); break; - case D3DMULTISAMPLE_NONE: - wcscpy_s( strMultiSample, 100, L"" ); break; - default: - swprintf_s( strMultiSample, 100, L" (%dx Multisample)", pPP->MultiSampleType ); break; - } - - WCHAR* pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats(); - swprintf_s( pstrStaticFrameStats, 256, L"D3D9 %%sVsync %s (%dx%d), %s%s%s", - ( pPP->PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE ) ? L"off" : L"on", - pPP->BackBufferWidth, pPP->BackBufferHeight, - strFmt, strDepthFmt, strMultiSample ); - } - else - { - // D3D11 - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - if( NULL == pd3dEnum ) - return; - - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d11.AdapterOrdinal, pDeviceSettings->d3d11.DriverType, pDeviceSettings->d3d11.Output, - pDeviceSettings->d3d11.sd.BufferDesc.Format, pDeviceSettings->d3d11.sd.Windowed ); - if( NULL == pDeviceSettingsCombo ) - return; - - WCHAR strFmt[100]; - - wcscpy_s( strFmt, 100, DXUTDXGIFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ) ); + // D3D11 + auto pd3dEnum = DXUTGetD3D11Enumeration(); + if( !pd3dEnum ) + return; - WCHAR strMultiSample[100]; - swprintf_s( strMultiSample, 100, L" (MS%u, Q%u)", pDeviceSettings->d3d11.sd.SampleDesc.Count, - pDeviceSettings->d3d11.sd.SampleDesc.Quality ); + auto pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( + pDeviceSettings->d3d11.AdapterOrdinal, + pDeviceSettings->d3d11.sd.BufferDesc.Format, pDeviceSettings->d3d11.sd.Windowed ); + if( !pDeviceSettingsCombo ) + return; - WCHAR* pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats(); - swprintf_s( pstrStaticFrameStats, 256, L"D3D11 %%sVsync %s (%dx%d), %s%s", - ( pDeviceSettings->d3d11.SyncInterval == 0 ) ? L"off" : L"on", - pDeviceSettings->d3d11.sd.BufferDesc.Width, pDeviceSettings->d3d11.sd.BufferDesc.Height, - strFmt, strMultiSample ); - } + WCHAR strFmt[100]; + wcscpy_s( strFmt, 100, DXUTDXGIFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ) ); + + WCHAR strMultiSample[100]; + swprintf_s( strMultiSample, 100, L" (MS%u, Q%u)", pDeviceSettings->d3d11.sd.SampleDesc.Count, + pDeviceSettings->d3d11.sd.SampleDesc.Quality ); + auto pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats(); + swprintf_s( pstrStaticFrameStats, 256, L"D3D11 %%ls Vsync %ls (%ux%u), %ls%ls", + ( pDeviceSettings->d3d11.SyncInterval == 0 ) ? L"off" : L"on", + pDeviceSettings->d3d11.sd.BufferDesc.Width, pDeviceSettings->d3d11.sd.BufferDesc.Height, + strFmt, strMultiSample ); } @@ -5328,21 +4130,23 @@ void DXUTUpdateFrameStats() GetDXUTState().SetLastStatsUpdateTime( fAbsTime ); GetDXUTState().SetLastStatsUpdateFrames( 0 ); - WCHAR* pstrFPS = GetDXUTState().GetFPSStats(); + auto pstrFPS = GetDXUTState().GetFPSStats(); swprintf_s( pstrFPS, 64, L"%0.2f fps ", fFPS ); } } + //-------------------------------------------------------------------------------------- // Returns a string describing the current device. If bShowFPS is true, then // the string contains the frames/sec. If "-nostats" was used in // the command line, the string will be blank //-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTGetFrameStats( bool bShowFPS ) +LPCWSTR WINAPI DXUTGetFrameStats( _In_ bool bShowFPS ) { - WCHAR* pstrFrameStats = GetDXUTState().GetFrameStats(); - WCHAR* pstrFPS = ( bShowFPS ) ? GetDXUTState().GetFPSStats() : L""; - swprintf_s( pstrFrameStats, 256, GetDXUTState().GetStaticFrameStats(), pstrFPS ); + auto pstrFrameStats = GetDXUTState().GetFrameStats(); + const WCHAR* pstrFPS = ( bShowFPS ) ? GetDXUTState().GetFPSStats() : L""; + WCHAR* pstrStats = GetDXUTState().GetStaticFrameStats(); + swprintf_s( pstrFrameStats, 256, pstrStats, pstrFPS ); return pstrFrameStats; } @@ -5350,63 +4154,15 @@ LPCWSTR WINAPI DXUTGetFrameStats( bool bShowFPS ) //-------------------------------------------------------------------------------------- // Updates the string which describes the device //-------------------------------------------------------------------------------------- -void DXUTUpdateD3D9DeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, - D3DADAPTER_IDENTIFIER9* pAdapterIdentifier ) -{ - if( GetDXUTState().GetNoStats() ) - return; - - // Store device description - WCHAR* pstrDeviceStats = GetDXUTState().GetDeviceStats(); - if( DeviceType == D3DDEVTYPE_REF ) - wcscpy_s( pstrDeviceStats, 256, L"REF" ); - else if( DeviceType == D3DDEVTYPE_HAL ) - wcscpy_s( pstrDeviceStats, 256, L"HAL" ); - else if( DeviceType == D3DDEVTYPE_SW ) - wcscpy_s( pstrDeviceStats, 256, L"SW" ); - - if( DeviceType == D3DDEVTYPE_HAL ) - { - // Be sure not to overflow m_strDeviceStats when appending the adapter - // description, since it can be long. - wcscat_s( pstrDeviceStats, 256, L": " ); - - // Try to get a unique description from the CD3D9EnumDeviceSettingsCombo - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( !pDeviceSettings ) - return; - - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, - pDeviceSettings->d3d9.AdapterFormat, pDeviceSettings->d3d9.pp.BackBufferFormat, - pDeviceSettings->d3d9.pp.Windowed ); - if( pDeviceSettingsCombo ) - { - wcscat_s( pstrDeviceStats, 256, pDeviceSettingsCombo->pAdapterInfo->szUniqueDescription ); - } - else - { - const int cchDesc = sizeof( pAdapterIdentifier->Description ); - WCHAR szDescription[cchDesc]; - MultiByteToWideChar( CP_ACP, 0, pAdapterIdentifier->Description, -1, szDescription, cchDesc ); - szDescription[cchDesc - 1] = 0; - wcscat_s( pstrDeviceStats, 256, szDescription ); - } - } -} - - -//-------------------------------------------------------------------------------------- -// Updates the string which describes the device -//-------------------------------------------------------------------------------------- -void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* pAdapterDesc ) +#pragma warning( suppress : 6101 ) +_Use_decl_annotations_ +void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, D3D_FEATURE_LEVEL featureLevel, DXGI_ADAPTER_DESC* pAdapterDesc ) { - if( GetDXUTState().GetNoStats() ) + if( GetDXUTState().GetNoStats() ) return; // Store device description - WCHAR* pstrDeviceStats = GetDXUTState().GetDeviceStats(); + auto pstrDeviceStats = GetDXUTState().GetDeviceStats(); if( DeviceType == D3D_DRIVER_TYPE_REFERENCE ) wcscpy_s( pstrDeviceStats, 256, L"REFERENCE" ); else if( DeviceType == D3D_DRIVER_TYPE_HARDWARE ) @@ -5423,20 +4179,54 @@ void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* wcscat_s( pstrDeviceStats, 256, L": " ); // Try to get a unique description from the CD3D11EnumDeviceSettingsCombo - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if( !pDeviceSettings ) return; - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - assert( pd3dEnum != NULL ); - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d11.AdapterOrdinal, pDeviceSettings->d3d11.DriverType, pDeviceSettings->d3d11.Output, + auto pd3dEnum = DXUTGetD3D11Enumeration(); + assert( pd3dEnum ); + _Analysis_assume_( pd3dEnum ); + auto pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( + pDeviceSettings->d3d11.AdapterOrdinal, pDeviceSettings->d3d11.sd.BufferDesc.Format, pDeviceSettings->d3d11.sd.Windowed ); if( pDeviceSettingsCombo ) wcscat_s( pstrDeviceStats, 256, pDeviceSettingsCombo->pAdapterInfo->szUniqueDescription ); else wcscat_s( pstrDeviceStats, 256, pAdapterDesc->Description ); } + + switch( featureLevel ) + { + case D3D_FEATURE_LEVEL_9_1: + wcscat_s( pstrDeviceStats, 256, L" (FL 9.1)" ); + break; + case D3D_FEATURE_LEVEL_9_2: + wcscat_s( pstrDeviceStats, 256, L" (FL 9.2)" ); + break; + case D3D_FEATURE_LEVEL_9_3: + wcscat_s( pstrDeviceStats, 256, L" (FL 9.3)" ); + break; + case D3D_FEATURE_LEVEL_10_0: + wcscat_s( pstrDeviceStats, 256, L" (FL 10.0)" ); + break; + case D3D_FEATURE_LEVEL_10_1: + wcscat_s( pstrDeviceStats, 256, L" (FL 10.1)" ); + break; + case D3D_FEATURE_LEVEL_11_0: + wcscat_s( pstrDeviceStats, 256, L" (FL 11.0)" ); + break; + case D3D_FEATURE_LEVEL_11_1: + wcscat_s( pstrDeviceStats, 256, L" (FL 11.1)" ); + break; +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + case D3D_FEATURE_LEVEL_12_0: + wcscat_s(pstrDeviceStats, 256, L" (FL 12.0)"); + break; + case D3D_FEATURE_LEVEL_12_1: + wcscat_s(pstrDeviceStats, 256, L" (FL 12.1)"); + break; +#endif + } } @@ -5447,45 +4237,24 @@ DXUTDeviceSettings WINAPI DXUTGetDeviceSettings() { // Return a copy of device settings of the current device. If no device exists yet, then // return a blank device settings struct - DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); + auto pDS = GetDXUTState().GetCurrentDeviceSettings(); if( pDS ) { return *pDS; } else { - DXUTDeviceSettings ds; - ZeroMemory( &ds, sizeof( DXUTDeviceSettings ) ); + DXUTDeviceSettings ds = {}; return ds; } } -D3DPRESENT_PARAMETERS WINAPI DXUTGetD3D9PresentParameters() -{ - // Return a copy of the present params of the current device. If no device exists yet, then - // return blank present params - DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); - if( pDS ) - { - return pDS->d3d9.pp; - } - else - { - D3DPRESENT_PARAMETERS pp; - ZeroMemory( &pp, sizeof( D3DPRESENT_PARAMETERS ) ); - return pp; - } -} - bool WINAPI DXUTIsVsyncEnabled() { - DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); + auto pDS = GetDXUTState().GetCurrentDeviceSettings(); if( pDS ) { - if( DXUTIsD3D9( pDS ) ) - return ( pDS->d3d9.pp.PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE ); - else - return ( pDS->d3d11.SyncInterval == 0 ); + return ( pDS->d3d11.SyncInterval == 0 ); } else { @@ -5493,15 +4262,7 @@ bool WINAPI DXUTIsVsyncEnabled() } }; -HRESULT WINAPI DXUTGetD3D9DeviceCaps( DXUTDeviceSettings* pDeviceSettings, D3DCAPS9* pCaps ) -{ - IDirect3D9* pD3D = DXUTGetD3D9Object(); - assert( pD3D != NULL ); - return pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, pCaps ); -} - - -bool WINAPI DXUTIsKeyDown( BYTE vKey ) +bool WINAPI DXUTIsKeyDown( _In_ BYTE vKey ) { bool* bKeys = GetDXUTState().GetKeys(); if( vKey >= 0xA0 && vKey <= 0xA5 ) // VK_LSHIFT, VK_RSHIFT, VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU @@ -5512,7 +4273,7 @@ bool WINAPI DXUTIsKeyDown( BYTE vKey ) return bKeys[vKey]; } -bool WINAPI DXUTWasKeyPressed( BYTE vKey ) +bool WINAPI DXUTWasKeyPressed( _In_ BYTE vKey ) { bool* bLastKeys = GetDXUTState().GetLastKeys(); bool* bKeys = GetDXUTState().GetKeys(); @@ -5520,18 +4281,19 @@ bool WINAPI DXUTWasKeyPressed( BYTE vKey ) return ( !bLastKeys[vKey] && bKeys[vKey] ); } -bool WINAPI DXUTIsMouseButtonDown( BYTE vButton ) +bool WINAPI DXUTIsMouseButtonDown( _In_ BYTE vButton ) { bool* bMouseButtons = GetDXUTState().GetMouseButtons(); int nIndex = DXUTMapButtonToArrayIndex( vButton ); return bMouseButtons[nIndex]; } -void WINAPI DXUTSetMultimonSettings( bool bAutoChangeAdapter ) +void WINAPI DXUTSetMultimonSettings( _In_ bool bAutoChangeAdapter ) { GetDXUTState().SetAutoChangeAdapter( bAutoChangeAdapter ); } +_Use_decl_annotations_ void WINAPI DXUTSetHotkeyHandling( bool bAltEnterToToggleFullscreen, bool bEscapeToQuit, bool bPauseToToggleTimePause ) { GetDXUTState().SetHandleEscape( bEscapeToQuit ); @@ -5539,6 +4301,7 @@ void WINAPI DXUTSetHotkeyHandling( bool bAltEnterToToggleFullscreen, bool bEscap GetDXUTState().SetHandlePause( bPauseToToggleTimePause ); } +_Use_decl_annotations_ void WINAPI DXUTSetCursorSettings( bool bShowCursorWhenFullScreen, bool bClipCursorWhenFullScreen ) { GetDXUTState().SetClipCursorWhenFullScreen( bClipCursorWhenFullScreen ); @@ -5546,11 +4309,12 @@ void WINAPI DXUTSetCursorSettings( bool bShowCursorWhenFullScreen, bool bClipCur DXUTSetupCursor(); } -void WINAPI DXUTSetWindowSettings( bool bCallDefWindowProc ) +void WINAPI DXUTSetWindowSettings( _In_ bool bCallDefWindowProc ) { GetDXUTState().SetCallDefWindowProc( bCallDefWindowProc ); } +_Use_decl_annotations_ void WINAPI DXUTSetConstantFrameTime( bool bEnabled, float fTimePerFrame ) { if( GetDXUTState().GetOverrideConstantFrameTime() ) @@ -5576,10 +4340,10 @@ void WINAPI DXUTResetFrameworkState() //-------------------------------------------------------------------------------------- // Closes down the window. When the window closes, it will cleanup everything //-------------------------------------------------------------------------------------- -void WINAPI DXUTShutdown( int nExitCode ) +void WINAPI DXUTShutdown( _In_ int nExitCode ) { HWND hWnd = DXUTGetHWND(); - if( hWnd != NULL ) + if( hWnd ) SendMessage( hWnd, WM_CLOSE, 0, 0 ); GetDXUTState().SetExitCode( nExitCode ); @@ -5596,40 +4360,32 @@ void WINAPI DXUTShutdown( int nExitCode ) // restored when the crashed app is run again. DXUTAllowShortcutKeys( true ); - // Shutdown D3D9 - IDirect3D9* pD3D = GetDXUTState().GetD3D9(); - SAFE_RELEASE( pD3D ); - GetDXUTState().SetD3D9( NULL ); - // Shutdown D3D11 - IDXGIFactory1* pDXGIFactory = GetDXUTState().GetDXGIFactory(); + auto pDXGIFactory = GetDXUTState().GetDXGIFactory(); SAFE_RELEASE( pDXGIFactory ); - GetDXUTState().SetDXGIFactory( NULL ); - - if( GetDXUTState().GetOverrideRelaunchMCE() ) - DXUTReLaunchMediaCenter(); + GetDXUTState().SetDXGIFactory( nullptr ); } + //-------------------------------------------------------------------------------------- // Tells DXUT whether to operate in gamma correct mode //-------------------------------------------------------------------------------------- -void WINAPI DXUTSetIsInGammaCorrectMode( bool bGammaCorrect ) +void WINAPI DXUTSetIsInGammaCorrectMode( _In_ bool bGammaCorrect ) { GetDXUTState().SetIsInGammaCorrectMode( bGammaCorrect ); } -void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings) { +//-------------------------------------------------------------------------------------- +void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings) +{ ZeroMemory( modifySettings, sizeof( DXUTDeviceSettings ) ); - - modifySettings->ver = DXUT_D3D11_DEVICE; modifySettings->d3d11.AdapterOrdinal = 0; modifySettings->d3d11.AutoCreateDepthStencil = true; modifySettings->d3d11.AutoDepthStencilFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; #if defined(DEBUG) || defined(_DEBUG) - modifySettings->d3d11.CreateFlags |= D3D10_CREATE_DEVICE_DEBUG; - modifySettings->d3d11.CreateFlags = 0; //by simanies: this is a bug on my machine and does not allow to create D3D Devices with debug + modifySettings->d3d11.CreateFlags |= D3D11_CREATE_DEVICE_DEBUG; #else modifySettings->d3d11.CreateFlags = 0; #endif @@ -5638,224 +4394,123 @@ void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings) { modifySettings->d3d11.PresentFlags = 0; modifySettings->d3d11.sd.BufferCount = 2; modifySettings->d3d11.sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - modifySettings->d3d11.sd.BufferDesc.Height = 480; - modifySettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = 60; - modifySettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = 1; + modifySettings->d3d11.sd.BufferDesc.Height = 600; + modifySettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = 0; + modifySettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = 0; modifySettings->d3d11.sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; modifySettings->d3d11.sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; - modifySettings->d3d11.sd.BufferDesc.Width = 640; + modifySettings->d3d11.sd.BufferDesc.Width = 800; modifySettings->d3d11.sd.BufferUsage = 32; modifySettings->d3d11.sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ; modifySettings->d3d11.sd.OutputWindow = DXUTGetHWND(); modifySettings->d3d11.sd.SampleDesc.Count = 1; modifySettings->d3d11.sd.SampleDesc.Quality = 0; modifySettings->d3d11.sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; - modifySettings->d3d11.sd.Windowed = 1; + modifySettings->d3d11.sd.Windowed = TRUE; modifySettings->d3d11.SyncInterval = 0; - - modifySettings->d3d9.AdapterFormat = D3DFMT_X8R8G8B8; - modifySettings->d3d9.AdapterOrdinal = 0; - modifySettings->d3d9.BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING; - modifySettings->d3d9.DeviceType = D3DDEVTYPE_HAL; - modifySettings->d3d9.pp.AutoDepthStencilFormat = D3DFMT_D24X8; - modifySettings->d3d9.pp.BackBufferCount = 1; - modifySettings->d3d9.pp.BackBufferFormat = D3DFMT_X8R8G8B8; - modifySettings->d3d9.pp.BackBufferHeight = 480; - modifySettings->d3d9.pp.BackBufferWidth = 640; - modifySettings->d3d9.pp.EnableAutoDepthStencil = 1; - modifySettings->d3d9.pp.Flags = 2; - modifySettings->d3d9.pp.FullScreen_RefreshRateInHz = 0; - modifySettings->d3d9.pp.hDeviceWindow = DXUTGetHWND(); - modifySettings->d3d9.pp.MultiSampleQuality = 0; - modifySettings->d3d9.pp.MultiSampleType = D3DMULTISAMPLE_NONE; - modifySettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - modifySettings->d3d9.pp.SwapEffect = D3DSWAPEFFECT_DISCARD; - modifySettings->d3d9.pp.Windowed = 1; } - //-------------------------------------------------------------------------------------- // Update settings based on what is enumeratabled //-------------------------------------------------------------------------------------- -HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL ) { - bool bAppSupportsD3D9 = DXUTDoesAppSupportD3D9(); - bool bAppSupportsD3D11 = DXUTDoesAppSupportD3D11(); - - if( GetSystemMetrics(0x1000) != 0 ) {// SM_REMOTESESSION - pDeviceSettings->d3d11.sd.Windowed = 1; - pDeviceSettings->d3d9.pp.Windowed = 1; +_Use_decl_annotations_ +HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL ) +{ + if( GetSystemMetrics(SM_REMOTESESSION) != 0 ) + { + pDeviceSettings->d3d11.sd.Windowed = TRUE; } int bestModeIndex=0; int bestMSAAIndex=0; - //DXUTSetDefaultDeviceSettings - if (bAppSupportsD3D11 && pDeviceSettings->ver == DXUT_D3D11_DEVICE ) { - CD3D11Enumeration *pEnum = NULL; - - - pEnum = DXUTGetD3D11Enumeration( forceEnum, false, forceFL); + CD3D11Enumeration *pEnum = DXUTGetD3D11Enumeration( forceEnum, true, forceFL); - CD3D11EnumAdapterInfo* pAdapterInfo = NULL; - CGrowableArray * pAdapterList = pEnum->GetAdapterInfoList(); - CD3D11EnumAdapterInfo* tempAdapterInfo = pAdapterList->GetAt( 0 ); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); iAdapter++ ) + CD3D11EnumAdapterInfo* pAdapterInfo = nullptr; + auto pAdapterList = pEnum->GetAdapterInfoList(); + for( auto it = pAdapterList->cbegin(); it != pAdapterList->cend(); ++it ) + { + auto tempAdapterInfo = *it; + if (tempAdapterInfo->AdapterOrdinal == pDeviceSettings->d3d11.AdapterOrdinal) pAdapterInfo = tempAdapterInfo; + } + if ( !pAdapterInfo ) + { + if ( pAdapterList->empty() || pDeviceSettings->d3d11.AdapterOrdinal > 0 ) { - tempAdapterInfo = pAdapterList->GetAt( iAdapter ); - if (tempAdapterInfo->AdapterOrdinal == pDeviceSettings->d3d11.AdapterOrdinal) pAdapterInfo = tempAdapterInfo; + return E_FAIL; // no adapters found. } - if (pAdapterInfo == NULL) return E_FAIL; // no adapters found. - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = NULL; - float biggestScore = 0; + pAdapterInfo = *pAdapterList->cbegin(); + } + CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = nullptr; + float biggestScore = 0; - int combo = 0; - for( int iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) - { - CD3D11EnumDeviceSettingsCombo* tempDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList.GetAt( iDeviceCombo ); + for( size_t iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.size(); iDeviceCombo++ ) + { + CD3D11EnumDeviceSettingsCombo* tempDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList[ iDeviceCombo ]; - DXGI_MODE_DESC adapterDisplayMode; - DXUTGetD3D11AdapterDisplayMode( pAdapterInfo->AdapterOrdinal, 0, &adapterDisplayMode ); - - int bestMode; - int bestMSAA; - float score = DXUTRankD3D11DeviceCombo(tempDeviceSettingsCombo, &(pDeviceSettings->d3d11), &adapterDisplayMode, bestMode, bestMSAA ); - if (score > biggestScore) { - combo = iDeviceCombo; - biggestScore = score; - pDeviceSettingsCombo = tempDeviceSettingsCombo; - bestModeIndex = bestMode; - bestMSAAIndex = bestMSAA; - } - - } - if (NULL == pDeviceSettingsCombo ) { - return E_FAIL; // no settigns found. + int bestMode; + int bestMSAA; + float score = DXUTRankD3D11DeviceCombo(tempDeviceSettingsCombo, &(pDeviceSettings->d3d11), bestMode, bestMSAA ); + if (score > biggestScore) + { + biggestScore = score; + pDeviceSettingsCombo = tempDeviceSettingsCombo; + bestModeIndex = bestMode; + bestMSAAIndex = bestMSAA; } + } + if (!pDeviceSettingsCombo ) + { + return E_FAIL; // no settings found. + } - pDeviceSettings->d3d11.AdapterOrdinal = pDeviceSettingsCombo->AdapterOrdinal; - pDeviceSettings->d3d11.DriverType = pDeviceSettingsCombo->DeviceType; - pDeviceSettings->d3d11.Output = pDeviceSettingsCombo->Output; + pDeviceSettings->d3d11.AdapterOrdinal = pDeviceSettingsCombo->AdapterOrdinal; + pDeviceSettings->d3d11.DriverType = pDeviceSettingsCombo->DeviceType; + pDeviceSettings->d3d11.Output = pDeviceSettingsCombo->Output; - pDeviceSettings->d3d11.sd.Windowed = pDeviceSettingsCombo->Windowed; - if( GetSystemMetrics(0x1000) != 0 ) {// SM_REMOTESESSION - pDeviceSettings->d3d11.sd.Windowed = 1; - } - if (pDeviceSettingsCombo->pOutputInfo != NULL) { - DXGI_MODE_DESC bestDisplayMode; - bestDisplayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList.GetAt(bestModeIndex); - if (!pDeviceSettingsCombo->Windowed) { - - pDeviceSettings->d3d11.sd.BufferDesc.Height = bestDisplayMode.Height; - pDeviceSettings->d3d11.sd.BufferDesc.Width = bestDisplayMode.Width; - pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = bestDisplayMode.RefreshRate.Numerator; - pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = bestDisplayMode.RefreshRate.Denominator; - pDeviceSettings->d3d11.sd.BufferDesc.Scaling = bestDisplayMode.Scaling; - pDeviceSettings->d3d11.sd.BufferDesc.ScanlineOrdering = bestDisplayMode.ScanlineOrdering; - } + pDeviceSettings->d3d11.sd.Windowed = pDeviceSettingsCombo->Windowed; + if( GetSystemMetrics(SM_REMOTESESSION) != 0 ) + { + pDeviceSettings->d3d11.sd.Windowed = TRUE; + } + if (pDeviceSettingsCombo->pOutputInfo) + { + auto bestDisplayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList[ bestModeIndex ]; + if (!pDeviceSettingsCombo->Windowed) + { + pDeviceSettings->d3d11.sd.BufferDesc.Height = bestDisplayMode.Height; + pDeviceSettings->d3d11.sd.BufferDesc.Width = bestDisplayMode.Width; + pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = bestDisplayMode.RefreshRate.Numerator; + pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = bestDisplayMode.RefreshRate.Denominator; + pDeviceSettings->d3d11.sd.BufferDesc.Scaling = bestDisplayMode.Scaling; + pDeviceSettings->d3d11.sd.BufferDesc.ScanlineOrdering = bestDisplayMode.ScanlineOrdering; } - if (pDeviceSettings->d3d11.DeviceFeatureLevel == 0) - pDeviceSettings->d3d11.DeviceFeatureLevel = pDeviceSettingsCombo->pDeviceInfo->SelectedLevel; - - - - - pDeviceSettings->d3d11.sd.SampleDesc.Count = pDeviceSettingsCombo->multiSampleCountList.GetAt(bestMSAAIndex); - if (pDeviceSettings->d3d11.sd.SampleDesc.Quality > pDeviceSettingsCombo->multiSampleQualityList.GetAt(bestMSAAIndex) - 1) - pDeviceSettings->d3d11.sd.SampleDesc.Quality = pDeviceSettingsCombo->multiSampleQualityList.GetAt(bestMSAAIndex) - 1; - - pDeviceSettings->d3d11.sd.BufferDesc.Format = pDeviceSettingsCombo->BackBufferFormat; - - return S_OK; } - // didn't find a D3D11 adapter. - if (bAppSupportsD3D9) { - // Find the best combination of: - // Adapter Ordinal - // Device Type - // Adapter Format - // Back Buffer Format - // Windowed - // given what's available on the system and the match options combined with the device settings input. - // This combination of settings is encapsulated by the CD3D9EnumDeviceSettingsCombo class. - float fBestRanking = -1.0f; - CD3D9EnumDeviceSettingsCombo* pBestDeviceSettingsCombo = NULL; - D3DDISPLAYMODE adapterDesktopDisplayMode; - - IDirect3D9* pD3D = DXUTGetD3D9Object(); - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration( forceEnum ); - CGrowableArray * pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); iAdapter++ ) - { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); - - // Get the desktop display mode of adapter - pD3D->GetAdapterDisplayMode( pAdapterInfo->AdapterOrdinal, &adapterDesktopDisplayMode ); - - // Enum all the device types supported by this adapter to find the best device settings - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) - { - CD3D9EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); + if (pDeviceSettings->d3d11.DeviceFeatureLevel == 0) + pDeviceSettings->d3d11.DeviceFeatureLevel = pDeviceSettingsCombo->pDeviceInfo->SelectedLevel; - // Enum all the device settings combinations. A device settings combination is - // a unique set of an adapter format, back buffer format, and IsWindowed. - for( int iDeviceCombo = 0; iDeviceCombo < pDeviceInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( - iDeviceCombo ); - - // If windowed mode the adapter format has to be the same as the desktop - // display mode format so skip any that don't match - if( pDeviceSettingsCombo->Windowed && - ( pDeviceSettingsCombo->AdapterFormat != adapterDesktopDisplayMode.Format ) ) - continue; + if ( pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + D3D_FEATURE_LEVEL maxWarpFL = pEnum->GetWARPFeaturevel(); - // Skip any combo that doesn't meet the preserve match options - int bestMode; - int bestMSAA; + if ( pDeviceSettings->d3d11.DeviceFeatureLevel > maxWarpFL ) + pDeviceSettings->d3d11.DeviceFeatureLevel = maxWarpFL; + } - // Get a ranking number that describes how closely this device combo matches the optimal combo - float fCurRanking = DXUTRankD3D9DeviceCombo( pDeviceSettingsCombo, - &(pDeviceSettings->d3d9), &adapterDesktopDisplayMode, bestMode, bestMSAA ); + if ( pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) + { + D3D_FEATURE_LEVEL maxRefFL = pEnum->GetREFFeaturevel(); - // If this combo better matches the input device settings then save it - if( fCurRanking > fBestRanking ) - { - pBestDeviceSettingsCombo = pDeviceSettingsCombo; - fBestRanking = fCurRanking; - bestModeIndex = bestMode; - bestMSAAIndex = bestMSAA; - } - } - } - } + if ( pDeviceSettings->d3d11.DeviceFeatureLevel > maxRefFL ) + pDeviceSettings->d3d11.DeviceFeatureLevel = maxRefFL; + } - // If no best device combination was found then fail - if( pBestDeviceSettingsCombo == NULL ) - return DXUTERR_NOCOMPATIBLEDEVICES; - - // Using the best device settings combo found, build valid device settings taking heed of - // the match options and the input device settings - pDeviceSettings->d3d9.AdapterFormat = pBestDeviceSettingsCombo->AdapterFormat;//D3DFMT_X8R8G8B8; - pDeviceSettings->d3d9.AdapterOrdinal = pBestDeviceSettingsCombo->AdapterOrdinal ;//0; - pDeviceSettings->d3d9.DeviceType = pBestDeviceSettingsCombo->DeviceType; - pDeviceSettings->d3d9.pp.BackBufferFormat = pBestDeviceSettingsCombo->BackBufferFormat;//D3DFMT_X8R8G8B8; - if( GetSystemMetrics(0x1000) != 0 ) {// SM_REMOTESESSION - pDeviceSettings->d3d9.pp.Windowed = 1; - } - if (!pBestDeviceSettingsCombo->Windowed) { - D3DDISPLAYMODE displayMode = pBestDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( bestModeIndex ); - pDeviceSettings->d3d9.pp.BackBufferHeight = displayMode.Height; - pDeviceSettings->d3d9.pp.BackBufferWidth = displayMode.Width; - pDeviceSettings->d3d9.pp.FullScreen_RefreshRateInHz = displayMode.RefreshRate; - } - pDeviceSettings->d3d9.pp.hDeviceWindow = pBestDeviceSettingsCombo->Windowed ? DXUTGetHWNDDeviceWindowed() : DXUTGetHWNDDeviceFullScreen(); - if (pDeviceSettings->d3d9.pp.MultiSampleQuality > pBestDeviceSettingsCombo->multiSampleQualityList.GetAt(bestMSAAIndex) - 1) - pDeviceSettings->d3d9.pp.MultiSampleQuality = pBestDeviceSettingsCombo->multiSampleQualityList.GetAt( bestMSAAIndex )-1; + pDeviceSettings->d3d11.sd.SampleDesc.Count = pDeviceSettingsCombo->multiSampleCountList[ bestMSAAIndex ]; + if (pDeviceSettings->d3d11.sd.SampleDesc.Quality > pDeviceSettingsCombo->multiSampleQualityList[ bestMSAAIndex ] - 1) + pDeviceSettings->d3d11.sd.SampleDesc.Quality = pDeviceSettingsCombo->multiSampleQualityList[ bestMSAAIndex ] - 1; - pDeviceSettings->d3d9.pp.MultiSampleType = pBestDeviceSettingsCombo->multiSampleTypeList.GetAt( bestMSAAIndex );; - pDeviceSettings->d3d9.pp.Windowed = pBestDeviceSettingsCombo->Windowed; - return S_OK; - } - return E_FAIL; + pDeviceSettings->d3d11.sd.BufferDesc.Format = pDeviceSettingsCombo->BackBufferFormat; + + return S_OK; } diff --git a/FriedLiver/Source/DXUT/Core/DXUT.h b/FriedLiver/Source/DXUT/Core/DXUT.h index 7e915c38..c70fd47a 100644 --- a/FriedLiver/Source/DXUT/Core/DXUT.h +++ b/FriedLiver/Source/DXUT/Core/DXUT.h @@ -2,69 +2,58 @@ // File: DXUT.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_H -#define DXUT_H #ifndef UNICODE #error "DXUT requires a Unicode build." #endif -#include "dxsdkver.h" -#if ( _DXSDK_PRODUCT_MAJOR < 9 || _DXSDK_BUILD_MAJOR < 1949 ) -#error The installed DXSDK is out of date. -#endif - #ifndef STRICT #define STRICT #endif -// If app hasn't choosen, set to work with Windows XP and beyond +// If app hasn't choosen, set to work with Windows Vista and beyond #ifndef WINVER -#define WINVER 0x0501 +#define WINVER 0x0600 #endif #ifndef _WIN32_WINDOWS -#define _WIN32_WINDOWS 0x0501 +#define _WIN32_WINDOWS 0x0600 #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #endif +#if defined(USE_DIRECT3D11_4) && !defined(USE_DIRECT3D11_3) +#define USE_DIRECT3D11_3 +#endif + +#if (_WIN32_WINNT >= 0x0A00) && !defined(USE_DIRECT3D11_3) +#define USE_DIRECT3D11_3 +#endif + // #define DXUT_AUTOLIB to automatically include the libs needed for DXUT #ifdef DXUT_AUTOLIB -#pragma comment( lib, "dxerr.lib" ) +#pragma comment( lib, "comctl32.lib" ) #pragma comment( lib, "dxguid.lib" ) -#pragma comment( lib, "d3d9.lib" ) -#if defined(DEBUG) || defined(_DEBUG) -#pragma comment( lib, "d3dx9d.lib" ) -#pragma comment( lib, "d3dx11d.lib" ) -#else -#pragma comment( lib, "d3dx9.lib" ) -#pragma comment( lib, "d3dx11.lib" ) -#endif #pragma comment( lib, "d3dcompiler.lib" ) -#pragma comment( lib, "winmm.lib" ) -#pragma comment( lib, "comctl32.lib" ) +#pragma comment( lib, "ole32.lib" ) +#pragma comment( lib, "uuid.lib" ) #endif -#pragma warning( disable : 4100 ) // disable unreference formal parameter warnings for /W4 builds +#pragma warning( disable : 4481 ) -// Enable extra D3D debugging in debug builds if using the debug DirectX runtime. -// This makes D3D objects work well in the debugger watch window, but slows down -// performance slightly. -#if defined(DEBUG) || defined(_DEBUG) -#ifndef D3D_DEBUG_INFO -#define D3D_DEBUG_INFO -#endif +// Standard Windows includes +#if !defined(NOMINMAX) +#define NOMINMAX #endif -// Standard Windows includes #include #include #include -#include -#include #include // for InitCommonControls() #include // for ExtractIcon() #include // for placement new @@ -78,23 +67,38 @@ #include #endif -// Direct3D9 includes -#include -#include - // Direct3D11 includes #include #include -#include +#include +#include #include -#include + +#ifdef USE_DIRECT3D11_3 +#include +#endif + +#ifdef USE_DIRECT3D11_4 +#include +#endif + +// DirectXMath includes +#include +#include + +// WIC includes +#include // XInput includes #include // HRESULT translation for Direct3D and other APIs -#include +#include "dxerr.h" +// STL includes +#include +#include +#include #if defined(DEBUG) || defined(_DEBUG) #ifndef V @@ -113,29 +117,25 @@ #endif #ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p)=NULL; } } +#define SAFE_DELETE(p) { if (p) { delete (p); (p) = nullptr; } } #endif #ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p)=NULL; } } +#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = nullptr; } } #endif #ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p)=NULL; } } +#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = nullptr; } } #endif +#ifndef D3DCOLOR_ARGB +#define D3DCOLOR_ARGB(a,r,g,b) \ + ((DWORD)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff))) +#endif +#define DXUT_VERSION 1122 //-------------------------------------------------------------------------------------- // Structs //-------------------------------------------------------------------------------------- -struct DXUTD3D9DeviceSettings -{ - UINT AdapterOrdinal; - D3DDEVTYPE DeviceType; - D3DFORMAT AdapterFormat; - DWORD BehaviorFlags; - D3DPRESENT_PARAMETERS pp; -}; - struct DXUTD3D11DeviceSettings { UINT AdapterOrdinal; @@ -150,18 +150,10 @@ struct DXUTD3D11DeviceSettings D3D_FEATURE_LEVEL DeviceFeatureLevel; }; -enum DXUTDeviceVersion -{ - DXUT_D3D9_DEVICE, - DXUT_D3D11_DEVICE -}; - struct DXUTDeviceSettings { - DXUTDeviceVersion ver; D3D_FEATURE_LEVEL MinimumFeatureLevel; - DXUTD3D9DeviceSettings d3d9; // only valid if ver == DXUT_D3D9_DEVICE - DXUTD3D11DeviceSettings d3d11; // only valid if ver == DXUT_D3D11_DEVICE + DXUTD3D11DeviceSettings d3d11; }; @@ -177,86 +169,75 @@ struct DXUTDeviceSettings #define DXUTERR_CREATINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0907) #define DXUTERR_RESETTINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0908) #define DXUTERR_DEVICEREMOVED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090A) -#define DXUTERR_NODIRECT3D11 MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090) + //-------------------------------------------------------------------------------------- // Callback registration //-------------------------------------------------------------------------------------- // General callbacks -typedef void (CALLBACK *LPDXUTCALLBACKFRAMEMOVE)( double fTime, float fElapsedTime, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKKEYBOARD)( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKMOUSE)( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ); -typedef LRESULT (CALLBACK *LPDXUTCALLBACKMSGPROC)( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKTIMER)( UINT idEvent, void* pUserContext ); -typedef bool (CALLBACK *LPDXUTCALLBACKMODIFYDEVICESETTINGS)( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); -typedef bool (CALLBACK *LPDXUTCALLBACKDEVICEREMOVED)( void* pUserContext ); - -// Direct3D 9 callbacks -typedef bool (CALLBACK *LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE)( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D9DEVICECREATED)( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D9DEVICERESET)( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D9FRAMERENDER)( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D9DEVICELOST)( void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D9DEVICEDESTROYED)( void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKFRAMEMOVE)( _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKKEYBOARD)( _In_ UINT nChar, _In_ bool bKeyDown, _In_ bool bAltDown, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKMOUSE)( _In_ bool bLeftButtonDown, _In_ bool bRightButtonDown, _In_ bool bMiddleButtonDown, + _In_ bool bSideButton1Down, _In_ bool bSideButton2Down, _In_ int nMouseWheelDelta, + _In_ int xPos, _In_ int yPos, _In_opt_ void* pUserContext ); +typedef LRESULT (CALLBACK *LPDXUTCALLBACKMSGPROC)( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam, + _Out_ bool* pbNoFurtherProcessing, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKTIMER)( _In_ UINT idEvent, _In_opt_ void* pUserContext ); +typedef bool (CALLBACK *LPDXUTCALLBACKMODIFYDEVICESETTINGS)( _In_ DXUTDeviceSettings* pDeviceSettings, _In_opt_ void* pUserContext ); +typedef bool (CALLBACK *LPDXUTCALLBACKDEVICEREMOVED)( _In_opt_ void* pUserContext ); class CD3D11EnumAdapterInfo; class CD3D11EnumDeviceInfo; + // Direct3D 11 callbacks -typedef bool (CALLBACK *LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE)( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11DEVICECREATED)( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRESIZED)( ID3D11Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D11FRAMERENDER)( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRELEASING)( void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D11DEVICEDESTROYED)( void* pUserContext ); +typedef bool (CALLBACK *LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE)( _In_ const CD3D11EnumAdapterInfo *AdapterInfo, _In_ UINT Output, _In_ const CD3D11EnumDeviceInfo *DeviceInfo, + _In_ DXGI_FORMAT BackBufferFormat, _In_ bool bWindowed, _In_opt_ void* pUserContext ); +typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11DEVICECREATED)( _In_ ID3D11Device* pd3dDevice, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext ); +typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRESIZED)( _In_ ID3D11Device* pd3dDevice, _In_ IDXGISwapChain *pSwapChain, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKD3D11FRAMERENDER)( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext, _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRELEASING)( _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKD3D11DEVICEDESTROYED)( _In_opt_ void* pUserContext ); // General callbacks -void WINAPI DXUTSetCallbackFrameMove( LPDXUTCALLBACKFRAMEMOVE pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackKeyboard( LPDXUTCALLBACKKEYBOARD pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackMouse( LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove = false, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackMsgProc( LPDXUTCALLBACKMSGPROC pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackDeviceChanging( LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackDeviceRemoved( LPDXUTCALLBACKDEVICEREMOVED pCallback, void* pUserContext = NULL ); - -// Direct3D 9 callbacks -void WINAPI DXUTSetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceCreated( LPDXUTCALLBACKD3D9DEVICECREATED pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceReset( LPDXUTCALLBACKD3D9DEVICERESET pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9FrameRender( LPDXUTCALLBACKD3D9FRAMERENDER pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceLost( LPDXUTCALLBACKD3D9DEVICELOST pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceDestroyed( LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallback, void* pUserContext = NULL ); +void WINAPI DXUTSetCallbackFrameMove( _In_ LPDXUTCALLBACKFRAMEMOVE pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackKeyboard( _In_ LPDXUTCALLBACKKEYBOARD pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackMouse( _In_ LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove = false, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackMsgProc( _In_ LPDXUTCALLBACKMSGPROC pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackDeviceChanging( _In_ LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackDeviceRemoved( _In_ LPDXUTCALLBACKDEVICEREMOVED pCallback, _In_opt_ void* pUserContext = nullptr ); // Direct3D 11 callbacks -void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11DeviceCreated( LPDXUTCALLBACKD3D11DEVICECREATED pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11SwapChainResized( LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11FrameRender( LPDXUTCALLBACKD3D11FRAMERENDER pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, void* pUserContext = NULL ); +void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11DeviceCreated( _In_ LPDXUTCALLBACKD3D11DEVICECREATED pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11SwapChainResized( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11FrameRender( _In_ LPDXUTCALLBACKD3D11FRAMERENDER pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( _In_ LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, _In_opt_ void* pUserContext = nullptr ); //-------------------------------------------------------------------------------------- // Initialization //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTInit( bool bParseCommandLine = true, - bool bShowMsgBoxOnError = true, - __in_opt WCHAR* strExtraCommandLineParams = NULL, - bool bThreadSafeDXUT = false ); +HRESULT WINAPI DXUTInit( _In_ bool bParseCommandLine = true, + _In_ bool bShowMsgBoxOnError = true, + _In_opt_ WCHAR* strExtraCommandLineParams = nullptr, + _In_ bool bThreadSafeDXUT = false ); // Choose either DXUTCreateWindow or DXUTSetWindow. If using DXUTSetWindow, consider using DXUTStaticWndProc -HRESULT WINAPI DXUTCreateWindow( unsigned int defaultWidth, unsigned int defaultHeight, const WCHAR* strWindowTitle = L"Direct3D Window", bool allowWindowResize = true, HINSTANCE hInstance = NULL, HICON hIcon = NULL, HMENU hMenu = NULL, int x = CW_USEDEFAULT, int y = CW_USEDEFAULT); -HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hWndDeviceWindowed, bool bHandleMessages = true ); -LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); +HRESULT WINAPI DXUTCreateWindow( _In_z_ const WCHAR* strWindowTitle = L"Direct3D Window", + _In_opt_ HINSTANCE hInstance = nullptr, _In_opt_ HICON hIcon = nullptr, _In_opt_ HMENU hMenu = nullptr, + _In_ int x = CW_USEDEFAULT, _In_ int y = CW_USEDEFAULT ); +HRESULT WINAPI DXUTSetWindow( _In_ HWND hWndFocus, _In_ HWND hWndDeviceFullScreen, _In_ HWND hWndDeviceWindowed, _In_ bool bHandleMessages = true ); +LRESULT CALLBACK DXUTStaticWndProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); -// Choose either DXUTCreateDevice or DXUTSetD3D*Device or DXUTCreateD3DDeviceFromSettings +// Choose either DXUTCreateDevice or DXUTCreateD3DDeviceFromSettings -HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed= true, int nSuggestedWidth =0, int nSuggestedHeight =0 ); -HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bPreserveInput = false, bool bClipWindowToSingleAdapter = true ); -HRESULT WINAPI DXUTSetD3D9Device( IDirect3DDevice9* pd3dDevice ); -HRESULT WINAPI DXUTSetD3D11Device( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain ); +HRESULT WINAPI DXUTCreateDevice(_In_ D3D_FEATURE_LEVEL reqFL, _In_ bool bWindowed= true, _In_ int nSuggestedWidth =0,_In_ int nSuggestedHeight =0 ); +HRESULT WINAPI DXUTCreateDeviceFromSettings( _In_ DXUTDeviceSettings* pDeviceSettings, _In_ bool bClipWindowToSingleAdapter = true ); // Choose either DXUTMainLoop or implement your own main loop -HRESULT WINAPI DXUTMainLoop( HACCEL hAccel = NULL ); +HRESULT WINAPI DXUTMainLoop( _In_opt_ HACCEL hAccel = nullptr ); // If not using DXUTMainLoop consider using DXUTRender3DEnvironment void WINAPI DXUTRender3DEnvironment(); @@ -268,50 +249,52 @@ void WINAPI DXUTRender3DEnvironment(); HRESULT WINAPI DXUTToggleFullScreen(); HRESULT WINAPI DXUTToggleREF(); HRESULT WINAPI DXUTToggleWARP(); -void WINAPI DXUTPause( bool bPauseTime, bool bPauseRendering ); -void WINAPI DXUTSetConstantFrameTime( bool bConstantFrameTime, float fTimePerFrame = 0.0333f ); -void WINAPI DXUTSetCursorSettings( bool bShowCursorWhenFullScreen = false, bool bClipCursorWhenFullScreen = false ); -void WINAPI DXUTSetD3DVersionSupport( bool bAppCanUseD3D9 = true, bool bAppCanUseD3D11 = true ); -void WINAPI DXUTSetHotkeyHandling( bool bAltEnterToToggleFullscreen = true, bool bEscapeToQuit = true, bool bPauseToToggleTimePause = true ); -void WINAPI DXUTSetMultimonSettings( bool bAutoChangeAdapter = true ); -void WINAPI DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen = false, bool bAllowWhenWindowed = true ); // Controls the Windows key, and accessibility shortcut keys -void WINAPI DXUTSetWindowSettings( bool bCallDefWindowProc = true ); -HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutInSecs = 1.0f, UINT* pnIDEvent = NULL, void* pCallbackUserContext = NULL ); -HRESULT WINAPI DXUTKillTimer( UINT nIDEvent ); +void WINAPI DXUTPause( _In_ bool bPauseTime, _In_ bool bPauseRendering ); +void WINAPI DXUTSetConstantFrameTime( _In_ bool bConstantFrameTime, _In_ float fTimePerFrame = 0.0333f ); +void WINAPI DXUTSetCursorSettings( _In_ bool bShowCursorWhenFullScreen = false, _In_ bool bClipCursorWhenFullScreen = false ); +void WINAPI DXUTSetHotkeyHandling( _In_ bool bAltEnterToToggleFullscreen = true, _In_ bool bEscapeToQuit = true, _In_ bool bPauseToToggleTimePause = true ); +void WINAPI DXUTSetMultimonSettings( _In_ bool bAutoChangeAdapter = true ); +void WINAPI DXUTSetShortcutKeySettings( _In_ bool bAllowWhenFullscreen = false, _In_ bool bAllowWhenWindowed = true ); // Controls the Windows key, and accessibility shortcut keys +void WINAPI DXUTSetWindowSettings( _In_ bool bCallDefWindowProc = true ); +HRESULT WINAPI DXUTSetTimer( _In_ LPDXUTCALLBACKTIMER pCallbackTimer, _In_ float fTimeoutInSecs = 1.0f, _Out_opt_ UINT* pnIDEvent = nullptr, _In_opt_ void* pCallbackUserContext = nullptr ); +HRESULT WINAPI DXUTKillTimer( _In_ UINT nIDEvent ); void WINAPI DXUTResetFrameworkState(); -void WINAPI DXUTShutdown( int nExitCode = 0 ); -void WINAPI DXUTSetIsInGammaCorrectMode( bool bGammaCorrect ); -BOOL WINAPI DXUTGetMSAASwapChainCreated(); +void WINAPI DXUTShutdown( _In_ int nExitCode = 0 ); +void WINAPI DXUTSetIsInGammaCorrectMode( _In_ bool bGammaCorrect ); +bool WINAPI DXUTGetMSAASwapChainCreated(); + //-------------------------------------------------------------------------------------- // State Retrieval //-------------------------------------------------------------------------------------- -// Direct3D 9 -IDirect3D9* WINAPI DXUTGetD3D9Object(); // Does not addref unlike typical Get* APIs -IDirect3DDevice9* WINAPI DXUTGetD3D9Device(); // Does not addref unlike typical Get* APIs -D3DPRESENT_PARAMETERS WINAPI DXUTGetD3D9PresentParameters(); -const D3DSURFACE_DESC* WINAPI DXUTGetD3D9BackBufferSurfaceDesc(); -const D3DCAPS9* WINAPI DXUTGetD3D9DeviceCaps(); -HRESULT WINAPI DXUTGetD3D9DeviceCaps( DXUTDeviceSettings* pDeviceSettings, D3DCAPS9* pCaps ); -bool WINAPI DXUTDoesAppSupportD3D9(); -bool WINAPI DXUTIsAppRenderingWithD3D9(); +// Direct3D 11.x (These do not addref unlike typical Get* APIs) +IDXGIFactory1* WINAPI DXUTGetDXGIFactory(); +IDXGISwapChain* WINAPI DXUTGetDXGISwapChain(); +const DXGI_SURFACE_DESC* WINAPI DXUTGetDXGIBackBufferSurfaceDesc(); +HRESULT WINAPI DXUTSetupD3D11Views( _In_ ID3D11DeviceContext* pd3dDeviceContext ); // Supports immediate or deferred context +D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel(); // Returns the D3D11 devices current feature level +ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView(); +ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView(); +ID3D11Device* WINAPI DXUTGetD3D11Device(); +ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext(); -// Direct3D 11 -IDXGIFactory1* WINAPI DXUTGetDXGIFactory(); // Does not addref unlike typical Get* APIs -IDXGISwapChain* WINAPI DXUTGetDXGISwapChain(); // Does not addref unlike typical Get* APIs -const DXGI_SURFACE_DESC* WINAPI DXUTGetDXGIBackBufferSurfaceDesc(); -bool WINAPI DXUTIsD3D11Available(); // If D3D11 APIs are availible -ID3D11Device* WINAPI DXUTGetD3D11Device(); // Does not addref unlike typical Get* APIs -ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext(); // Does not addref unlike typical Get* APIs -HRESULT WINAPI DXUTSetupD3D11Views( ID3D11DeviceContext* pd3dDeviceContext ); // Supports immediate or deferred context -D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel(); // Returns the D3D11 devices current feature level -ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView(); // Does not addref unlike typical Get* APIs -ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView(); // Does not addref unlike typical Get* APIs -bool WINAPI DXUTDoesAppSupportD3D11(); -bool WINAPI DXUTIsAppRenderingWithD3D11(); +ID3D11Device1* WINAPI DXUTGetD3D11Device1(); +ID3D11DeviceContext1* WINAPI DXUTGetD3D11DeviceContext1(); + +ID3D11Device2* WINAPI DXUTGetD3D11Device2(); +ID3D11DeviceContext2* WINAPI DXUTGetD3D11DeviceContext2(); +#ifdef USE_DIRECT3D11_3 +ID3D11Device3* WINAPI DXUTGetD3D11Device3(); +ID3D11DeviceContext3* WINAPI DXUTGetD3D11DeviceContext3(); +#endif + +#ifdef USE_DIRECT3D11_4 +ID3D11Device4* WINAPI DXUTGetD3D11Device4(); +ID3D11DeviceContext4* WINAPI DXUTGetD3D11DeviceContext4(); +#endif // General DXUTDeviceSettings WINAPI DXUTGetDeviceSettings(); @@ -331,7 +314,7 @@ bool WINAPI DXUTIsWindowed(); bool WINAPI DXUTIsInGammaCorrectMode(); float WINAPI DXUTGetFPS(); LPCWSTR WINAPI DXUTGetWindowTitle(); -LPCWSTR WINAPI DXUTGetFrameStats( bool bIncludeFPS = false ); +LPCWSTR WINAPI DXUTGetFrameStats( _In_ bool bIncludeFPS = false ); LPCWSTR WINAPI DXUTGetDeviceStats(); bool WINAPI DXUTIsVsyncEnabled(); @@ -341,9 +324,9 @@ bool WINAPI DXUTIsActive(); int WINAPI DXUTGetExitCode(); bool WINAPI DXUTGetShowMsgBoxOnError(); bool WINAPI DXUTGetAutomation(); // Returns true if -automation parameter is used to launch the app -bool WINAPI DXUTIsKeyDown( BYTE vKey ); // Pass a virtual-key code, ex. VK_F1, 'A', VK_RETURN, VK_LSHIFT, etc -bool WINAPI DXUTWasKeyPressed( BYTE vKey ); // Like DXUTIsKeyDown() but return true only if the key was just pressed -bool WINAPI DXUTIsMouseButtonDown( BYTE vButton ); // Pass a virtual-key code: VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, VK_XBUTTON2 +bool WINAPI DXUTIsKeyDown( _In_ BYTE vKey ); // Pass a virtual-key code, ex. VK_F1, 'A', VK_RETURN, VK_LSHIFT, etc +bool WINAPI DXUTWasKeyPressed( _In_ BYTE vKey ); // Like DXUTIsKeyDown() but return true only if the key was just pressed +bool WINAPI DXUTIsMouseButtonDown( _In_ BYTE vButton ); // Pass a virtual-key code: VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, VK_XBUTTON2 HRESULT WINAPI DXUTCreateState(); // Optional method to create DXUT's memory. If its not called by the application it will be automatically called when needed void WINAPI DXUTDestroyState(); // Optional method to destroy DXUT's memory. If its not called by the application it will be automatically called after the application exits WinMain @@ -351,14 +334,4 @@ void WINAPI DXUTDestroyState(); // Optional method to destroy DXUT's memory // DXUT core layer includes //-------------------------------------------------------------------------------------- #include "DXUTmisc.h" -#include "DXUTDevice9.h" #include "DXUTDevice11.h" - - - - -#endif - - - - diff --git a/FriedLiver/Source/DXUT/Core/DXUTDevice11.cpp b/FriedLiver/Source/DXUT/Core/DXUTDevice11.cpp index 1b53afbc..63cbd456 100644 --- a/FriedLiver/Source/DXUT/Core/DXUTDevice11.cpp +++ b/FriedLiver/Source/DXUT/Core/DXUTDevice11.cpp @@ -4,10 +4,11 @@ // Enumerates D3D adapters, devices, modes, etc. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" -#undef min // use __min instead -#undef max // use __max instead //-------------------------------------------------------------------------------------- // Forward declarations @@ -16,17 +17,14 @@ extern void DXUTGetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACC static int __cdecl SortModesCallback( const void* arg1, const void* arg2 ); -CD3D11Enumeration* g_pDXUTD3D11Enumeration = NULL; - - - +CD3D11Enumeration* g_pDXUTD3D11Enumeration = nullptr; HRESULT WINAPI DXUTCreateD3D11Enumeration() { - if( g_pDXUTD3D11Enumeration == NULL ) + if( !g_pDXUTD3D11Enumeration ) { - g_pDXUTD3D11Enumeration = new CD3D11Enumeration(); - if( NULL == g_pDXUTD3D11Enumeration ) + g_pDXUTD3D11Enumeration = new (std::nothrow) CD3D11Enumeration(); + if( !g_pDXUTD3D11Enumeration ) return E_OUTOFMEMORY; } return S_OK; @@ -40,18 +38,13 @@ void WINAPI DXUTDestroyD3D11Enumeration() class DXUTMemoryHelperD3D11Enum { public: -DXUTMemoryHelperD3D11Enum() -{ - DXUTCreateD3D11Enumeration(); -} -~DXUTMemoryHelperD3D11Enum() -{ - DXUTDestroyD3D11Enumeration(); -} +DXUTMemoryHelperD3D11Enum() noexcept { DXUTCreateD3D11Enumeration(); } +~DXUTMemoryHelperD3D11Enum() { DXUTDestroyD3D11Enumeration(); } }; //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration( bool bForceEnumerate, bool bEnumerateAllAdapterFormats, D3D_FEATURE_LEVEL forceFL ) { // Using an static class with accessor function to allow control of the construction order @@ -72,21 +65,15 @@ CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration( bool bForceEnumerate, bool bE //-------------------------------------------------------------------------------------- -CD3D11Enumeration::CD3D11Enumeration() +CD3D11Enumeration::CD3D11Enumeration() noexcept : + m_bHasEnumerated(false), + m_IsD3D11DeviceAcceptableFunc(nullptr), + m_pIsD3D11DeviceAcceptableFuncUserContext(nullptr), + m_bEnumerateAllAdapterFormats(false), + m_forceFL(D3D_FEATURE_LEVEL(0)), + m_warpFL(D3D_FEATURE_LEVEL_10_1), + m_refFL(D3D_FEATURE_LEVEL_11_0) { - m_bHasEnumerated = false; - m_IsD3D11DeviceAcceptableFunc = NULL; - m_pIsD3D11DeviceAcceptableFuncUserContext = NULL; - - m_nMinWidth = 640; - m_nMinHeight = 480; - m_nMaxWidth = UINT_MAX; - m_nMaxHeight = UINT_MAX; - m_bEnumerateAllAdapterFormats = false; - - m_nRefreshMin = 0; - m_nRefreshMax = UINT_MAX; - ResetPossibleDepthStencilFormats(); } @@ -110,13 +97,14 @@ CD3D11Enumeration::~CD3D11Enumeration() // if supported otherwise it will default to SWVP, however the app can change this // through the ConfirmDevice callback. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, void* pIsD3D11DeviceAcceptableFuncUserContext ) { CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D11 Enumeration" ); HRESULT hr; - IDXGIFactory1* pFactory = DXUTGetDXGIFactory(); - if( pFactory == NULL ) + auto pFactory = DXUTGetDXGIFactory(); + if( !pFactory ) return E_FAIL; m_bHasEnumerated = true; @@ -127,18 +115,33 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 for( int index = 0; ; ++index ) { - IDXGIAdapter* pAdapter = NULL; + IDXGIAdapter* pAdapter = nullptr; hr = pFactory->EnumAdapters( index, &pAdapter ); if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit break; - CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo; + IDXGIAdapter2* pAdapter2 = nullptr; + if ( SUCCEEDED( pAdapter->QueryInterface( __uuidof(IDXGIAdapter2), ( LPVOID* )&pAdapter2 ) ) ) + { + // Succeeds on DirectX 11.1 Runtime systems + DXGI_ADAPTER_DESC2 desc; + hr = pAdapter2->GetDesc2( &desc ); + pAdapter2->Release(); + + if ( SUCCEEDED(hr) && ( desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE ) ) + { + // Skip "always there" Microsoft Basics Display Driver + pAdapter->Release(); + continue; + } + } + + auto pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo; if( !pAdapterInfo ) { SAFE_RELEASE( pAdapter ); return E_OUTOFMEMORY; } - ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) ); pAdapterInfo->AdapterOrdinal = index; pAdapter->GetDesc( &pAdapterInfo->AdapterDesc ); pAdapterInfo->m_pAdapter = pAdapter; @@ -152,38 +155,30 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 } hr = EnumerateOutputs( pAdapterInfo ); - if( FAILED( hr ) || pAdapterInfo->outputInfoList.GetSize() <= 0 ) + if( FAILED( hr ) || pAdapterInfo->outputInfoList.empty() ) { delete pAdapterInfo; continue; } // Get info for each devicecombo on this device - if( FAILED( hr = EnumerateDeviceCombos( pFactory, pAdapterInfo ) ) ) + if( FAILED( hr = EnumerateDeviceCombos( pAdapterInfo ) ) ) { delete pAdapterInfo; continue; } - hr = m_AdapterInfoList.Add( pAdapterInfo ); - if( FAILED( hr ) ) - { - delete pAdapterInfo; - return hr; - } + m_AdapterInfoList.push_back( pAdapterInfo ); } - // If we did not get an adapter then we should still enumerate WARP and Ref. - if (m_AdapterInfoList.GetSize() == 0) { - - - CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo; + if (m_AdapterInfoList.size() == 0) + { + auto pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo; if( !pAdapterInfo ) { return E_OUTOFMEMORY; } - ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) ); pAdapterInfo->bAdapterUnavailable = true; hr = EnumerateDevices( pAdapterInfo ); @@ -194,7 +189,7 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 delete pAdapterInfo; } - if (!FAILED(hr)) hr = m_AdapterInfoList.Add( pAdapterInfo ); + if (SUCCEEDED(hr)) m_AdapterInfoList.push_back( pAdapterInfo ); } // @@ -203,14 +198,13 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 // them. // bool bUniqueDesc = true; - CD3D11EnumAdapterInfo* pAdapterInfo; - for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ ) + for( size_t i = 0; i < m_AdapterInfoList.size(); i++ ) { - CD3D11EnumAdapterInfo* pAdapterInfo1 = m_AdapterInfoList.GetAt( i ); + auto pAdapterInfo1 = m_AdapterInfoList[ i ]; - for( int j = i + 1; j < m_AdapterInfoList.GetSize(); j++ ) + for( size_t j = i + 1; j < m_AdapterInfoList.size(); j++ ) { - CD3D11EnumAdapterInfo* pAdapterInfo2 = m_AdapterInfoList.GetAt( j ); + auto pAdapterInfo2 = m_AdapterInfoList[ j ]; if( wcsncmp( pAdapterInfo1->AdapterDesc.Description, pAdapterInfo2->AdapterDesc.Description, DXGI_MAX_DEVICE_IDENTIFIER_STRING ) == 0 ) { @@ -223,17 +217,77 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 break; } - for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ ) + for( auto it = m_AdapterInfoList.begin(); it != m_AdapterInfoList.end(); ++it ) { - pAdapterInfo = m_AdapterInfoList.GetAt( i ); - - wcscpy_s( pAdapterInfo->szUniqueDescription, 100, pAdapterInfo->AdapterDesc.Description ); + wcscpy_s((*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, (*it)->AdapterDesc.Description); if( !bUniqueDesc ) { - WCHAR sz[100]; - swprintf_s( sz, 100, L" (#%d)", pAdapterInfo->AdapterOrdinal ); - wcscat_s( pAdapterInfo->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz ); + WCHAR sz[32]; + swprintf_s( sz, 32, L" (#%u)", (*it)->AdapterOrdinal ); + wcscat_s( (*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz ); + } + } + + // Check WARP max feature level + { + static const D3D_FEATURE_LEVEL fLvlWarp[] = + { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, +#endif + D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 + }; + + ID3D11Device* pDevice = nullptr; + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, fLvlWarp, _countof(fLvlWarp), + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr ); + if ( hr == E_INVALIDARG ) + { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + // DirectX 11.1 runtime will not recognize FL 12.x, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[2], _countof(fLvlWarp) - 2, + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr); + if (hr == E_INVALIDARG) + { + // DirectX 11.0 runtime will not recognize FL 11.1+, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[3], _countof(fLvlWarp) - 3, + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr); + } +#else + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[1], _countof(fLvlWarp) - 1, + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr ); +#endif + } + + if ( SUCCEEDED(hr) ) + { + pDevice->Release(); + } + else + m_warpFL = D3D_FEATURE_LEVEL_10_1; + } + + // Check REF max feature level + { + static const D3D_FEATURE_LEVEL fLvlRef[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 }; + + ID3D11Device* pDevice = nullptr; + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, fLvlRef, _countof(fLvlRef), + D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr ); + if ( hr == E_INVALIDARG ) + { + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, &fLvlRef[1], _countof(fLvlRef) - 1, + D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr ); } + + if ( SUCCEEDED(hr) ) + { + pDevice->Release(); + } + else + m_refFL = D3D_FEATURE_LEVEL_11_0; } return S_OK; @@ -241,14 +295,14 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateOutputs( CD3D11EnumAdapterInfo* pAdapterInfo ) +HRESULT CD3D11Enumeration::EnumerateOutputs( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ) { HRESULT hr; IDXGIOutput* pOutput; for( int iOutput = 0; ; ++iOutput ) { - pOutput = NULL; + pOutput = nullptr; hr = pAdapterInfo->m_pAdapter->EnumOutputs( iOutput, &pOutput ); if( DXGI_ERROR_NOT_FOUND == hr ) { @@ -260,38 +314,32 @@ HRESULT CD3D11Enumeration::EnumerateOutputs( CD3D11EnumAdapterInfo* pAdapterInfo } else //Success! { - CD3D11EnumOutputInfo* pOutputInfo = new CD3D11EnumOutputInfo; + auto pOutputInfo = new (std::nothrow) CD3D11EnumOutputInfo; if( !pOutputInfo ) { SAFE_RELEASE( pOutput ); return E_OUTOFMEMORY; } - ZeroMemory( pOutputInfo, sizeof( CD3D11EnumOutputInfo ) ); - pOutput->GetDesc( &pOutputInfo->Desc ); pOutputInfo->Output = iOutput; pOutputInfo->m_pOutput = pOutput; + pOutput->GetDesc( &pOutputInfo->Desc ); EnumerateDisplayModes( pOutputInfo ); - if( pOutputInfo->displayModeList.GetSize() <= 0 ) + if( pOutputInfo->displayModeList.empty() ) { // If this output has no valid display mode, do not save it. delete pOutputInfo; continue; } - hr = pAdapterInfo->outputInfoList.Add( pOutputInfo ); - if( FAILED( hr ) ) - { - delete pOutputInfo; - return hr; - } + pAdapterInfo->outputInfoList.push_back( pOutputInfo ); } } } //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputInfo ) +HRESULT CD3D11Enumeration::EnumerateDisplayModes( _In_ CD3D11EnumOutputInfo* pOutputInfo ) { HRESULT hr = S_OK; DXGI_FORMAT allowedAdapterFormatArray[] = @@ -323,7 +371,7 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI // This is to avoid calling GetDisplayModeList more times than necessary. // GetDisplayModeList is an expensive call. UINT NumModes = 512; - DXGI_MODE_DESC* pDesc = new DXGI_MODE_DESC[ NumModes ]; + auto pDesc = new (std::nothrow) DXGI_MODE_DESC[ NumModes ]; assert( pDesc ); if( !pDesc ) return E_OUTOFMEMORY; @@ -346,14 +394,14 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI { DEVMODE DevMode; DevMode.dmSize = sizeof( DEVMODE ); - if( EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &DevMode ) ) + if( EnumDisplaySettings( nullptr, ENUM_CURRENT_SETTINGS, &DevMode ) ) { NumModes = 1; pDesc[0].Width = DevMode.dmPelsWidth; pDesc[0].Height = DevMode.dmPelsHeight; pDesc[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM; - pDesc[0].RefreshRate.Numerator = 60; - pDesc[0].RefreshRate.Denominator = 1; + pDesc[0].RefreshRate.Numerator = 0; + pDesc[0].RefreshRate.Denominator = 0; pDesc[0].ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE; pDesc[0].Scaling = DXGI_MODE_SCALING_CENTERED; hr = S_OK; @@ -367,14 +415,14 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI hr = pOutputInfo->m_pOutput->GetDisplayModeList( allowedAdapterFormatArray[f], DXGI_ENUM_MODES_SCALING, &NumModes, - NULL ); + nullptr ); if( FAILED( hr ) ) { NumModes = 0; break; } - pDesc = new DXGI_MODE_DESC[ NumModes ]; + pDesc = new (std::nothrow) DXGI_MODE_DESC[ NumModes ]; assert( pDesc ); if( !pDesc ) return E_OUTOFMEMORY; @@ -406,7 +454,8 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI { for( UINT m = 0; m < NumModes; m++ ) { - pOutputInfo->displayModeList.Add( pDesc[m] ); +#pragma warning ( suppress : 6385 ) + pOutputInfo->displayModeList.push_back( pDesc[m] ); } } @@ -418,10 +467,10 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateDevices( CD3D11EnumAdapterInfo* pAdapterInfo ) +HRESULT CD3D11Enumeration::EnumerateDevices( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ) { HRESULT hr; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); + auto deviceSettings = DXUTGetDeviceSettings(); const D3D_DRIVER_TYPE devTypeArray[] = { D3D_DRIVER_TYPE_HARDWARE, @@ -433,33 +482,35 @@ HRESULT CD3D11Enumeration::EnumerateDevices( CD3D11EnumAdapterInfo* pAdapterInfo // Enumerate each Direct3D device type for( UINT iDeviceType = 0; iDeviceType < devTypeArrayCount; iDeviceType++ ) { - CD3D11EnumDeviceInfo* pDeviceInfo = new CD3D11EnumDeviceInfo; - if( pDeviceInfo == NULL ) + auto pDeviceInfo = new (std::nothrow) CD3D11EnumDeviceInfo; + if( !pDeviceInfo ) return E_OUTOFMEMORY; // Fill struct w/ AdapterOrdinal and D3D_DRIVER_TYPE pDeviceInfo->AdapterOrdinal = pAdapterInfo->AdapterOrdinal; pDeviceInfo->DeviceType = devTypeArray[iDeviceType]; - D3D_FEATURE_LEVEL FeatureLevels[] = + static const D3D_FEATURE_LEVEL FeatureLevels[] = { - D3D_FEATURE_LEVEL_11_0, - D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0, - D3D_FEATURE_LEVEL_9_3, - D3D_FEATURE_LEVEL_9_2, - D3D_FEATURE_LEVEL_9_1 +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + D3D_FEATURE_LEVEL_12_1, + D3D_FEATURE_LEVEL_12_0, +#endif + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1 }; UINT NumFeatureLevels = ARRAYSIZE( FeatureLevels ); // Call D3D11CreateDevice to ensure that this is a D3D11 device. - ID3D11Device* pd3dDevice = NULL; - ID3D11DeviceContext* pd3dDeviceContext = NULL; - IDXGIAdapter* pAdapter = NULL; - //if( devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE ) - // pAdapter = pAdapterInfo->m_pAdapter; - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - devTypeArray[iDeviceType], + ID3D11Device* pd3dDevice = nullptr; + ID3D11DeviceContext* pd3dDeviceContext = nullptr; + hr = DXUT_Dynamic_D3D11CreateDevice( (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], ( HMODULE )0, 0, FeatureLevels, @@ -468,163 +519,195 @@ HRESULT CD3D11Enumeration::EnumerateDevices( CD3D11EnumAdapterInfo* pAdapterInfo &pd3dDevice, &pDeviceInfo->MaxLevel, &pd3dDeviceContext ); - if( FAILED( hr ) || pDeviceInfo->MaxLevel < deviceSettings.MinimumFeatureLevel) + + if ( hr == E_INVALIDARG ) + { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + // DirectX 11.1 runtime will not recognize FL 12.x, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice((devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + (HMODULE)0, 0, + &FeatureLevels[2], NumFeatureLevels - 2, + D3D11_SDK_VERSION, &pd3dDevice, &pDeviceInfo->MaxLevel, + &pd3dDeviceContext); + + if (hr == E_INVALIDARG) + { + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice((devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + (HMODULE)0, 0, + &FeatureLevels[3], NumFeatureLevels - 3, + D3D11_SDK_VERSION, &pd3dDevice, &pDeviceInfo->MaxLevel, + &pd3dDeviceContext); + } +#else + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice( (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + ( HMODULE )0, 0, + &FeatureLevels[1], NumFeatureLevels - 1, + D3D11_SDK_VERSION, &pd3dDevice, &pDeviceInfo->MaxLevel, + &pd3dDeviceContext ); +#endif + } + + if ( FAILED(hr) ) { delete pDeviceInfo; continue; } + else if ( pDeviceInfo->MaxLevel < deviceSettings.MinimumFeatureLevel ) + { + delete pDeviceInfo; + SAFE_RELEASE( pd3dDevice ); + SAFE_RELEASE( pd3dDeviceContext ); + continue; + } - if (g_forceFL == 0 || g_forceFL == pDeviceInfo->MaxLevel) { + if (m_forceFL == 0 || m_forceFL == pDeviceInfo->MaxLevel) + { pDeviceInfo->SelectedLevel = pDeviceInfo->MaxLevel; } - else if (g_forceFL > pDeviceInfo->MaxLevel) { + else if (m_forceFL > pDeviceInfo->MaxLevel) + { delete pDeviceInfo; SAFE_RELEASE( pd3dDevice ); SAFE_RELEASE( pd3dDeviceContext ); continue; - } else { + } + else + { // A device was created with a higher feature level that the user-specified feature level. SAFE_RELEASE( pd3dDevice ); SAFE_RELEASE( pd3dDeviceContext ); D3D_FEATURE_LEVEL rtFL; - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - devTypeArray[iDeviceType], - ( HMODULE )0, - 0, - &g_forceFL, - 1, - D3D11_SDK_VERSION, - &pd3dDevice, - &rtFL, - &pd3dDeviceContext ); - - if( !FAILED( hr ) && rtFL == g_forceFL ) { - - pDeviceInfo->SelectedLevel = g_forceFL; - }else { + hr = DXUT_Dynamic_D3D11CreateDevice( (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + ( HMODULE )0, + 0, + &m_forceFL, + 1, + D3D11_SDK_VERSION, + &pd3dDevice, + &rtFL, + &pd3dDeviceContext ); + + if( SUCCEEDED( hr ) && rtFL == m_forceFL ) + { + pDeviceInfo->SelectedLevel = m_forceFL; + } + else + { delete pDeviceInfo; - SAFE_RELEASE( pd3dDevice ); - SAFE_RELEASE( pd3dDeviceContext ); + if ( SUCCEEDED(hr) ) + { + SAFE_RELEASE( pd3dDevice ); + SAFE_RELEASE( pd3dDeviceContext ); + } continue; } } - IDXGIDevice1* pDXGIDev = NULL; - hr = pd3dDevice->QueryInterface( __uuidof( IDXGIDevice1 ), ( LPVOID* )&pDXGIDev ); - if( SUCCEEDED( hr ) && pDXGIDev ) - { - SAFE_RELEASE( pAdapterInfo->m_pAdapter ); - pDXGIDev->GetAdapter( &pAdapterInfo->m_pAdapter ); - } - SAFE_RELEASE( pDXGIDev ); - - D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS ho; - pd3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &ho, sizeof(ho)); + hr = pd3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &ho, sizeof(ho)); + if ( FAILED(hr) ) + memset( &ho, 0, sizeof(ho) ); + pDeviceInfo->ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x = ho.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x; SAFE_RELEASE( pd3dDeviceContext ); SAFE_RELEASE( pd3dDevice ); - pAdapterInfo->deviceInfoList.Add( pDeviceInfo ); + pAdapterInfo->deviceInfoList.push_back( pDeviceInfo ); } return S_OK; } -HRESULT CD3D11Enumeration::EnumerateDeviceCombosNoAdapter( CD3D11EnumAdapterInfo* pAdapterInfo ) +HRESULT CD3D11Enumeration::EnumerateDeviceCombosNoAdapter( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ) { // Iterate through each combination of device driver type, output, // adapter format, and backbuffer format to build the adapter's device combo list. // - for( int device = 0; device < pAdapterInfo->deviceInfoList.GetSize(); ++device ) + for( auto dit = pAdapterInfo->deviceInfoList.cbegin(); dit != pAdapterInfo->deviceInfoList.cend(); ++dit ) + { + DXGI_FORMAT BufferFormatArray[] = { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( device ); + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, //This is DXUT's preferred mode - DXGI_FORMAT BufferFormatArray[] = - { - DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, //This is DXUT's preferred mode - - DXGI_FORMAT_R8G8B8A8_UNORM, - DXGI_FORMAT_R16G16B16A16_FLOAT, - DXGI_FORMAT_R10G10B10A2_UNORM - }; - const UINT BufferFormatArrayCount = sizeof( BufferFormatArray ) / sizeof - ( BufferFormatArray[0] ); - - // Swap perferred modes for apps running in linear space - if( !DXUTIsInGammaCorrectMode() ) - { - BufferFormatArray[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - BufferFormatArray[1] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - } + DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R10G10B10A2_UNORM + }; - for( UINT iBufferFormat = 0; iBufferFormat < BufferFormatArrayCount; iBufferFormat++ ) - { - DXGI_FORMAT BufferFormat = BufferFormatArray[iBufferFormat]; + // Swap perferred modes for apps running in linear space + if( !DXUTIsInGammaCorrectMode() ) + { + BufferFormatArray[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + BufferFormatArray[1] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + } + for( UINT iBufferFormat = 0; iBufferFormat < _countof( BufferFormatArray ); iBufferFormat++ ) + { + DXGI_FORMAT BufferFormat = BufferFormatArray[iBufferFormat]; + // determine if there are any modes for this particular format - // determine if there are any modes for this particular format + // If an application callback function has been provided, make sure this device + // is acceptable to the app. + if( m_IsD3D11DeviceAcceptableFunc ) + { + if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, + 0, + *dit, + BufferFormat, + TRUE, + m_pIsD3D11DeviceAcceptableFuncUserContext ) ) + continue; + } + // At this point, we have an adapter/device/backbufferformat/iswindowed + // DeviceCombo that is supported by the system. We still + // need to find one or more suitable depth/stencil buffer format, + // multisample type, and present interval. + CD3D11EnumDeviceSettingsCombo* pDeviceCombo = new (std::nothrow) CD3D11EnumDeviceSettingsCombo; + if( !pDeviceCombo ) + return E_OUTOFMEMORY; - // If an application callback function has been provided, make sure this device - // is acceptable to the app. - if( m_IsD3D11DeviceAcceptableFunc != NULL ) - { - if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, - 0, - pDeviceInfo, - BufferFormat, - TRUE, - m_pIsD3D11DeviceAcceptableFuncUserContext ) ) - continue; - } + pDeviceCombo->AdapterOrdinal = (*dit)->AdapterOrdinal; + pDeviceCombo->DeviceType = (*dit)->DeviceType; + pDeviceCombo->BackBufferFormat = BufferFormat; + pDeviceCombo->Windowed = TRUE; + pDeviceCombo->Output = 0; + pDeviceCombo->pAdapterInfo = pAdapterInfo; + pDeviceCombo->pDeviceInfo = (*dit); + pDeviceCombo->pOutputInfo = nullptr; - // At this point, we have an adapter/device/backbufferformat/iswindowed - // DeviceCombo that is supported by the system. We still - // need to find one or more suitable depth/stencil buffer format, - // multisample type, and present interval. - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = new CD3D11EnumDeviceSettingsCombo; - if( pDeviceCombo == NULL ) - return E_OUTOFMEMORY; + BuildMultiSampleQualityList( BufferFormat, pDeviceCombo ); - pDeviceCombo->AdapterOrdinal = pDeviceInfo->AdapterOrdinal; - pDeviceCombo->DeviceType = pDeviceInfo->DeviceType; - pDeviceCombo->BackBufferFormat = BufferFormat; - pDeviceCombo->Windowed = TRUE; - pDeviceCombo->Output = 0; - pDeviceCombo->pAdapterInfo = pAdapterInfo; - pDeviceCombo->pDeviceInfo = pDeviceInfo; - pDeviceCombo->pOutputInfo = NULL; - - BuildMultiSampleQualityList( BufferFormat, pDeviceCombo ); - - if( FAILED( pAdapterInfo->deviceSettingsComboList.Add( pDeviceCombo ) ) ) - delete pDeviceCombo; - } - + pAdapterInfo->deviceSettingsComboList.push_back( pDeviceCombo ); } - + } return S_OK; } //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D11EnumAdapterInfo* pAdapterInfo ) +_Use_decl_annotations_ +HRESULT CD3D11Enumeration::EnumerateDeviceCombos( CD3D11EnumAdapterInfo* pAdapterInfo ) { // Iterate through each combination of device driver type, output, // adapter format, and backbuffer format to build the adapter's device combo list. // - - for( int output = 0; output < pAdapterInfo->outputInfoList.GetSize(); ++output ) + for( size_t output = 0; output < pAdapterInfo->outputInfoList.size(); ++output ) { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( output ); + auto pOutputInfo = pAdapterInfo->outputInfoList[ output ]; - for( int device = 0; device < pAdapterInfo->deviceInfoList.GetSize(); ++device ) + for( size_t device = 0; device < pAdapterInfo->deviceInfoList.size(); ++device ) { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( device ); + auto pDeviceInfo = pAdapterInfo->deviceInfoList[ device ]; DXGI_FORMAT backBufferFormatArray[] = { @@ -634,8 +717,6 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM }; - const UINT backBufferFormatArrayCount = sizeof( backBufferFormatArray ) / sizeof - ( backBufferFormatArray[0] ); // Swap perferred modes for apps running in linear space if( !DXUTIsInGammaCorrectMode() ) @@ -644,30 +725,30 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 backBufferFormatArray[1] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; } - for( UINT iBackBufferFormat = 0; iBackBufferFormat < backBufferFormatArrayCount; iBackBufferFormat++ ) + for( UINT iBackBufferFormat = 0; iBackBufferFormat < _countof( backBufferFormatArray ); iBackBufferFormat++ ) { DXGI_FORMAT backBufferFormat = backBufferFormatArray[iBackBufferFormat]; for( int nWindowed = 0; nWindowed < 2; nWindowed++ ) { - if( !nWindowed && pOutputInfo->displayModeList.GetSize() == 0 ) + if( !nWindowed && pOutputInfo->displayModeList.size() == 0 ) continue; // determine if there are any modes for this particular format - UINT iModes = 0; - for( int i = 0; i < pOutputInfo->displayModeList.GetSize(); i++ ) + size_t iModes = 0; + for( size_t i = 0; i < pOutputInfo->displayModeList.size(); i++ ) { - if( backBufferFormat == pOutputInfo->displayModeList.GetAt( i ).Format ) - iModes ++; + if( backBufferFormat == pOutputInfo->displayModeList[ i ].Format ) + ++iModes; } - if( 0 == iModes ) + if( !iModes ) continue; // If an application callback function has been provided, make sure this device // is acceptable to the app. - if( m_IsD3D11DeviceAcceptableFunc != NULL ) + if( m_IsD3D11DeviceAcceptableFunc ) { - if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, output, + if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, static_cast( output ), pDeviceInfo, backBufferFormat, FALSE != nWindowed, m_pIsD3D11DeviceAcceptableFuncUserContext ) ) @@ -678,8 +759,8 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 // DeviceCombo that is supported by the system. We still // need to find one or more suitable depth/stencil buffer format, // multisample type, and present interval. - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = new CD3D11EnumDeviceSettingsCombo; - if( pDeviceCombo == NULL ) + auto pDeviceCombo = new (std::nothrow) CD3D11EnumDeviceSettingsCombo; + if( !pDeviceCombo ) return E_OUTOFMEMORY; pDeviceCombo->AdapterOrdinal = pDeviceInfo->AdapterOrdinal; @@ -693,8 +774,7 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 BuildMultiSampleQualityList( backBufferFormat, pDeviceCombo ); - if( FAILED( pAdapterInfo->deviceSettingsComboList.Add( pDeviceCombo ) ) ) - delete pDeviceCombo; + pAdapterInfo->deviceSettingsComboList.push_back( pDeviceCombo ); } } } @@ -709,47 +789,41 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 //-------------------------------------------------------------------------------------- void CD3D11Enumeration::ClearAdapterInfoList() { - CD3D11EnumAdapterInfo* pAdapterInfo; - for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ ) + for( auto it = m_AdapterInfoList.begin(); it != m_AdapterInfoList.end(); ++it ) { - pAdapterInfo = m_AdapterInfoList.GetAt( i ); + auto pAdapterInfo = *it; delete pAdapterInfo; } - - m_AdapterInfoList.RemoveAll(); + m_AdapterInfoList.clear(); } //-------------------------------------------------------------------------------------- void CD3D11Enumeration::ResetPossibleDepthStencilFormats() { - m_DepthStencilPossibleList.RemoveAll(); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D32_FLOAT_S8X24_UINT ); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D32_FLOAT ); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D24_UNORM_S8_UINT ); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D16_UNORM ); + m_DepthStencilPossibleList.clear(); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D32_FLOAT_S8X24_UINT ); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D32_FLOAT ); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D24_UNORM_S8_UINT ); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D16_UNORM ); } + //-------------------------------------------------------------------------------------- -void CD3D11Enumeration::SetEnumerateAllAdapterFormats( bool bEnumerateAllAdapterFormats ) +void CD3D11Enumeration::SetEnumerateAllAdapterFormats( _In_ bool bEnumerateAllAdapterFormats ) { m_bEnumerateAllAdapterFormats = bEnumerateAllAdapterFormats; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CD3D11Enumeration::BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11EnumDeviceSettingsCombo* pDeviceCombo ) { - ID3D11Device* pd3dDevice = NULL; - ID3D11DeviceContext* pd3dDeviceContext = NULL; - IDXGIAdapter* pAdapter = NULL; + ID3D11Device* pd3dDevice = nullptr; + ID3D11DeviceContext* pd3dDeviceContext = nullptr; + IDXGIAdapter* pAdapter = nullptr; - //if( pDeviceCombo->DeviceType == D3D_DRIVER_TYPE_HARDWARE ) - // DXUTGetDXGIFactory()->EnumAdapters( pDeviceCombo->pAdapterInfo->AdapterOrdinal, &pAdapter ); - - //DXGI_ADAPTER_DESC dad; - //pAdapter->GetDesc(&dad); - D3D_FEATURE_LEVEL *FeatureLevels = &(pDeviceCombo->pDeviceInfo->SelectedLevel); D3D_FEATURE_LEVEL returnedFeatureLevel; @@ -781,8 +855,8 @@ void CD3D11Enumeration::BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11Enum //the format and sample count combination is not supported for the installed adapter. if (Quality != 0) { - pDeviceCombo->multiSampleCountList.Add( i ); - pDeviceCombo->multiSampleQualityList.Add( Quality ); + pDeviceCombo->multiSampleCountList.push_back( i ); + pDeviceCombo->multiSampleQualityList.push_back( Quality ); } } } @@ -797,84 +871,83 @@ void CD3D11Enumeration::BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11Enum // Call GetAdapterInfoList() after Enumerate() to get a STL vector of // CD3D11EnumAdapterInfo* //-------------------------------------------------------------------------------------- -CGrowableArray * CD3D11Enumeration::GetAdapterInfoList() +std::vector * CD3D11Enumeration::GetAdapterInfoList() { return &m_AdapterInfoList; } //-------------------------------------------------------------------------------------- -CD3D11EnumAdapterInfo* CD3D11Enumeration::GetAdapterInfo( UINT AdapterOrdinal ) +CD3D11EnumAdapterInfo* CD3D11Enumeration::GetAdapterInfo( _In_ UINT AdapterOrdinal ) const { - for( int iAdapter = 0; iAdapter < m_AdapterInfoList.GetSize(); iAdapter++ ) + for( auto it = m_AdapterInfoList.cbegin(); it != m_AdapterInfoList.cend(); ++it ) { - CD3D11EnumAdapterInfo* pAdapterInfo = m_AdapterInfoList.GetAt( iAdapter ); - if( pAdapterInfo->AdapterOrdinal == AdapterOrdinal ) - return pAdapterInfo; + if( (*it)->AdapterOrdinal == AdapterOrdinal ) + return *it; } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -CD3D11EnumDeviceInfo* CD3D11Enumeration::GetDeviceInfo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType ) +_Use_decl_annotations_ +CD3D11EnumDeviceInfo* CD3D11Enumeration::GetDeviceInfo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType ) const { - CD3D11EnumAdapterInfo* pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); + auto pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); if( pAdapterInfo ) { - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) + for( auto it = pAdapterInfo->deviceInfoList.cbegin(); it != pAdapterInfo->deviceInfoList.cend(); ++it ) { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); - if( pDeviceInfo->DeviceType == DeviceType ) - return pDeviceInfo; + if( (*it)->DeviceType == DeviceType ) + return *it; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -CD3D11EnumOutputInfo* CD3D11Enumeration::GetOutputInfo( UINT AdapterOrdinal, UINT Output ) +_Use_decl_annotations_ +CD3D11EnumOutputInfo* CD3D11Enumeration::GetOutputInfo( UINT AdapterOrdinal, UINT Output ) const { - CD3D11EnumAdapterInfo* pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); - if( pAdapterInfo && pAdapterInfo->outputInfoList.GetSize() > int( Output ) ) + auto pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); + if( pAdapterInfo && pAdapterInfo->outputInfoList.size() > size_t( Output ) ) { - return pAdapterInfo->outputInfoList.GetAt( Output ); + return pAdapterInfo->outputInfoList[ Output ]; } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ CD3D11EnumDeviceSettingsCombo* CD3D11Enumeration::GetDeviceSettingsCombo( UINT AdapterOrdinal, - D3D_DRIVER_TYPE DeviceType, UINT Output, - DXGI_FORMAT BackBufferFormat, BOOL Windowed ) + DXGI_FORMAT BackBufferFormat, BOOL Windowed ) const { - CD3D11EnumAdapterInfo* pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); + auto pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); if( pAdapterInfo ) { - for( int iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) + for( size_t iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.size(); iDeviceCombo++ ) { - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList.GetAt( - iDeviceCombo ); + auto pDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList[ iDeviceCombo ]; if( pDeviceSettingsCombo->BackBufferFormat == BackBufferFormat && pDeviceSettingsCombo->Windowed == Windowed ) return pDeviceSettingsCombo; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -CD3D11EnumOutputInfo::~CD3D11EnumOutputInfo( void ) +CD3D11EnumOutputInfo::~CD3D11EnumOutputInfo() { SAFE_RELEASE( m_pOutput ); - displayModeList.RemoveAll(); + displayModeList.clear(); } @@ -885,28 +958,28 @@ CD3D11EnumDeviceInfo::~CD3D11EnumDeviceInfo() //-------------------------------------------------------------------------------------- -CD3D11EnumAdapterInfo::~CD3D11EnumAdapterInfo( void ) +CD3D11EnumAdapterInfo::~CD3D11EnumAdapterInfo() { - for( int i = 0; i < outputInfoList.GetSize(); i++ ) + for( size_t j = 0; j < outputInfoList.size(); ++j ) { - CD3D11EnumOutputInfo* pOutputInfo = outputInfoList.GetAt( i ); + auto pOutputInfo = outputInfoList[ j ]; delete pOutputInfo; } - outputInfoList.RemoveAll(); + outputInfoList.clear(); - for( int i = 0; i < deviceInfoList.GetSize(); ++i ) + for( size_t j = 0; j < deviceInfoList.size(); ++j ) { - CD3D11EnumDeviceInfo* pDeviceInfo = deviceInfoList.GetAt( i ); + auto pDeviceInfo = deviceInfoList[ j ]; delete pDeviceInfo; } - deviceInfoList.RemoveAll(); + deviceInfoList.clear(); - for( int i = 0; i < deviceSettingsComboList.GetSize(); ++i ) + for( size_t j = 0; j < deviceSettingsComboList.size(); ++j ) { - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = deviceSettingsComboList.GetAt( i ); + auto pDeviceCombo = deviceSettingsComboList[ j ]; delete pDeviceCombo; } - deviceSettingsComboList.RemoveAll(); + deviceSettingsComboList.clear(); SAFE_RELEASE( m_pAdapter ); } @@ -939,6 +1012,7 @@ UINT WINAPI DXUTGetDXGIColorChannelBits( DXGI_FORMAT fmt ) case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: return 10; case DXGI_FORMAT_R8G8B8A8_TYPELESS: @@ -947,12 +1021,21 @@ UINT WINAPI DXUTGetDXGIColorChannelBits( DXGI_FORMAT fmt ) case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return 8; case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: return 5; + case DXGI_FORMAT_B4G4R4A4_UNORM: + return 4; + default: return 0; } @@ -962,9 +1045,9 @@ UINT WINAPI DXUTGetDXGIColorChannelBits( DXGI_FORMAT fmt ) // Returns a ranking number that describes how closely this device // combo matches the optimal combo based on the match options and the optimal device settings //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo, DXUTD3D11DeviceSettings* pOptimalDeviceSettings, - DXGI_MODE_DESC* pAdapterDisplayMode, int &bestModeIndex, int &bestMSAAIndex ) @@ -981,7 +1064,6 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo const float fResolutionWeight = 1.0f; const float fBackBufferFormatWeight = 1.0f; const float fMultiSampleWeight = 1.0f; - const float fRefreshRateWeight = 1.0f; //--------------------- // Adapter ordinal @@ -1005,7 +1087,7 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo } // Slightly prefer HAL - if( pDeviceSettingsCombo->DeviceType == D3DDEVTYPE_HAL ) + if( pDeviceSettingsCombo->DeviceType == D3D_DRIVER_TYPE_HARDWARE ) fCurRanking += 0.1f; //--------------------- @@ -1015,31 +1097,76 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo fCurRanking += fWindowWeight; //--------------------- - // Resolution + // Resolution/Refresh Rate //--------------------- - bool bResolutionFound = false; - unsigned int best = 0xffffffff; bestModeIndex=0; - for( int idm = 0; pDeviceSettingsCombo->pOutputInfo != NULL && idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.GetSize() && !bResolutionFound; idm++ ) + + if( pDeviceSettingsCombo->pOutputInfo ) { - DXGI_MODE_DESC displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList.GetAt( idm ); - if( displayMode.Width == pOptimalDeviceSettings->sd.BufferDesc.Width && - displayMode.Height == pOptimalDeviceSettings->sd.BufferDesc.Height ) - bResolutionFound = true; + bool bResolutionFound = false; + float best = FLT_MAX; + + if ( !pDeviceSettingsCombo->Windowed + && !pOptimalDeviceSettings->sd.Windowed + && ( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Numerator > 0 || pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Denominator > 0 ) ) + { + // Match both Resolution & Refresh Rate + for( size_t idm = 0; idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.size() && !bResolutionFound; idm++ ) + { + auto displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList[ idm ]; + + float refreshDiff = fabsf( ( float( displayMode.RefreshRate.Numerator ) / float( displayMode.RefreshRate.Denominator ) ) - + ( float( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Numerator ) / float( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Denominator ) ) ); + + if( displayMode.Width == pOptimalDeviceSettings->sd.BufferDesc.Width + && displayMode.Height == pOptimalDeviceSettings->sd.BufferDesc.Height + && ( refreshDiff < 0.1f ) ) + { + bResolutionFound = true; + bestModeIndex = static_cast( idm ); + break; + } + + float current = refreshDiff + + fabsf( float( displayMode.Width ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Width ) ) + + fabsf( float( displayMode.Height ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Height ) ); - unsigned int current = - (UINT) abs ((int)displayMode.Width - (int)pOptimalDeviceSettings->sd.BufferDesc.Width) + - (UINT) abs ((int)displayMode.Height - (int)pOptimalDeviceSettings->sd.BufferDesc.Height ); + if( current < best ) + { + best = current; + bestModeIndex = static_cast( idm ); + } + } + } + else + { + // Match just Resolution + for( size_t idm = 0; idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.size() && !bResolutionFound; idm++ ) + { + auto displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList[ idm ]; - if (current < best) { - best = current; - bestModeIndex= idm; + if( displayMode.Width == pOptimalDeviceSettings->sd.BufferDesc.Width + && displayMode.Height == pOptimalDeviceSettings->sd.BufferDesc.Height ) + { + bResolutionFound = true; + bestModeIndex = static_cast( idm ); + break; + } + float current = fabsf( float( displayMode.Width ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Width ) ) + + fabsf( float( displayMode.Height ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Height ) ); + + if( current < best ) + { + best = current; + bestModeIndex = static_cast( idm ); + } + } } + if( bResolutionFound ) + fCurRanking += fResolutionWeight; } - if( bResolutionFound ) - fCurRanking += fResolutionWeight; //--------------------- // Back buffer format @@ -1053,7 +1180,7 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo int nBitDepthDelta = abs( ( long )DXUTGetDXGIColorChannelBits( pDeviceSettingsCombo->BackBufferFormat ) - ( long )DXUTGetDXGIColorChannelBits( pOptimalDeviceSettings->sd.BufferDesc.Format ) ); - float fScale = __max( 0.9f - ( float )nBitDepthDelta * 0.2f, 0.0f ); + float fScale = std::max( 0.9f - ( float )nBitDepthDelta * 0.2f, 0.0f ); fCurRanking += fScale * fBackBufferFormatWeight; } @@ -1067,13 +1194,13 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo //--------------------- bool bMultiSampleFound = false; bestMSAAIndex = 0; - for( int i = 0; i < pDeviceSettingsCombo->multiSampleCountList.GetSize(); i++ ) + for( size_t i = 0; i < pDeviceSettingsCombo->multiSampleCountList.size(); i++ ) { - UINT Count = pDeviceSettingsCombo->multiSampleCountList.GetAt( i ); + UINT Count = pDeviceSettingsCombo->multiSampleCountList[ i ]; if( Count == pOptimalDeviceSettings->sd.SampleDesc.Count ) { - bestMSAAIndex = i; + bestMSAAIndex = static_cast( i ); bMultiSampleFound = true; break; } @@ -1096,21 +1223,6 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo //--------------------- // No caps for the present flags - //--------------------- - // Refresh rate - //--------------------- - bool bRefreshFound = false; - for( int idm = 0; pDeviceSettingsCombo->pOutputInfo != NULL && idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.GetSize(); idm++ ) - { - DXGI_MODE_DESC displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList.GetAt( idm ); - if( fabs( float( displayMode.RefreshRate.Numerator ) / displayMode.RefreshRate.Denominator - - float( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Numerator ) / - pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Denominator ) < 0.1f ) - bRefreshFound = true; - } - if( bRefreshFound ) - fCurRanking += fRefreshRateWeight; - //--------------------- // Present interval //--------------------- @@ -1123,32 +1235,38 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo //-------------------------------------------------------------------------------------- // Returns the DXGI_MODE_DESC struct for a given adapter and output //-------------------------------------------------------------------------------------- +#pragma warning ( suppress : 6101 ) +_Use_decl_annotations_ HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( UINT AdapterOrdinal, UINT nOutput, DXGI_MODE_DESC* pModeDesc ) { if( !pModeDesc ) return E_INVALIDARG; - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - CD3D11EnumOutputInfo* pOutputInfo = pD3DEnum->GetOutputInfo( AdapterOrdinal, nOutput ); + auto pD3DEnum = DXUTGetD3D11Enumeration(); + if ( !pD3DEnum ) + return E_POINTER; + + auto pOutputInfo = pD3DEnum->GetOutputInfo( AdapterOrdinal, nOutput ); if( pOutputInfo ) { - pModeDesc->Width = 640; - pModeDesc->Height = 480; - pModeDesc->RefreshRate.Numerator = 60; - pModeDesc->RefreshRate.Denominator = 1; + pModeDesc->Width = 800; + pModeDesc->Height = 600; + pModeDesc->RefreshRate.Numerator = 0; + pModeDesc->RefreshRate.Denominator = 0; pModeDesc->Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; pModeDesc->Scaling = DXGI_MODE_SCALING_UNSPECIFIED; pModeDesc->ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; DXGI_OUTPUT_DESC Desc; - pOutputInfo->m_pOutput->GetDesc( &Desc ); + if ( FAILED(pOutputInfo->m_pOutput->GetDesc(&Desc))) + memset( &Desc, 0, sizeof(Desc) ); pModeDesc->Width = Desc.DesktopCoordinates.right - Desc.DesktopCoordinates.left; pModeDesc->Height = Desc.DesktopCoordinates.bottom - Desc.DesktopCoordinates.top; - } - // This should not be required with DXGI 1.1 support for BGRA... - if( pModeDesc->Format == DXGI_FORMAT_B8G8R8A8_UNORM ) - pModeDesc->Format = DXGI_FORMAT_R8G8B8A8_UNORM; + // This should not be required with DXGI 1.1 support for BGRA... + if( pModeDesc->Format == DXGI_FORMAT_B8G8R8A8_UNORM ) + pModeDesc->Format = DXGI_FORMAT_R8G8B8A8_UNORM; + } return S_OK; } diff --git a/FriedLiver/Source/DXUT/Core/DXUTDevice11.h b/FriedLiver/Source/DXUT/Core/DXUTDevice11.h index c15c571e..8c73c453 100644 --- a/FriedLiver/Source/DXUT/Core/DXUTDevice11.h +++ b/FriedLiver/Source/DXUT/Core/DXUTDevice11.h @@ -4,17 +4,18 @@ // Enumerates D3D adapters, devices, modes, etc. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_DEVICE11_H -#define DXUT_DEVICE11_H void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings); //-------------------------------------------------------------------------------------- // Functions to get bit depth from formats //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( UINT AdapterOrdinal, UINT Output, DXGI_MODE_DESC* pModeDesc ); +HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( _In_ UINT AdapterOrdinal, _In_ UINT Output, _Out_ DXGI_MODE_DESC* pModeDesc ); @@ -39,8 +40,7 @@ struct CD3D11EnumDeviceSettingsCombo; //-------------------------------------------------------------------------------------- -// Enumerates available Direct3D10 adapters, devices, modes, etc. -// Use DXUTGetD3D9Enumeration() to access global instance +// Enumerates available Direct3D11 adapters, devices, modes, etc. //-------------------------------------------------------------------------------------- class CD3D11Enumeration { @@ -49,28 +49,27 @@ class CD3D11Enumeration // // Use these calls and the IsDeviceAcceptable to control the contents of // the enumeration object, which affects the device selection and the device settings dialog. - void SetResolutionMinMax( UINT nMinWidth, UINT nMinHeight, UINT nMaxWidth, UINT nMaxHeight ); - void SetRefreshMinMax( UINT nMin, UINT nMax ); - void SetForceFeatureLevel( D3D_FEATURE_LEVEL forceFL) { - g_forceFL = forceFL; - }; - void SetMultisampleQualityMax( UINT nMax ); - CGrowableArray* GetPossibleDepthStencilFormatList(); + void SetResolutionMinMax( _In_ UINT nMinWidth, _In_ UINT nMinHeight, _In_ UINT nMaxWidth, _In_ UINT nMaxHeight ); + void SetRefreshMinMax( _In_ UINT nMin, _In_ UINT nMax ); + void SetForceFeatureLevel( _In_ D3D_FEATURE_LEVEL forceFL) { m_forceFL = forceFL; } + void SetMultisampleQualityMax( _In_ UINT nMax ); void ResetPossibleDepthStencilFormats(); - void SetEnumerateAllAdapterFormats( bool bEnumerateAllAdapterFormats ); + void SetEnumerateAllAdapterFormats( _In_ bool bEnumerateAllAdapterFormats ); // Call Enumerate() to enumerate available D3D11 adapters, devices, modes, etc. bool HasEnumerated() { return m_bHasEnumerated; } - HRESULT Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, - void* pIsD3D11DeviceAcceptableFuncUserContext ); + HRESULT Enumerate( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, + _In_opt_ void* pIsD3D11DeviceAcceptableFuncUserContext ); // These should be called after Enumerate() is called - CGrowableArray* GetAdapterInfoList(); - CD3D11EnumAdapterInfo* GetAdapterInfo( UINT AdapterOrdinal ); - CD3D11EnumDeviceInfo* GetDeviceInfo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType ); - CD3D11EnumOutputInfo* GetOutputInfo( UINT AdapterOrdinal, UINT Output ); - CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( DXUTD3D11DeviceSettings* pDeviceSettings ) { return GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->DriverType, pDeviceSettings->Output, pDeviceSettings->sd.BufferDesc.Format, pDeviceSettings->sd.Windowed ); } - CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType, UINT Output, DXGI_FORMAT BackBufferFormat, BOOL Windowed ); + std::vector* GetAdapterInfoList(); + CD3D11EnumAdapterInfo* GetAdapterInfo( _In_ UINT AdapterOrdinal ) const; + CD3D11EnumDeviceInfo* GetDeviceInfo( _In_ UINT AdapterOrdinal, _In_ D3D_DRIVER_TYPE DeviceType ) const; + CD3D11EnumOutputInfo* GetOutputInfo( _In_ UINT AdapterOrdinal, _In_ UINT Output ) const; + CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ DXUTD3D11DeviceSettings* pDeviceSettings ) const { return GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->sd.BufferDesc.Format, pDeviceSettings->sd.Windowed ); } + CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ UINT AdapterOrdinal, _In_ DXGI_FORMAT BackBufferFormat, _In_ BOOL Windowed ) const; + D3D_FEATURE_LEVEL GetWARPFeaturevel() const { return m_warpFL; } + D3D_FEATURE_LEVEL GetREFFeaturevel() const { return m_refFL; } ~CD3D11Enumeration(); @@ -78,38 +77,32 @@ class CD3D11Enumeration friend HRESULT WINAPI DXUTCreateD3D11Enumeration(); // Use DXUTGetD3D11Enumeration() to access global instance - CD3D11Enumeration(); + CD3D11Enumeration() noexcept; bool m_bHasEnumerated; LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE m_IsD3D11DeviceAcceptableFunc; void* m_pIsD3D11DeviceAcceptableFuncUserContext; - CGrowableArray m_DepthStencilPossibleList; + std::vector m_DepthStencilPossibleList; - UINT m_nMinWidth; - UINT m_nMaxWidth; - UINT m_nMinHeight; - UINT m_nMaxHeight; - UINT m_nRefreshMin; - UINT m_nRefreshMax; - UINT m_nMultisampleQualityMax; bool m_bEnumerateAllAdapterFormats; - D3D_FEATURE_LEVEL g_forceFL; + D3D_FEATURE_LEVEL m_forceFL; + D3D_FEATURE_LEVEL m_warpFL; + D3D_FEATURE_LEVEL m_refFL; - // Array of CD3D9EnumAdapterInfo* with unique AdapterOrdinals - CGrowableArray m_AdapterInfoList; + std::vector m_AdapterInfoList; - HRESULT EnumerateOutputs( CD3D11EnumAdapterInfo *pAdapterInfo ); - HRESULT EnumerateDevices( CD3D11EnumAdapterInfo *pAdapterInfo ); - HRESULT EnumerateDeviceCombos( IDXGIFactory1 *pFactory, CD3D11EnumAdapterInfo* pAdapterInfo ); - HRESULT EnumerateDeviceCombosNoAdapter( CD3D11EnumAdapterInfo* pAdapterInfo ); + HRESULT EnumerateOutputs( _In_ CD3D11EnumAdapterInfo *pAdapterInfo ); + HRESULT EnumerateDevices( _In_ CD3D11EnumAdapterInfo *pAdapterInfo ); + HRESULT EnumerateDeviceCombos( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ); + HRESULT EnumerateDeviceCombosNoAdapter( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ); - HRESULT EnumerateDisplayModes( CD3D11EnumOutputInfo *pOutputInfo ); - void BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11EnumDeviceSettingsCombo* pDeviceCombo ); + HRESULT EnumerateDisplayModes( _In_ CD3D11EnumOutputInfo *pOutputInfo ); + void BuildMultiSampleQualityList( _In_ DXGI_FORMAT fmt, _In_ CD3D11EnumDeviceSettingsCombo* pDeviceCombo ); void ClearAdapterInfoList(); }; -CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration(bool bForceEnumerate = false, bool EnumerateAllAdapterFormats = false, D3D_FEATURE_LEVEL forceFL = ((D3D_FEATURE_LEVEL )0) ); +CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration(_In_ bool bForceEnumerate = false, _In_ bool EnumerateAllAdapterFormats = true, _In_ D3D_FEATURE_LEVEL forceFL = ((D3D_FEATURE_LEVEL )0) ); #define DXGI_MAX_DEVICE_IDENTIFIER_STRING 128 @@ -123,6 +116,16 @@ class CD3D11EnumAdapterInfo const CD3D11EnumAdapterInfo &operator = ( const CD3D11EnumAdapterInfo &rhs ); public: + CD3D11EnumAdapterInfo() noexcept : + AdapterOrdinal( 0 ), + AdapterDesc{}, + szUniqueDescription{}, + m_pAdapter( nullptr ), + bAdapterUnavailable(false) + { + *szUniqueDescription = 0; + memset( &AdapterDesc, 0, sizeof(AdapterDesc) ); + } ~CD3D11EnumAdapterInfo(); UINT AdapterOrdinal; @@ -131,11 +134,11 @@ class CD3D11EnumAdapterInfo IDXGIAdapter *m_pAdapter; bool bAdapterUnavailable; - CGrowableArray outputInfoList; // Array of CD3D11EnumOutputInfo* - CGrowableArray deviceInfoList; // Array of CD3D11EnumDeviceInfo* + std::vector outputInfoList; // Array of CD3D11EnumOutputInfo* + std::vector deviceInfoList; // Array of CD3D11EnumDeviceInfo* // List of CD3D11EnumDeviceSettingsCombo* with a unique set // of BackBufferFormat, and Windowed - CGrowableArray deviceSettingsComboList; + std::vector deviceSettingsComboList; }; @@ -144,6 +147,12 @@ class CD3D11EnumOutputInfo const CD3D11EnumOutputInfo &operator = ( const CD3D11EnumOutputInfo &rhs ); public: + CD3D11EnumOutputInfo() noexcept : + AdapterOrdinal(0), + Output(0), + m_pOutput(nullptr), + Desc{} + {} ~CD3D11EnumOutputInfo(); UINT AdapterOrdinal; @@ -151,13 +160,12 @@ class CD3D11EnumOutputInfo IDXGIOutput* m_pOutput; DXGI_OUTPUT_DESC Desc; - CGrowableArray displayModeList; // Array of supported D3DDISPLAYMODEs + std::vector displayModeList; // Array of supported D3DDISPLAYMODEs }; //-------------------------------------------------------------------------------------- -// A class describing a Direct3D10 device that contains a -// unique supported driver type +// A class describing a Direct3D11 device that contains a unique supported driver type //-------------------------------------------------------------------------------------- class CD3D11EnumDeviceInfo { @@ -187,24 +195,27 @@ struct CD3D11EnumDeviceSettingsCombo BOOL Windowed; UINT Output; - CGrowableArray multiSampleCountList; // List of valid sampling counts (multisampling) - CGrowableArray multiSampleQualityList; // List of number of quality levels for each multisample count + std::vector multiSampleCountList; // List of valid sampling counts (multisampling) + std::vector multiSampleQualityList; // List of number of quality levels for each multisample count CD3D11EnumAdapterInfo* pAdapterInfo; CD3D11EnumDeviceInfo* pDeviceInfo; CD3D11EnumOutputInfo* pOutputInfo; + + CD3D11EnumDeviceSettingsCombo() noexcept : + AdapterOrdinal(0), + DeviceType(D3D_DRIVER_TYPE_UNKNOWN), + BackBufferFormat(DXGI_FORMAT_UNKNOWN), + Windowed(FALSE), + Output(0), + pAdapterInfo(nullptr), + pDeviceInfo(nullptr), + pOutputInfo(nullptr) + { } }; -float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo, - DXUTD3D11DeviceSettings* pOptimalDeviceSettings, - DXGI_MODE_DESC* pAdapterDisplayMode, - int &bestModeIndex, - int &bestMSAAIndex +float DXUTRankD3D11DeviceCombo( _In_ CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo, + _In_ DXUTD3D11DeviceSettings* pOptimalDeviceSettings, + _Out_ int &bestModeIndex, + _Out_ int &bestMSAAIndex ); - - - - -#endif - - diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2015.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_2015.vcxproj new file mode 100644 index 00000000..71c4ea23 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2015.vcxproj @@ -0,0 +1,330 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + WIN32;NDEBUG;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + WIN32;NDEBUG;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2015.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_2015.vcxproj.filters new file mode 100644 index 00000000..78f1ab4e --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2015.vcxproj.filters @@ -0,0 +1,29 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2015_Win10.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_2015_Win10.vcxproj new file mode 100644 index 00000000..1171fd10 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2015_Win10.vcxproj @@ -0,0 +1,331 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + 10.0.14393.0 + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2015_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_2015_Win10.vcxproj.filters new file mode 100644 index 00000000..78f1ab4e --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2015_Win10.vcxproj.filters @@ -0,0 +1,29 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2017_Win10.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_2017_Win10.vcxproj new file mode 100644 index 00000000..ed3b43ff --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2017_Win10.vcxproj @@ -0,0 +1,343 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + 10.0.17763.0 + + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2017_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_2017_Win10.vcxproj.filters new file mode 100644 index 00000000..78f1ab4e --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2017_Win10.vcxproj.filters @@ -0,0 +1,29 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2019_Win10.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_2019_Win10.vcxproj new file mode 100644 index 00000000..f1a73cc2 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2019_Win10.vcxproj @@ -0,0 +1,343 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + 10.0 + + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_2019_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_2019_Win10.vcxproj.filters new file mode 100644 index 00000000..78f1ab4e --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_2019_Win10.vcxproj.filters @@ -0,0 +1,29 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015.vcxproj new file mode 100644 index 00000000..8ba13077 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015.vcxproj @@ -0,0 +1,330 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015.vcxproj.filters new file mode 100644 index 00000000..153fbf34 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015.vcxproj.filters @@ -0,0 +1,23 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015_Win10.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015_Win10.vcxproj new file mode 100644 index 00000000..98ecdfee --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015_Win10.vcxproj @@ -0,0 +1,331 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + 10.0.14393.0 + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015_Win10.vcxproj.filters new file mode 100644 index 00000000..153fbf34 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2015_Win10.vcxproj.filters @@ -0,0 +1,23 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2017_Win10.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2017_Win10.vcxproj new file mode 100644 index 00000000..27193abe --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2017_Win10.vcxproj @@ -0,0 +1,343 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + 10.0.17763.0 + + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2017_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2017_Win10.vcxproj.filters new file mode 100644 index 00000000..153fbf34 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2017_Win10.vcxproj.filters @@ -0,0 +1,23 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2019_Win10.vcxproj b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2019_Win10.vcxproj new file mode 100644 index 00000000..4764175b --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2019_Win10.vcxproj @@ -0,0 +1,343 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUT + {85344B7F-5AA0-4e12-A065-D1333D11F6CA} + DXUT + Win32Proj + 10.0 + + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUT + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUT + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2019_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2019_Win10.vcxproj.filters new file mode 100644 index 00000000..153fbf34 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/DXUT_DirectXTK_2019_Win10.vcxproj.filters @@ -0,0 +1,23 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Core/DXUTmisc.cpp b/FriedLiver/Source/DXUT/Core/DXUTmisc.cpp index 499abfdf..83a5e453 100644 --- a/FriedLiver/Source/DXUT/Core/DXUTmisc.cpp +++ b/FriedLiver/Source/DXUT/Core/DXUTmisc.cpp @@ -3,13 +3,18 @@ // // Shortcut macros and functions for using DX objects // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "dxut.h" #include + +#include "ScreenGrab.h" + + #define DXUT_GAMEPAD_TRIGGER_THRESHOLD 30 -#undef min // use __min instead -#undef max // use __max instead CDXUTTimer* WINAPI DXUTGetGlobalTimer() { @@ -20,17 +25,15 @@ CDXUTTimer* WINAPI DXUTGetGlobalTimer() //-------------------------------------------------------------------------------------- -CDXUTTimer::CDXUTTimer() +CDXUTTimer::CDXUTTimer() noexcept : + m_bTimerStopped(true), + m_llQPFTicksPerSec{}, + m_llStopTime{}, + m_llLastElapsedTime{}, + m_llBaseTime{} { - m_bTimerStopped = true; - m_llQPFTicksPerSec = 0; - - m_llStopTime = 0; - m_llLastElapsedTime = 0; - m_llBaseTime = 0; - // Use QueryPerformanceFrequency to get the frequency of the counter - LARGE_INTEGER qwTicksPerSec = { 0 }; + LARGE_INTEGER qwTicksPerSec = {}; QueryPerformanceFrequency( &qwTicksPerSec ); m_llQPFTicksPerSec = qwTicksPerSec.QuadPart; } @@ -52,7 +55,7 @@ void CDXUTTimer::Reset() void CDXUTTimer::Start() { // Get the current time - LARGE_INTEGER qwTime = { 0 }; + LARGE_INTEGER qwTime = {}; QueryPerformanceCounter( &qwTime ); if( m_bTimerStopped ) @@ -68,7 +71,7 @@ void CDXUTTimer::Stop() { if( !m_bTimerStopped ) { - LARGE_INTEGER qwTime = { 0 }; + LARGE_INTEGER qwTime = {}; QueryPerformanceCounter( &qwTime ); m_llStopTime = qwTime.QuadPart; m_llLastElapsedTime = qwTime.QuadPart; @@ -85,9 +88,9 @@ void CDXUTTimer::Advance() //-------------------------------------------------------------------------------------- -double CDXUTTimer::GetAbsoluteTime() +double CDXUTTimer::GetAbsoluteTime() const { - LARGE_INTEGER qwTime = { 0 }; + LARGE_INTEGER qwTime = {}; QueryPerformanceCounter( &qwTime ); double fTime = qwTime.QuadPart / ( double )m_llQPFTicksPerSec; @@ -97,7 +100,7 @@ double CDXUTTimer::GetAbsoluteTime() //-------------------------------------------------------------------------------------- -double CDXUTTimer::GetTime() +double CDXUTTimer::GetTime() const { LARGE_INTEGER qwTime = GetAdjustedCurrentTime(); @@ -108,6 +111,7 @@ double CDXUTTimer::GetTime() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTTimer::GetTimeValues( double* pfTime, double* pfAbsoluteTime, float* pfElapsedTime ) { assert( pfTime && pfAbsoluteTime && pfElapsedTime ); @@ -152,7 +156,7 @@ float CDXUTTimer::GetElapsedTime() //-------------------------------------------------------------------------------------- // If stopped, returns time when stopped otherwise returns current time //-------------------------------------------------------------------------------------- -LARGE_INTEGER CDXUTTimer::GetAdjustedCurrentTime() +LARGE_INTEGER CDXUTTimer::GetAdjustedCurrentTime() const { LARGE_INTEGER qwTime; if( m_llStopTime != 0 ) @@ -162,12 +166,6 @@ LARGE_INTEGER CDXUTTimer::GetAdjustedCurrentTime() return qwTime; } -//-------------------------------------------------------------------------------------- -bool CDXUTTimer::IsStopped() -{ - return m_bTimerStopped; -} - //-------------------------------------------------------------------------------------- // Limit the current thread to one processor (the current one). This ensures that timing code // runs on only one processor, and will not suffer any ill effects from power management. @@ -201,331 +199,138 @@ void CDXUTTimer::LimitThreadAffinityToCurrentProc() } -//-------------------------------------------------------------------------------------- -// Returns the string for the given D3DFORMAT. -//-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTD3DFormatToString( D3DFORMAT format, bool bWithPrefix ) -{ - WCHAR* pstr = NULL; - switch( format ) - { - case D3DFMT_UNKNOWN: - pstr = L"D3DFMT_UNKNOWN"; break; - case D3DFMT_R8G8B8: - pstr = L"D3DFMT_R8G8B8"; break; - case D3DFMT_A8R8G8B8: - pstr = L"D3DFMT_A8R8G8B8"; break; - case D3DFMT_X8R8G8B8: - pstr = L"D3DFMT_X8R8G8B8"; break; - case D3DFMT_R5G6B5: - pstr = L"D3DFMT_R5G6B5"; break; - case D3DFMT_X1R5G5B5: - pstr = L"D3DFMT_X1R5G5B5"; break; - case D3DFMT_A1R5G5B5: - pstr = L"D3DFMT_A1R5G5B5"; break; - case D3DFMT_A4R4G4B4: - pstr = L"D3DFMT_A4R4G4B4"; break; - case D3DFMT_R3G3B2: - pstr = L"D3DFMT_R3G3B2"; break; - case D3DFMT_A8: - pstr = L"D3DFMT_A8"; break; - case D3DFMT_A8R3G3B2: - pstr = L"D3DFMT_A8R3G3B2"; break; - case D3DFMT_X4R4G4B4: - pstr = L"D3DFMT_X4R4G4B4"; break; - case D3DFMT_A2B10G10R10: - pstr = L"D3DFMT_A2B10G10R10"; break; - case D3DFMT_A8B8G8R8: - pstr = L"D3DFMT_A8B8G8R8"; break; - case D3DFMT_X8B8G8R8: - pstr = L"D3DFMT_X8B8G8R8"; break; - case D3DFMT_G16R16: - pstr = L"D3DFMT_G16R16"; break; - case D3DFMT_A2R10G10B10: - pstr = L"D3DFMT_A2R10G10B10"; break; - case D3DFMT_A16B16G16R16: - pstr = L"D3DFMT_A16B16G16R16"; break; - case D3DFMT_A8P8: - pstr = L"D3DFMT_A8P8"; break; - case D3DFMT_P8: - pstr = L"D3DFMT_P8"; break; - case D3DFMT_L8: - pstr = L"D3DFMT_L8"; break; - case D3DFMT_A8L8: - pstr = L"D3DFMT_A8L8"; break; - case D3DFMT_A4L4: - pstr = L"D3DFMT_A4L4"; break; - case D3DFMT_V8U8: - pstr = L"D3DFMT_V8U8"; break; - case D3DFMT_L6V5U5: - pstr = L"D3DFMT_L6V5U5"; break; - case D3DFMT_X8L8V8U8: - pstr = L"D3DFMT_X8L8V8U8"; break; - case D3DFMT_Q8W8V8U8: - pstr = L"D3DFMT_Q8W8V8U8"; break; - case D3DFMT_V16U16: - pstr = L"D3DFMT_V16U16"; break; - case D3DFMT_A2W10V10U10: - pstr = L"D3DFMT_A2W10V10U10"; break; - case D3DFMT_UYVY: - pstr = L"D3DFMT_UYVY"; break; - case D3DFMT_YUY2: - pstr = L"D3DFMT_YUY2"; break; - case D3DFMT_DXT1: - pstr = L"D3DFMT_DXT1"; break; - case D3DFMT_DXT2: - pstr = L"D3DFMT_DXT2"; break; - case D3DFMT_DXT3: - pstr = L"D3DFMT_DXT3"; break; - case D3DFMT_DXT4: - pstr = L"D3DFMT_DXT4"; break; - case D3DFMT_DXT5: - pstr = L"D3DFMT_DXT5"; break; - case D3DFMT_D16_LOCKABLE: - pstr = L"D3DFMT_D16_LOCKABLE"; break; - case D3DFMT_D32: - pstr = L"D3DFMT_D32"; break; - case D3DFMT_D15S1: - pstr = L"D3DFMT_D15S1"; break; - case D3DFMT_D24S8: - pstr = L"D3DFMT_D24S8"; break; - case D3DFMT_D24X8: - pstr = L"D3DFMT_D24X8"; break; - case D3DFMT_D24X4S4: - pstr = L"D3DFMT_D24X4S4"; break; - case D3DFMT_D16: - pstr = L"D3DFMT_D16"; break; - case D3DFMT_L16: - pstr = L"D3DFMT_L16"; break; - case D3DFMT_VERTEXDATA: - pstr = L"D3DFMT_VERTEXDATA"; break; - case D3DFMT_INDEX16: - pstr = L"D3DFMT_INDEX16"; break; - case D3DFMT_INDEX32: - pstr = L"D3DFMT_INDEX32"; break; - case D3DFMT_Q16W16V16U16: - pstr = L"D3DFMT_Q16W16V16U16"; break; - case D3DFMT_MULTI2_ARGB8: - pstr = L"D3DFMT_MULTI2_ARGB8"; break; - case D3DFMT_R16F: - pstr = L"D3DFMT_R16F"; break; - case D3DFMT_G16R16F: - pstr = L"D3DFMT_G16R16F"; break; - case D3DFMT_A16B16G16R16F: - pstr = L"D3DFMT_A16B16G16R16F"; break; - case D3DFMT_R32F: - pstr = L"D3DFMT_R32F"; break; - case D3DFMT_G32R32F: - pstr = L"D3DFMT_G32R32F"; break; - case D3DFMT_A32B32G32R32F: - pstr = L"D3DFMT_A32B32G32R32F"; break; - case D3DFMT_CxV8U8: - pstr = L"D3DFMT_CxV8U8"; break; - default: - pstr = L"Unknown format"; break; - } - if( bWithPrefix || wcsstr( pstr, L"D3DFMT_" ) == NULL ) - return pstr; - else - return pstr + lstrlen( L"D3DFMT_" ); -} - - //-------------------------------------------------------------------------------------- // Returns the string for the given DXGI_FORMAT. //-------------------------------------------------------------------------------------- +#define DXUTDXGIFMTSTR( a ) case a: pstr = L#a; break; + +_Use_decl_annotations_ LPCWSTR WINAPI DXUTDXGIFormatToString( DXGI_FORMAT format, bool bWithPrefix ) { - WCHAR* pstr = NULL; + const WCHAR* pstr = nullptr; switch( format ) { - case DXGI_FORMAT_R32G32B32A32_TYPELESS: - pstr = L"DXGI_FORMAT_R32G32B32A32_TYPELESS"; break; - case DXGI_FORMAT_R32G32B32A32_FLOAT: - pstr = L"DXGI_FORMAT_R32G32B32A32_FLOAT"; break; - case DXGI_FORMAT_R32G32B32A32_UINT: - pstr = L"DXGI_FORMAT_R32G32B32A32_UINT"; break; - case DXGI_FORMAT_R32G32B32A32_SINT: - pstr = L"DXGI_FORMAT_R32G32B32A32_SINT"; break; - case DXGI_FORMAT_R32G32B32_TYPELESS: - pstr = L"DXGI_FORMAT_R32G32B32_TYPELESS"; break; - case DXGI_FORMAT_R32G32B32_FLOAT: - pstr = L"DXGI_FORMAT_R32G32B32_FLOAT"; break; - case DXGI_FORMAT_R32G32B32_UINT: - pstr = L"DXGI_FORMAT_R32G32B32_UINT"; break; - case DXGI_FORMAT_R32G32B32_SINT: - pstr = L"DXGI_FORMAT_R32G32B32_SINT"; break; - case DXGI_FORMAT_R16G16B16A16_TYPELESS: - pstr = L"DXGI_FORMAT_R16G16B16A16_TYPELESS"; break; - case DXGI_FORMAT_R16G16B16A16_FLOAT: - pstr = L"DXGI_FORMAT_R16G16B16A16_FLOAT"; break; - case DXGI_FORMAT_R16G16B16A16_UNORM: - pstr = L"DXGI_FORMAT_R16G16B16A16_UNORM"; break; - case DXGI_FORMAT_R16G16B16A16_UINT: - pstr = L"DXGI_FORMAT_R16G16B16A16_UINT"; break; - case DXGI_FORMAT_R16G16B16A16_SNORM: - pstr = L"DXGI_FORMAT_R16G16B16A16_SNORM"; break; - case DXGI_FORMAT_R16G16B16A16_SINT: - pstr = L"DXGI_FORMAT_R16G16B16A16_SINT"; break; - case DXGI_FORMAT_R32G32_TYPELESS: - pstr = L"DXGI_FORMAT_R32G32_TYPELESS"; break; - case DXGI_FORMAT_R32G32_FLOAT: - pstr = L"DXGI_FORMAT_R32G32_FLOAT"; break; - case DXGI_FORMAT_R32G32_UINT: - pstr = L"DXGI_FORMAT_R32G32_UINT"; break; - case DXGI_FORMAT_R32G32_SINT: - pstr = L"DXGI_FORMAT_R32G32_SINT"; break; - case DXGI_FORMAT_R32G8X24_TYPELESS: - pstr = L"DXGI_FORMAT_R32G8X24_TYPELESS"; break; - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: - pstr = L"DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; break; - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: - pstr = L"DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; break; - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: - pstr = L"DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; break; - case DXGI_FORMAT_R10G10B10A2_TYPELESS: - pstr = L"DXGI_FORMAT_R10G10B10A2_TYPELESS"; break; - case DXGI_FORMAT_R10G10B10A2_UNORM: - pstr = L"DXGI_FORMAT_R10G10B10A2_UNORM"; break; - case DXGI_FORMAT_R10G10B10A2_UINT: - pstr = L"DXGI_FORMAT_R10G10B10A2_UINT"; break; - case DXGI_FORMAT_R11G11B10_FLOAT: - pstr = L"DXGI_FORMAT_R11G11B10_FLOAT"; break; - case DXGI_FORMAT_R8G8B8A8_TYPELESS: - pstr = L"DXGI_FORMAT_R8G8B8A8_TYPELESS"; break; - case DXGI_FORMAT_R8G8B8A8_UNORM: - pstr = L"DXGI_FORMAT_R8G8B8A8_UNORM"; break; - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - pstr = L"DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; break; - case DXGI_FORMAT_R8G8B8A8_UINT: - pstr = L"DXGI_FORMAT_R8G8B8A8_UINT"; break; - case DXGI_FORMAT_R8G8B8A8_SNORM: - pstr = L"DXGI_FORMAT_R8G8B8A8_SNORM"; break; - case DXGI_FORMAT_R8G8B8A8_SINT: - pstr = L"DXGI_FORMAT_R8G8B8A8_SINT"; break; - case DXGI_FORMAT_R16G16_TYPELESS: - pstr = L"DXGI_FORMAT_R16G16_TYPELESS"; break; - case DXGI_FORMAT_R16G16_FLOAT: - pstr = L"DXGI_FORMAT_R16G16_FLOAT"; break; - case DXGI_FORMAT_R16G16_UNORM: - pstr = L"DXGI_FORMAT_R16G16_UNORM"; break; - case DXGI_FORMAT_R16G16_UINT: - pstr = L"DXGI_FORMAT_R16G16_UINT"; break; - case DXGI_FORMAT_R16G16_SNORM: - pstr = L"DXGI_FORMAT_R16G16_SNORM"; break; - case DXGI_FORMAT_R16G16_SINT: - pstr = L"DXGI_FORMAT_R16G16_SINT"; break; - case DXGI_FORMAT_R32_TYPELESS: - pstr = L"DXGI_FORMAT_R32_TYPELESS"; break; - case DXGI_FORMAT_D32_FLOAT: - pstr = L"DXGI_FORMAT_D32_FLOAT"; break; - case DXGI_FORMAT_R32_FLOAT: - pstr = L"DXGI_FORMAT_R32_FLOAT"; break; - case DXGI_FORMAT_R32_UINT: - pstr = L"DXGI_FORMAT_R32_UINT"; break; - case DXGI_FORMAT_R32_SINT: - pstr = L"DXGI_FORMAT_R32_SINT"; break; - case DXGI_FORMAT_R24G8_TYPELESS: - pstr = L"DXGI_FORMAT_R24G8_TYPELESS"; break; - case DXGI_FORMAT_D24_UNORM_S8_UINT: - pstr = L"DXGI_FORMAT_D24_UNORM_S8_UINT"; break; - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: - pstr = L"DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; break; - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: - pstr = L"DXGI_FORMAT_X24_TYPELESS_G8_UINT"; break; - case DXGI_FORMAT_R8G8_TYPELESS: - pstr = L"DXGI_FORMAT_R8G8_TYPELESS"; break; - case DXGI_FORMAT_R8G8_UNORM: - pstr = L"DXGI_FORMAT_R8G8_UNORM"; break; - case DXGI_FORMAT_R8G8_UINT: - pstr = L"DXGI_FORMAT_R8G8_UINT"; break; - case DXGI_FORMAT_R8G8_SNORM: - pstr = L"DXGI_FORMAT_R8G8_SNORM"; break; - case DXGI_FORMAT_R8G8_SINT: - pstr = L"DXGI_FORMAT_R8G8_SINT"; break; - case DXGI_FORMAT_R16_TYPELESS: - pstr = L"DXGI_FORMAT_R16_TYPELESS"; break; - case DXGI_FORMAT_R16_FLOAT: - pstr = L"DXGI_FORMAT_R16_FLOAT"; break; - case DXGI_FORMAT_D16_UNORM: - pstr = L"DXGI_FORMAT_D16_UNORM"; break; - case DXGI_FORMAT_R16_UNORM: - pstr = L"DXGI_FORMAT_R16_UNORM"; break; - case DXGI_FORMAT_R16_UINT: - pstr = L"DXGI_FORMAT_R16_UINT"; break; - case DXGI_FORMAT_R16_SNORM: - pstr = L"DXGI_FORMAT_R16_SNORM"; break; - case DXGI_FORMAT_R16_SINT: - pstr = L"DXGI_FORMAT_R16_SINT"; break; - case DXGI_FORMAT_R8_TYPELESS: - pstr = L"DXGI_FORMAT_R8_TYPELESS"; break; - case DXGI_FORMAT_R8_UNORM: - pstr = L"DXGI_FORMAT_R8_UNORM"; break; - case DXGI_FORMAT_R8_UINT: - pstr = L"DXGI_FORMAT_R8_UINT"; break; - case DXGI_FORMAT_R8_SNORM: - pstr = L"DXGI_FORMAT_R8_SNORM"; break; - case DXGI_FORMAT_R8_SINT: - pstr = L"DXGI_FORMAT_R8_SINT"; break; - case DXGI_FORMAT_A8_UNORM: - pstr = L"DXGI_FORMAT_A8_UNORM"; break; - case DXGI_FORMAT_R1_UNORM: - pstr = L"DXGI_FORMAT_R1_UNORM"; break; - case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: - pstr = L"DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; break; - case DXGI_FORMAT_R8G8_B8G8_UNORM: - pstr = L"DXGI_FORMAT_R8G8_B8G8_UNORM"; break; - case DXGI_FORMAT_G8R8_G8B8_UNORM: - pstr = L"DXGI_FORMAT_G8R8_G8B8_UNORM"; break; - case DXGI_FORMAT_BC1_TYPELESS: - pstr = L"DXGI_FORMAT_BC1_TYPELESS"; break; - case DXGI_FORMAT_BC1_UNORM: - pstr = L"DXGI_FORMAT_BC1_UNORM"; break; - case DXGI_FORMAT_BC1_UNORM_SRGB: - pstr = L"DXGI_FORMAT_BC1_UNORM_SRGB"; break; - case DXGI_FORMAT_BC2_TYPELESS: - pstr = L"DXGI_FORMAT_BC2_TYPELESS"; break; - case DXGI_FORMAT_BC2_UNORM: - pstr = L"DXGI_FORMAT_BC2_UNORM"; break; - case DXGI_FORMAT_BC2_UNORM_SRGB: - pstr = L"DXGI_FORMAT_BC2_UNORM_SRGB"; break; - case DXGI_FORMAT_BC3_TYPELESS: - pstr = L"DXGI_FORMAT_BC3_TYPELESS"; break; - case DXGI_FORMAT_BC3_UNORM: - pstr = L"DXGI_FORMAT_BC3_UNORM"; break; - case DXGI_FORMAT_BC3_UNORM_SRGB: - pstr = L"DXGI_FORMAT_BC3_UNORM_SRGB"; break; - case DXGI_FORMAT_BC4_TYPELESS: - pstr = L"DXGI_FORMAT_BC4_TYPELESS"; break; - case DXGI_FORMAT_BC4_UNORM: - pstr = L"DXGI_FORMAT_BC4_UNORM"; break; - case DXGI_FORMAT_BC4_SNORM: - pstr = L"DXGI_FORMAT_BC4_SNORM"; break; - case DXGI_FORMAT_BC5_TYPELESS: - pstr = L"DXGI_FORMAT_BC5_TYPELESS"; break; - case DXGI_FORMAT_BC5_UNORM: - pstr = L"DXGI_FORMAT_BC5_UNORM"; break; - case DXGI_FORMAT_BC5_SNORM: - pstr = L"DXGI_FORMAT_BC5_SNORM"; break; - case DXGI_FORMAT_B5G6R5_UNORM: - pstr = L"DXGI_FORMAT_B5G6R5_UNORM"; break; - case DXGI_FORMAT_B5G5R5A1_UNORM: - pstr = L"DXGI_FORMAT_B5G5R5A1_UNORM"; break; - case DXGI_FORMAT_B8G8R8A8_UNORM: - pstr = L"DXGI_FORMAT_B8G8R8A8_UNORM"; break; + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G8X24_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_D32_FLOAT_S8X24_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10A2_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10A2_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10A2_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R11G11B10_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_D32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R24G8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_D24_UNORM_S8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R24_UNORM_X8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_X24_TYPELESS_G8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_D16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_A8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R1_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R9G9B9E5_SHAREDEXP) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_B8G8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_G8R8_G8B8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC1_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC1_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC1_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC2_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC2_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC2_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC3_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC3_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC3_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC4_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC4_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC4_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC5_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC5_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC5_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B5G6R5_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B5G5R5A1_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8A8_UNORM) + + // DXGI 1.1 + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8X8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8A8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8X8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC6H_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC6H_UF16) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC6H_SF16) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC7_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC7_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC7_UNORM_SRGB) + + // DXGI 1.2 + DXUTDXGIFMTSTR(DXGI_FORMAT_B4G4R4A4_UNORM) + default: pstr = L"Unknown format"; break; } - if( bWithPrefix || wcsstr( pstr, L"DXGI_FORMAT_" ) == NULL ) + if( bWithPrefix || !wcsstr( pstr, L"DXGI_FORMAT_" ) ) return pstr; else - return pstr + lstrlen( L"DXGI_FORMAT_" ); + return pstr + wcslen( L"DXGI_FORMAT_" ); } +#undef DXUTDXGIFMTSTR + //-------------------------------------------------------------------------------------- // Outputs to the debug stream a formatted Unicode string with a variable-argument list. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ VOID WINAPI DXUTOutputDebugStringW( LPCWSTR strMsg, ... ) { #if defined(DEBUG) || defined(_DEBUG) @@ -547,6 +352,7 @@ VOID WINAPI DXUTOutputDebugStringW( LPCWSTR strMsg, ... ) //-------------------------------------------------------------------------------------- // Outputs to the debug stream a formatted MBCS string with a variable-argument list. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ VOID WINAPI DXUTOutputDebugStringA( LPCSTR strMsg, ... ) { #if defined(DEBUG) || defined(_DEBUG) @@ -566,203 +372,190 @@ VOID WINAPI DXUTOutputDebugStringA( LPCSTR strMsg, ... ) //-------------------------------------------------------------------------------------- -// Direct3D9 dynamic linking support -- calls top-level D3D9 APIs with graceful +// Direct3D dynamic linking support -- calls top-level D3D APIs with graceful // failure if APIs are not present. //-------------------------------------------------------------------------------------- // Function prototypes -typedef IDirect3D9* (WINAPI * LPDIRECT3DCREATE9) (UINT); -typedef INT (WINAPI * LPD3DPERF_BEGINEVENT)(D3DCOLOR, LPCWSTR); +typedef INT (WINAPI * LPD3DPERF_BEGINEVENT)(DWORD, LPCWSTR); typedef INT (WINAPI * LPD3DPERF_ENDEVENT)(void); -typedef VOID (WINAPI * LPD3DPERF_SETMARKER)(D3DCOLOR, LPCWSTR); -typedef VOID (WINAPI * LPD3DPERF_SETREGION)(D3DCOLOR, LPCWSTR); +typedef VOID (WINAPI * LPD3DPERF_SETMARKER)(DWORD, LPCWSTR); +typedef VOID (WINAPI * LPD3DPERF_SETREGION)(DWORD, LPCWSTR); typedef BOOL (WINAPI * LPD3DPERF_QUERYREPEATFRAME)(void); typedef VOID (WINAPI * LPD3DPERF_SETOPTIONS)( DWORD dwOptions ); -typedef DWORD (WINAPI * LPD3DPERF_GETSTATUS)( void ); +typedef DWORD (WINAPI * LPD3DPERF_GETSTATUS)(); typedef HRESULT (WINAPI * LPCREATEDXGIFACTORY)(REFIID, void ** ); -typedef HRESULT (WINAPI * LPD3D11CREATEDEVICE)( IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT32, D3D_FEATURE_LEVEL*, UINT, UINT32, ID3D11Device**, D3D_FEATURE_LEVEL*, ID3D11DeviceContext** ); +typedef HRESULT (WINAPI * LPDXGIGETDEBUGINTERFACE)(REFIID, void ** ); // Module and function pointers -static HMODULE s_hModD3D9 = NULL; -static LPDIRECT3DCREATE9 s_DynamicDirect3DCreate9 = NULL; -static LPD3DPERF_BEGINEVENT s_DynamicD3DPERF_BeginEvent = NULL; -static LPD3DPERF_ENDEVENT s_DynamicD3DPERF_EndEvent = NULL; -static LPD3DPERF_SETMARKER s_DynamicD3DPERF_SetMarker = NULL; -static LPD3DPERF_SETREGION s_DynamicD3DPERF_SetRegion = NULL; -static LPD3DPERF_QUERYREPEATFRAME s_DynamicD3DPERF_QueryRepeatFrame = NULL; -static LPD3DPERF_SETOPTIONS s_DynamicD3DPERF_SetOptions = NULL; -static LPD3DPERF_GETSTATUS s_DynamicD3DPERF_GetStatus = NULL; -static HMODULE s_hModDXGI = NULL; -static LPCREATEDXGIFACTORY s_DynamicCreateDXGIFactory = NULL; -static HMODULE s_hModD3D11 = NULL; -static LPD3D11CREATEDEVICE s_DynamicD3D11CreateDevice = NULL; +static HMODULE s_hModD3D9 = nullptr; +static LPD3DPERF_BEGINEVENT s_DynamicD3DPERF_BeginEvent = nullptr; +static LPD3DPERF_ENDEVENT s_DynamicD3DPERF_EndEvent = nullptr; +static LPD3DPERF_SETMARKER s_DynamicD3DPERF_SetMarker = nullptr; +static LPD3DPERF_SETREGION s_DynamicD3DPERF_SetRegion = nullptr; +static LPD3DPERF_QUERYREPEATFRAME s_DynamicD3DPERF_QueryRepeatFrame = nullptr; +static LPD3DPERF_SETOPTIONS s_DynamicD3DPERF_SetOptions = nullptr; +static LPD3DPERF_GETSTATUS s_DynamicD3DPERF_GetStatus = nullptr; +static HMODULE s_hModDXGI = nullptr; +static HMODULE s_hModDXGIDebug = nullptr; +static LPCREATEDXGIFACTORY s_DynamicCreateDXGIFactory = nullptr; +static LPDXGIGETDEBUGINTERFACE s_DynamicDXGIGetDebugInterface = nullptr; +static HMODULE s_hModD3D11 = nullptr; +static PFN_D3D11_CREATE_DEVICE s_DynamicD3D11CreateDevice = nullptr; // Ensure function pointers are initialized -static bool DXUT_EnsureD3D9APIs( void ) +static bool DXUT_EnsureD3D9APIs() { // If the module is non-NULL, this function has already been called. Note // that this doesn't guarantee that all ProcAddresses were found. - if( s_hModD3D9 != NULL ) + if( s_hModD3D9 ) return true; - // This may fail if Direct3D 9 isn't installed - s_hModD3D9 = LoadLibrary( L"d3d9.dll" ); - if( s_hModD3D9 != NULL ) + // This could fail in theory, but not on any modern version of Windows + s_hModD3D9 = LoadLibraryEx( L"d3d9.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); + if( s_hModD3D9 ) { - s_DynamicDirect3DCreate9 = (LPDIRECT3DCREATE9)GetProcAddress( s_hModD3D9, "Direct3DCreate9" ); - s_DynamicD3DPERF_BeginEvent = (LPD3DPERF_BEGINEVENT)GetProcAddress( s_hModD3D9, "D3DPERF_BeginEvent" ); - s_DynamicD3DPERF_EndEvent = (LPD3DPERF_ENDEVENT)GetProcAddress( s_hModD3D9, "D3DPERF_EndEvent" ); - s_DynamicD3DPERF_SetMarker = (LPD3DPERF_SETMARKER)GetProcAddress( s_hModD3D9, "D3DPERF_SetMarker" ); - s_DynamicD3DPERF_SetRegion = (LPD3DPERF_SETREGION)GetProcAddress( s_hModD3D9, "D3DPERF_SetRegion" ); - s_DynamicD3DPERF_QueryRepeatFrame = (LPD3DPERF_QUERYREPEATFRAME)GetProcAddress( s_hModD3D9, "D3DPERF_QueryRepeatFrame" ); - s_DynamicD3DPERF_SetOptions = (LPD3DPERF_SETOPTIONS)GetProcAddress( s_hModD3D9, "D3DPERF_SetOptions" ); - s_DynamicD3DPERF_GetStatus = (LPD3DPERF_GETSTATUS)GetProcAddress( s_hModD3D9, "D3DPERF_GetStatus" ); + // TODO - Use 11.1 perf APIs instead? + s_DynamicD3DPERF_BeginEvent = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D9, "D3DPERF_BeginEvent" ) ) ); + s_DynamicD3DPERF_EndEvent = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D9, "D3DPERF_EndEvent" ) ) ); + s_DynamicD3DPERF_SetMarker = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D9, "D3DPERF_SetMarker" ) ) ); + s_DynamicD3DPERF_SetRegion = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D9, "D3DPERF_SetRegion" ) ) ); + s_DynamicD3DPERF_QueryRepeatFrame = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D9, "D3DPERF_QueryRepeatFrame" ) ) ); + s_DynamicD3DPERF_SetOptions = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D9, "D3DPERF_SetOptions" ) ) ); + s_DynamicD3DPERF_GetStatus = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D9, "D3DPERF_GetStatus" ) ) ); } - return s_hModD3D9 != NULL; + return s_hModD3D9 != nullptr; } -bool DXUT_EnsureD3D11APIs( void ) +bool DXUT_EnsureD3D11APIs() { // If both modules are non-NULL, this function has already been called. Note // that this doesn't guarantee that all ProcAddresses were found. - if( s_hModD3D11 != NULL && s_hModDXGI != NULL ) + if( s_hModD3D11 && s_hModDXGI ) return true; // This may fail if Direct3D 11 isn't installed - s_hModD3D11 = LoadLibrary( L"d3d11.dll" ); - if( s_hModD3D11 != NULL ) + s_hModD3D11 = LoadLibraryEx( L"d3d11.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); + if( s_hModD3D11 ) { - s_DynamicD3D11CreateDevice = ( LPD3D11CREATEDEVICE )GetProcAddress( s_hModD3D11, "D3D11CreateDevice" ); + s_DynamicD3D11CreateDevice = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModD3D11, "D3D11CreateDevice" ) ) ); } if( !s_DynamicCreateDXGIFactory ) { - s_hModDXGI = LoadLibrary( L"dxgi.dll" ); + s_hModDXGI = LoadLibraryEx( L"dxgi.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( s_hModDXGI ) { - s_DynamicCreateDXGIFactory = ( LPCREATEDXGIFACTORY )GetProcAddress( s_hModDXGI, "CreateDXGIFactory1" ); + s_DynamicCreateDXGIFactory = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModDXGI, "CreateDXGIFactory1" ) ) ); } - return ( s_hModDXGI != NULL ) && ( s_hModD3D11 != NULL ); - } + if ( !s_DynamicDXGIGetDebugInterface ) + { + s_hModDXGIDebug = LoadLibraryEx( L"dxgidebug.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); + if ( s_hModDXGIDebug ) + { + s_DynamicDXGIGetDebugInterface = reinterpret_cast( reinterpret_cast( GetProcAddress( s_hModDXGIDebug, "DXGIGetDebugInterface" ) ) ); + } + } - return ( s_hModD3D11 != NULL ); -} + return ( s_hModDXGI ) && ( s_hModD3D11 ); + } -IDirect3D9* WINAPI DXUT_Dynamic_Direct3DCreate9( UINT SDKVersion ) -{ - if( DXUT_EnsureD3D9APIs() && s_DynamicDirect3DCreate9 != NULL ) - return s_DynamicDirect3DCreate9( SDKVersion ); - else - return NULL; + return s_hModD3D11 != nullptr; } -int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( D3DCOLOR col, LPCWSTR wszName ) +int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( _In_ DWORD col, _In_z_ LPCWSTR wszName ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_BeginEvent != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_BeginEvent ) return s_DynamicD3DPERF_BeginEvent( col, wszName ); else return -1; } -int WINAPI DXUT_Dynamic_D3DPERF_EndEvent( void ) +int WINAPI DXUT_Dynamic_D3DPERF_EndEvent() { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_EndEvent != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_EndEvent ) return s_DynamicD3DPERF_EndEvent(); else return -1; } -void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( D3DCOLOR col, LPCWSTR wszName ) +void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( _In_ DWORD col, _In_z_ LPCWSTR wszName ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetMarker != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetMarker ) s_DynamicD3DPERF_SetMarker( col, wszName ); } -void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( D3DCOLOR col, LPCWSTR wszName ) +void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( _In_ DWORD col, _In_z_ LPCWSTR wszName ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetRegion != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetRegion ) s_DynamicD3DPERF_SetRegion( col, wszName ); } -BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame( void ) +BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame() { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_QueryRepeatFrame != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_QueryRepeatFrame ) return s_DynamicD3DPERF_QueryRepeatFrame(); else return FALSE; } -void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( DWORD dwOptions ) +void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( _In_ DWORD dwOptions ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetOptions != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetOptions ) s_DynamicD3DPERF_SetOptions( dwOptions ); } -DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus( void ) +DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus() { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_GetStatus != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_GetStatus ) return s_DynamicD3DPERF_GetStatus(); else return 0; } +_Use_decl_annotations_ HRESULT WINAPI DXUT_Dynamic_CreateDXGIFactory1( REFIID rInterface, void** ppOut ) { - if( DXUT_EnsureD3D11APIs() && s_DynamicCreateDXGIFactory != NULL ) + if( DXUT_EnsureD3D11APIs() && s_DynamicCreateDXGIFactory ) return s_DynamicCreateDXGIFactory( rInterface, ppOut ); else - return DXUTERR_NODIRECT3D11; + return DXUTERR_NODIRECT3D; } +_Use_decl_annotations_ +HRESULT WINAPI DXUT_Dynamic_DXGIGetDebugInterface( REFIID rInterface, void** ppOut ) +{ + if( DXUT_EnsureD3D11APIs() && s_DynamicDXGIGetDebugInterface ) + return s_DynamicDXGIGetDebugInterface( rInterface, ppOut ); + else + return E_NOTIMPL; +} - +_Use_decl_annotations_ HRESULT WINAPI DXUT_Dynamic_D3D11CreateDevice( IDXGIAdapter* pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT32 Flags, - D3D_FEATURE_LEVEL* pFeatureLevels, + const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT32 SDKVersion, ID3D11Device** ppDevice, D3D_FEATURE_LEVEL* pFeatureLevel, ID3D11DeviceContext** ppImmediateContext ) { - if( DXUT_EnsureD3D11APIs() && s_DynamicD3D11CreateDevice != NULL ) + if( DXUT_EnsureD3D11APIs() && s_DynamicD3D11CreateDevice ) return s_DynamicD3D11CreateDevice( pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext ); else - return DXUTERR_NODIRECT3D11; -} - -//-------------------------------------------------------------------------------------- -// Trace a string description of a decl -//-------------------------------------------------------------------------------------- -void WINAPI DXUTTraceDecl( D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE] ) -{ - int iDecl = 0; - for( iDecl = 0; iDecl < MAX_FVF_DECL_SIZE; iDecl++ ) - { - if( decl[iDecl].Stream == 0xFF ) - break; - - DXUTOutputDebugString( L"decl[%d]=Stream:%d, Offset:%d, %s, %s, %s, UsageIndex:%d\n", iDecl, - decl[iDecl].Stream, - decl[iDecl].Offset, - DXUTTraceD3DDECLTYPEtoString( decl[iDecl].Type ), - DXUTTraceD3DDECLMETHODtoString( decl[iDecl].Method ), - DXUTTraceD3DDECLUSAGEtoString( decl[iDecl].Usage ), - decl[iDecl].UsageIndex ); - } - - DXUTOutputDebugString( L"decl[%d]=D3DDECL_END\n", iDecl ); + return DXUTERR_NODIRECT3D; } #define TRACE_ID(iD) case iD: return L#iD; //-------------------------------------------------------------------------------------- -WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ) +const WCHAR* WINAPI DXUTTraceWindowsMessage( _In_ UINT uMsg ) { switch( uMsg ) { @@ -986,113 +779,6 @@ WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ) } -//-------------------------------------------------------------------------------------- -WCHAR* WINAPI DXUTTraceD3DDECLTYPEtoString( BYTE t ) -{ - switch( t ) - { - case D3DDECLTYPE_FLOAT1: - return L"D3DDECLTYPE_FLOAT1"; - case D3DDECLTYPE_FLOAT2: - return L"D3DDECLTYPE_FLOAT2"; - case D3DDECLTYPE_FLOAT3: - return L"D3DDECLTYPE_FLOAT3"; - case D3DDECLTYPE_FLOAT4: - return L"D3DDECLTYPE_FLOAT4"; - case D3DDECLTYPE_D3DCOLOR: - return L"D3DDECLTYPE_D3DCOLOR"; - case D3DDECLTYPE_UBYTE4: - return L"D3DDECLTYPE_UBYTE4"; - case D3DDECLTYPE_SHORT2: - return L"D3DDECLTYPE_SHORT2"; - case D3DDECLTYPE_SHORT4: - return L"D3DDECLTYPE_SHORT4"; - case D3DDECLTYPE_UBYTE4N: - return L"D3DDECLTYPE_UBYTE4N"; - case D3DDECLTYPE_SHORT2N: - return L"D3DDECLTYPE_SHORT2N"; - case D3DDECLTYPE_SHORT4N: - return L"D3DDECLTYPE_SHORT4N"; - case D3DDECLTYPE_USHORT2N: - return L"D3DDECLTYPE_USHORT2N"; - case D3DDECLTYPE_USHORT4N: - return L"D3DDECLTYPE_USHORT4N"; - case D3DDECLTYPE_UDEC3: - return L"D3DDECLTYPE_UDEC3"; - case D3DDECLTYPE_DEC3N: - return L"D3DDECLTYPE_DEC3N"; - case D3DDECLTYPE_FLOAT16_2: - return L"D3DDECLTYPE_FLOAT16_2"; - case D3DDECLTYPE_FLOAT16_4: - return L"D3DDECLTYPE_FLOAT16_4"; - case D3DDECLTYPE_UNUSED: - return L"D3DDECLTYPE_UNUSED"; - default: - return L"D3DDECLTYPE Unknown"; - } -} - -WCHAR* WINAPI DXUTTraceD3DDECLMETHODtoString( BYTE m ) -{ - switch( m ) - { - case D3DDECLMETHOD_DEFAULT: - return L"D3DDECLMETHOD_DEFAULT"; - case D3DDECLMETHOD_PARTIALU: - return L"D3DDECLMETHOD_PARTIALU"; - case D3DDECLMETHOD_PARTIALV: - return L"D3DDECLMETHOD_PARTIALV"; - case D3DDECLMETHOD_CROSSUV: - return L"D3DDECLMETHOD_CROSSUV"; - case D3DDECLMETHOD_UV: - return L"D3DDECLMETHOD_UV"; - case D3DDECLMETHOD_LOOKUP: - return L"D3DDECLMETHOD_LOOKUP"; - case D3DDECLMETHOD_LOOKUPPRESAMPLED: - return L"D3DDECLMETHOD_LOOKUPPRESAMPLED"; - default: - return L"D3DDECLMETHOD Unknown"; - } -} - -WCHAR* WINAPI DXUTTraceD3DDECLUSAGEtoString( BYTE u ) -{ - switch( u ) - { - case D3DDECLUSAGE_POSITION: - return L"D3DDECLUSAGE_POSITION"; - case D3DDECLUSAGE_BLENDWEIGHT: - return L"D3DDECLUSAGE_BLENDWEIGHT"; - case D3DDECLUSAGE_BLENDINDICES: - return L"D3DDECLUSAGE_BLENDINDICES"; - case D3DDECLUSAGE_NORMAL: - return L"D3DDECLUSAGE_NORMAL"; - case D3DDECLUSAGE_PSIZE: - return L"D3DDECLUSAGE_PSIZE"; - case D3DDECLUSAGE_TEXCOORD: - return L"D3DDECLUSAGE_TEXCOORD"; - case D3DDECLUSAGE_TANGENT: - return L"D3DDECLUSAGE_TANGENT"; - case D3DDECLUSAGE_BINORMAL: - return L"D3DDECLUSAGE_BINORMAL"; - case D3DDECLUSAGE_TESSFACTOR: - return L"D3DDECLUSAGE_TESSFACTOR"; - case D3DDECLUSAGE_POSITIONT: - return L"D3DDECLUSAGE_POSITIONT"; - case D3DDECLUSAGE_COLOR: - return L"D3DDECLUSAGE_COLOR"; - case D3DDECLUSAGE_FOG: - return L"D3DDECLUSAGE_FOG"; - case D3DDECLUSAGE_DEPTH: - return L"D3DDECLUSAGE_DEPTH"; - case D3DDECLUSAGE_SAMPLE: - return L"D3DDECLUSAGE_SAMPLE"; - default: - return L"D3DDECLUSAGE Unknown"; - } -} - - //-------------------------------------------------------------------------------------- // Multimon API handling for OSes with or without multimon API support //-------------------------------------------------------------------------------------- @@ -1101,24 +787,19 @@ typedef HMONITOR ( WINAPI* LPMONITORFROMWINDOW )( HWND, DWORD ); typedef BOOL ( WINAPI* LPGETMONITORINFO )( HMONITOR, LPMONITORINFO ); typedef HMONITOR ( WINAPI* LPMONITORFROMRECT )( LPCRECT lprcScreenCoords, DWORD dwFlags ); +#pragma warning( suppress : 6101 ) +_Use_decl_annotations_ BOOL WINAPI DXUTGetMonitorInfo( HMONITOR hMonitor, LPMONITORINFO lpMonitorInfo ) { static bool s_bInited = false; - static LPGETMONITORINFO s_pFnGetMonitorInfo = NULL; + static LPGETMONITORINFO s_pFnGetMonitorInfo = nullptr; if( !s_bInited ) { s_bInited = true; HMODULE hUser32 = GetModuleHandle( L"USER32" ); if( hUser32 ) { - OSVERSIONINFOA osvi = - { - 0 - }; osvi.dwOSVersionInfoSize = sizeof( osvi ); GetVersionExA( ( OSVERSIONINFOA* )&osvi ); - bool bNT = ( VER_PLATFORM_WIN32_NT == osvi.dwPlatformId ); - s_pFnGetMonitorInfo = ( LPGETMONITORINFO )( bNT ? GetProcAddress( hUser32, - "GetMonitorInfoW" ) : - GetProcAddress( hUser32, "GetMonitorInfoA" ) ); + s_pFnGetMonitorInfo = reinterpret_cast( reinterpret_cast( GetProcAddress( hUser32, "GetMonitorInfoW" ) ) ); } } @@ -1141,16 +822,17 @@ BOOL WINAPI DXUTGetMonitorInfo( HMONITOR hMonitor, LPMONITORINFO lpMonitorInfo ) } +_Use_decl_annotations_ HMONITOR WINAPI DXUTMonitorFromWindow( HWND hWnd, DWORD dwFlags ) { static bool s_bInited = false; - static LPMONITORFROMWINDOW s_pFnGetMonitorFromWindow = NULL; + static LPMONITORFROMWINDOW s_pFnGetMonitorFromWindow = nullptr; if( !s_bInited ) { s_bInited = true; HMODULE hUser32 = GetModuleHandle( L"USER32" ); - if( hUser32 ) s_pFnGetMonitorFromWindow = ( LPMONITORFROMWINDOW )GetProcAddress( hUser32, - "MonitorFromWindow" ); + if( hUser32 ) s_pFnGetMonitorFromWindow = reinterpret_cast( reinterpret_cast( GetProcAddress( hUser32, + "MonitorFromWindow" ) ) ); } if( s_pFnGetMonitorFromWindow ) @@ -1160,15 +842,16 @@ HMONITOR WINAPI DXUTMonitorFromWindow( HWND hWnd, DWORD dwFlags ) } +_Use_decl_annotations_ HMONITOR WINAPI DXUTMonitorFromRect( LPCRECT lprcScreenCoords, DWORD dwFlags ) { static bool s_bInited = false; - static LPMONITORFROMRECT s_pFnGetMonitorFromRect = NULL; + static LPMONITORFROMRECT s_pFnGetMonitorFromRect = nullptr; if( !s_bInited ) { s_bInited = true; HMODULE hUser32 = GetModuleHandle( L"USER32" ); - if( hUser32 ) s_pFnGetMonitorFromRect = ( LPMONITORFROMRECT )GetProcAddress( hUser32, "MonitorFromRect" ); + if( hUser32 ) s_pFnGetMonitorFromRect = reinterpret_cast( reinterpret_cast( GetProcAddress( hUser32, "MonitorFromRect" ) ) ); } if( s_pFnGetMonitorFromRect ) @@ -1182,37 +865,26 @@ HMONITOR WINAPI DXUTMonitorFromRect( LPCRECT lprcScreenCoords, DWORD dwFlags ) // Get the desktop resolution of an adapter. This isn't the same as the current resolution // from GetAdapterDisplayMode since the device might be fullscreen //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI DXUTGetDesktopResolution( UINT AdapterOrdinal, UINT* pWidth, UINT* pHeight ) { - DXUTDeviceSettings DeviceSettings = DXUTGetDeviceSettings(); + auto DeviceSettings = DXUTGetDeviceSettings(); - WCHAR strDeviceName[256] = {0}; - DEVMODE devMode; - ZeroMemory( &devMode, sizeof( DEVMODE ) ); + WCHAR strDeviceName[256] = {}; + DEVMODE devMode = {}; devMode.dmSize = sizeof( DEVMODE ); - if( DeviceSettings.ver == DXUT_D3D9_DEVICE ) - { - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - assert( pd3dEnum != NULL ); - CD3D9EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( AdapterOrdinal ); - if( pAdapterInfo ) - { - MultiByteToWideChar( CP_ACP, 0, pAdapterInfo->AdapterIdentifier.DeviceName, -1, strDeviceName, 256 ); - strDeviceName[255] = 0; - } - } - else + + auto pd3dEnum = DXUTGetD3D11Enumeration(); + assert( pd3dEnum ); + _Analysis_assume_( pd3dEnum ); + auto pOutputInfo = pd3dEnum->GetOutputInfo( AdapterOrdinal, DeviceSettings.d3d11.Output ); + if( pOutputInfo ) { - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - assert( pd3dEnum != NULL ); - CD3D11EnumOutputInfo* pOutputInfo = pd3dEnum->GetOutputInfo( AdapterOrdinal, DeviceSettings.d3d11.Output ); - if( pOutputInfo ) - { - wcscpy_s( strDeviceName, 256, pOutputInfo->Desc.DeviceName ); - } + wcscpy_s( strDeviceName, 256, pOutputInfo->Desc.DeviceName ); } EnumDisplaySettings( strDeviceName, ENUM_REGISTRY_SETTINGS, &devMode ); + if( pWidth ) *pWidth = devMode.dmPelsWidth; if( pHeight ) @@ -1223,6 +895,7 @@ void WINAPI DXUTGetDesktopResolution( UINT AdapterOrdinal, UINT* pWidth, UINT* p //-------------------------------------------------------------------------------------- // Display error msg box to help debug //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, const WCHAR* strMsg, bool bPopMsgBox ) { @@ -1230,267 +903,19 @@ HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, if( bPopMsgBox && bShowMsgBoxOnError == false ) bPopMsgBox = false; - return DXTrace( strFile, dwLine, hr, strMsg, bPopMsgBox ); -} - - -//-------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------- -void WINAPI DXUTConvertDeviceSettings11to9( DXUTD3D11DeviceSettings* pIn, DXUTD3D9DeviceSettings* pOut ) -{ - pOut->AdapterOrdinal = pIn->AdapterOrdinal; - - if( pIn->DriverType == D3D_DRIVER_TYPE_HARDWARE ) - pOut->DeviceType = D3DDEVTYPE_HAL; - else if( pIn->DriverType == D3D_DRIVER_TYPE_REFERENCE ) - pOut->DeviceType = D3DDEVTYPE_REF; - else if( pIn->DriverType == D3D_DRIVER_TYPE_NULL ) - pOut->DeviceType = D3DDEVTYPE_NULLREF; - - pOut->AdapterFormat = ConvertFormatDXGIToD3D9( pIn->sd.BufferDesc.Format ); - pOut->BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING; - pOut->pp.BackBufferWidth = pIn->sd.BufferDesc.Width; - pOut->pp.BackBufferHeight = pIn->sd.BufferDesc.Height; - pOut->pp.BackBufferFormat = ConvertFormatDXGIToD3D9( pIn->sd.BufferDesc.Format ); - pOut->pp.BackBufferCount = pIn->sd.BufferCount; - pOut->pp.MultiSampleType = ( D3DMULTISAMPLE_TYPE )pIn->sd.SampleDesc.Count; - pOut->pp.MultiSampleQuality = pIn->sd.SampleDesc.Quality; - pOut->pp.SwapEffect = D3DSWAPEFFECT_DISCARD; - pOut->pp.hDeviceWindow = pIn->sd.OutputWindow; - pOut->pp.Windowed = pIn->sd.Windowed; - pOut->pp.EnableAutoDepthStencil = true; - pOut->pp.AutoDepthStencilFormat = D3DFMT_D24FS8; - pOut->pp.Flags = 0; - if( pIn->sd.BufferDesc.RefreshRate.Denominator == 0 ) - pOut->pp.FullScreen_RefreshRateInHz = 60; - else - pOut->pp.FullScreen_RefreshRateInHz = pIn->sd.BufferDesc.RefreshRate.Numerator / - pIn->sd.BufferDesc.RefreshRate.Denominator; - - switch( pIn->SyncInterval ) - { - case 0: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; break; - case 2: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_TWO; break; - case 3: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_THREE; break; - case 4: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_FOUR; break; - - case 1: - default: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; - break; - } -} - - -//-------------------------------------------------------------------------------------- -void WINAPI DXUTConvertDeviceSettings9to11( DXUTD3D9DeviceSettings* pIn, DXUTD3D11DeviceSettings* pOut ) -{ - pOut->AdapterOrdinal = pIn->AdapterOrdinal; - - if( pIn->DeviceType == D3DDEVTYPE_HAL ) - pOut->DriverType = D3D_DRIVER_TYPE_HARDWARE; - else if( pIn->DeviceType == D3DDEVTYPE_REF ) - pOut->DriverType = D3D_DRIVER_TYPE_REFERENCE; - else if( pIn->DeviceType == D3DDEVTYPE_NULLREF ) - pOut->DriverType = D3D_DRIVER_TYPE_NULL; - - pOut->Output = 0; - - pOut->sd.BufferDesc.Width = pIn->pp.BackBufferWidth; - pOut->sd.BufferDesc.Height = pIn->pp.BackBufferHeight; - pOut->sd.BufferDesc.RefreshRate.Numerator = pIn->pp.FullScreen_RefreshRateInHz; - pOut->sd.BufferDesc.RefreshRate.Denominator = 1; - pOut->sd.BufferDesc.Format = ConvertFormatD3D9ToDXGI( pIn->pp.BackBufferFormat ); - - if( pIn->pp.MultiSampleType == D3DMULTISAMPLE_NONMASKABLE ) - { - pOut->sd.SampleDesc.Count = pIn->pp.MultiSampleQuality; - pOut->sd.SampleDesc.Quality = 0; - } - else + WCHAR buff[ MAX_PATH ]; + int result = MultiByteToWideChar( CP_ACP, + MB_PRECOMPOSED, + strFile, + -1, + buff, + MAX_PATH ); + if ( !result ) { - pOut->sd.SampleDesc.Count = pIn->pp.MultiSampleType; - pOut->sd.SampleDesc.Quality = pIn->pp.MultiSampleQuality; + wcscpy_s( buff, L"*ERROR*" ); } - pOut->sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - pOut->sd.BufferCount = pIn->pp.BackBufferCount; - pOut->sd.OutputWindow = pIn->pp.hDeviceWindow; - pOut->sd.Windowed = pIn->pp.Windowed; - -#if defined(DEBUG) || defined(_DEBUG) - pOut->CreateFlags = D3D11_CREATE_DEVICE_DEBUG; -#else - pOut->CreateFlags = 0; -#endif - - switch( pIn->pp.PresentationInterval ) - { - case D3DPRESENT_INTERVAL_IMMEDIATE: - pOut->SyncInterval = 0; break; - case D3DPRESENT_INTERVAL_ONE: - pOut->SyncInterval = 1; break; - case D3DPRESENT_INTERVAL_TWO: - pOut->SyncInterval = 2; break; - case D3DPRESENT_INTERVAL_THREE: - pOut->SyncInterval = 3; break; - case D3DPRESENT_INTERVAL_FOUR: - pOut->SyncInterval = 4; break; - - case D3DPRESENT_INTERVAL_DEFAULT: - default: - pOut->SyncInterval = 1; - break; - } - - pOut->PresentFlags = 0; -} - - - -DXGI_FORMAT WINAPI ConvertFormatD3D9ToDXGI( D3DFORMAT fmt ) -{ - switch( fmt ) - { - case D3DFMT_UNKNOWN: - return DXGI_FORMAT_UNKNOWN; - case D3DFMT_R8G8B8: - case D3DFMT_A8R8G8B8: - case D3DFMT_X8R8G8B8: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_R5G6B5: - return DXGI_FORMAT_B5G6R5_UNORM; - case D3DFMT_X1R5G5B5: - case D3DFMT_A1R5G5B5: - return DXGI_FORMAT_B5G5R5A1_UNORM; - case D3DFMT_A4R4G4B4: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_R3G3B2: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_A8: - return DXGI_FORMAT_A8_UNORM; - case D3DFMT_A8R3G3B2: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_X4R4G4B4: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_A2B10G10R10: - return DXGI_FORMAT_R10G10B10A2_UNORM; - case D3DFMT_A8B8G8R8: - case D3DFMT_X8B8G8R8: - return DXGI_FORMAT_B8G8R8A8_UNORM; - case D3DFMT_G16R16: - return DXGI_FORMAT_R16G16_UNORM; - case D3DFMT_A2R10G10B10: - return DXGI_FORMAT_R10G10B10A2_UNORM; - case D3DFMT_A16B16G16R16: - return DXGI_FORMAT_R16G16B16A16_UNORM; - case D3DFMT_R16F: - return DXGI_FORMAT_R16_FLOAT; - case D3DFMT_G16R16F: - return DXGI_FORMAT_R16G16_FLOAT; - case D3DFMT_A16B16G16R16F: - return DXGI_FORMAT_R16G16B16A16_FLOAT; - case D3DFMT_R32F: - return DXGI_FORMAT_R32_FLOAT; - case D3DFMT_G32R32F: - return DXGI_FORMAT_R32G32_FLOAT; - case D3DFMT_A32B32G32R32F: - return DXGI_FORMAT_R32G32B32A32_FLOAT; - } - return DXGI_FORMAT_UNKNOWN; -} - - -D3DFORMAT WINAPI ConvertFormatDXGIToD3D9( DXGI_FORMAT fmt ) -{ - switch( fmt ) - { - case DXGI_FORMAT_UNKNOWN: - return D3DFMT_UNKNOWN; - case DXGI_FORMAT_R8G8B8A8_UNORM: - return D3DFMT_A8R8G8B8; - case DXGI_FORMAT_B5G6R5_UNORM: - return D3DFMT_R5G6B5; - case DXGI_FORMAT_B5G5R5A1_UNORM: - return D3DFMT_A1R5G5B5; - case DXGI_FORMAT_A8_UNORM: - return D3DFMT_A8; - case DXGI_FORMAT_R10G10B10A2_UNORM: - return D3DFMT_A2B10G10R10; - case DXGI_FORMAT_B8G8R8A8_UNORM: - return D3DFMT_A8B8G8R8; - case DXGI_FORMAT_R16G16_UNORM: - return D3DFMT_G16R16; - case DXGI_FORMAT_R16G16B16A16_UNORM: - return D3DFMT_A16B16G16R16; - case DXGI_FORMAT_R16_FLOAT: - return D3DFMT_R16F; - case DXGI_FORMAT_R16G16_FLOAT: - return D3DFMT_G16R16F; - case DXGI_FORMAT_R16G16B16A16_FLOAT: - return D3DFMT_A16B16G16R16F; - case DXGI_FORMAT_R32_FLOAT: - return D3DFMT_R32F; - case DXGI_FORMAT_R32G32_FLOAT: - return D3DFMT_G32R32F; - case DXGI_FORMAT_R32G32B32A32_FLOAT: - return D3DFMT_A32B32G32R32F; - } - return D3DFMT_UNKNOWN; -} - -//-------------------------------------------------------------------------------------- -IDirect3DDevice9* WINAPI DXUTCreateRefDevice9( HWND hWnd, bool bNullRef ) -{ - HRESULT hr; - IDirect3D9* pD3D = DXUT_Dynamic_Direct3DCreate9( D3D_SDK_VERSION ); - if( NULL == pD3D ) - return NULL; - - D3DDISPLAYMODE Mode; - pD3D->GetAdapterDisplayMode( 0, &Mode ); - - D3DPRESENT_PARAMETERS pp; - ZeroMemory( &pp, sizeof( D3DPRESENT_PARAMETERS ) ); - pp.BackBufferWidth = 1; - pp.BackBufferHeight = 1; - pp.BackBufferFormat = Mode.Format; - pp.BackBufferCount = 1; - pp.SwapEffect = D3DSWAPEFFECT_COPY; - pp.Windowed = TRUE; - pp.hDeviceWindow = hWnd; - - IDirect3DDevice9* pd3dDevice = NULL; - hr = pD3D->CreateDevice( D3DADAPTER_DEFAULT, bNullRef ? D3DDEVTYPE_NULLREF : D3DDEVTYPE_REF, - hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp, &pd3dDevice ); - - SAFE_RELEASE( pD3D ); - return pd3dDevice; -} - - -//-------------------------------------------------------------------------------------- -// Helper function to launch the Media Center UI after the program terminates -//-------------------------------------------------------------------------------------- -bool DXUTReLaunchMediaCenter() -{ - // Get the path to Media Center - WCHAR szExpandedPath[MAX_PATH]; - if( !ExpandEnvironmentStrings( L"%SystemRoot%\\ehome\\ehshell.exe", szExpandedPath, MAX_PATH ) ) - return false; - - // Skip if ehshell.exe doesn't exist - if( GetFileAttributes( szExpandedPath ) == 0xFFFFFFFF ) - return false; - - // Launch ehshell.exe - INT_PTR result = ( INT_PTR )ShellExecute( NULL, TEXT( "open" ), szExpandedPath, NULL, NULL, SW_SHOWNORMAL ); - return ( result > 32 ); + return DXTraceW( buff, dwLine, hr, strMsg, bPopMsgBox ); } typedef DWORD ( WINAPI* LPXINPUTGETSTATE )( DWORD dwUserIndex, XINPUT_STATE* pState ); @@ -1502,24 +927,25 @@ typedef void ( WINAPI* LPXINPUTENABLE )( BOOL bEnable ); //-------------------------------------------------------------------------------------- // Does extra processing on XInput data to make it slightly more convenient to use //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTGetGamepadState( DWORD dwPort, DXUT_GAMEPAD* pGamePad, bool bThumbstickDeadZone, bool bSnapThumbstickToCardinals ) { - if( dwPort >= DXUT_MAX_CONTROLLERS || pGamePad == NULL ) + if( dwPort >= DXUT_MAX_CONTROLLERS || !pGamePad ) return E_FAIL; - static LPXINPUTGETSTATE s_pXInputGetState = NULL; - static LPXINPUTGETCAPABILITIES s_pXInputGetCapabilities = NULL; - if( NULL == s_pXInputGetState || NULL == s_pXInputGetCapabilities ) + static LPXINPUTGETSTATE s_pXInputGetState = nullptr; + static LPXINPUTGETCAPABILITIES s_pXInputGetCapabilities = nullptr; + if( !s_pXInputGetState || !s_pXInputGetCapabilities ) { - HINSTANCE hInst = LoadLibrary( XINPUT_DLL ); + HINSTANCE hInst = LoadLibraryEx( XINPUT_DLL, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( hInst ) { - s_pXInputGetState = ( LPXINPUTGETSTATE )GetProcAddress( hInst, "XInputGetState" ); - s_pXInputGetCapabilities = ( LPXINPUTGETCAPABILITIES )GetProcAddress( hInst, "XInputGetCapabilities" ); + s_pXInputGetState = reinterpret_cast( reinterpret_cast( GetProcAddress( hInst, "XInputGetState" ) ) ); + s_pXInputGetCapabilities = reinterpret_cast( reinterpret_cast( GetProcAddress( hInst, "XInputGetCapabilities" ) ) ); } } - if( s_pXInputGetState == NULL ) + if( !s_pXInputGetState ) return E_FAIL; XINPUT_STATE InputState; @@ -1614,14 +1040,14 @@ HRESULT DXUTGetGamepadState( DWORD dwPort, DXUT_GAMEPAD* pGamePad, bool bThumbst // Don't pause the game or deactive the window without first stopping rumble otherwise // the controller will continue to rumble //-------------------------------------------------------------------------------------- -void DXUTEnableXInput( bool bEnable ) +void DXUTEnableXInput( _In_ bool bEnable ) { - static LPXINPUTENABLE s_pXInputEnable = NULL; - if( NULL == s_pXInputEnable ) + static LPXINPUTENABLE s_pXInputEnable = nullptr; + if( !s_pXInputEnable ) { - HINSTANCE hInst = LoadLibrary( XINPUT_DLL ); + HINSTANCE hInst = LoadLibraryEx( XINPUT_DLL, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( hInst ) - s_pXInputEnable = ( LPXINPUTENABLE )GetProcAddress( hInst, "XInputEnable" ); + s_pXInputEnable = reinterpret_cast( reinterpret_cast( GetProcAddress( hInst, "XInputEnable" ) ) ); } if( s_pXInputEnable ) @@ -1635,14 +1061,14 @@ void DXUTEnableXInput( bool bEnable ) //-------------------------------------------------------------------------------------- HRESULT DXUTStopRumbleOnAllControllers() { - static LPXINPUTSETSTATE s_pXInputSetState = NULL; - if( NULL == s_pXInputSetState ) + static LPXINPUTSETSTATE s_pXInputSetState = nullptr; + if( !s_pXInputSetState ) { - HINSTANCE hInst = LoadLibrary( XINPUT_DLL ); + HINSTANCE hInst = LoadLibraryEx( XINPUT_DLL, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( hInst ) - s_pXInputSetState = ( LPXINPUTSETSTATE )GetProcAddress( hInst, "XInputSetState" ); + s_pXInputSetState = reinterpret_cast( reinterpret_cast( GetProcAddress( hInst, "XInputSetState" ) ) ); } - if( s_pXInputSetState == NULL ) + if( !s_pXInputSetState ) return E_FAIL; XINPUT_VIBRATION vibration; @@ -1657,7 +1083,7 @@ HRESULT DXUTStopRumbleOnAllControllers() //-------------------------------------------------------------------------------------- // Helper functions to create SRGB formats from typeless formats and vice versa //-------------------------------------------------------------------------------------- -DXGI_FORMAT MAKE_SRGB( DXGI_FORMAT format ) +DXGI_FORMAT MAKE_SRGB( _In_ DXGI_FORMAT format ) { if( !DXUTIsInGammaCorrectMode() ) return format; @@ -1674,66 +1100,146 @@ DXGI_FORMAT MAKE_SRGB( DXGI_FORMAT format ) case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: return DXGI_FORMAT_BC1_UNORM_SRGB; + case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: return DXGI_FORMAT_BC2_UNORM_SRGB; + case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: return DXGI_FORMAT_BC3_UNORM_SRGB; - }; - - return format; -} - -//-------------------------------------------------------------------------------------- -DXGI_FORMAT MAKE_TYPELESS( DXGI_FORMAT format ) -{ - if( !DXUTIsInGammaCorrectMode() ) - return format; + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; - switch( format ) - { - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - case DXGI_FORMAT_R8G8B8A8_UNORM: - case DXGI_FORMAT_R8G8B8A8_UINT: - case DXGI_FORMAT_R8G8B8A8_SNORM: - case DXGI_FORMAT_R8G8B8A8_SINT: - return DXGI_FORMAT_R8G8B8A8_TYPELESS; + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; - case DXGI_FORMAT_BC1_UNORM_SRGB: - case DXGI_FORMAT_BC1_UNORM: - return DXGI_FORMAT_BC1_TYPELESS; - case DXGI_FORMAT_BC2_UNORM_SRGB: - case DXGI_FORMAT_BC2_UNORM: - return DXGI_FORMAT_BC2_TYPELESS; - case DXGI_FORMAT_BC3_UNORM_SRGB: - case DXGI_FORMAT_BC3_UNORM: - return DXGI_FORMAT_BC3_TYPELESS; + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + return DXGI_FORMAT_BC7_UNORM_SRGB; }; return format; } //-------------------------------------------------------------------------------------- -HRESULT DXUTSnapD3D9Screenshot( LPCTSTR szFileName ) +DXGI_FORMAT MAKE_TYPELESS( _In_ DXGI_FORMAT format ) { - HRESULT hr = S_OK; - IDirect3DDevice9* pDev = DXUTGetD3D9Device(); - if( !pDev ) - return E_FAIL; - - IDirect3DSurface9* pBackBuffer = NULL; - V_RETURN( pDev->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ) ); - - return D3DXSaveSurfaceToFile( szFileName, D3DXIFF_BMP, pBackBuffer, NULL, NULL ); + switch( format ) + { + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: + case DXGI_FORMAT_R32G32B32A32_SINT: + return DXGI_FORMAT_R32G32B32A32_TYPELESS; + + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: + return DXGI_FORMAT_R32G32B32_TYPELESS; + + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SINT: + return DXGI_FORMAT_R16G16B16A16_TYPELESS; + + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + return DXGI_FORMAT_R32G32_TYPELESS; + + case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: + return DXGI_FORMAT_R10G10B10A2_TYPELESS; + + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SINT: + return DXGI_FORMAT_R8G8B8A8_TYPELESS; + + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16_SINT: + return DXGI_FORMAT_R16G16_TYPELESS; + + case DXGI_FORMAT_D32_FLOAT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + return DXGI_FORMAT_R32_TYPELESS; + + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8_SINT: + return DXGI_FORMAT_R8G8_TYPELESS; + + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_D16_UNORM: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16_SINT: + return DXGI_FORMAT_R16_TYPELESS; + + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_A8_UNORM: + return DXGI_FORMAT_R8_TYPELESS; + + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + return DXGI_FORMAT_BC1_TYPELESS; + + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + return DXGI_FORMAT_BC2_TYPELESS; + + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + return DXGI_FORMAT_BC3_TYPELESS; + + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + return DXGI_FORMAT_BC4_TYPELESS; + + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + return DXGI_FORMAT_BC5_TYPELESS; + + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + return DXGI_FORMAT_B8G8R8A8_TYPELESS; + + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + return DXGI_FORMAT_B8G8R8X8_TYPELESS; + + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + return DXGI_FORMAT_BC6H_TYPELESS; + + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return DXGI_FORMAT_BC7_TYPELESS; + + default: + return format; + } } - - - //-------------------------------------------------------------------------------------- -HRESULT DXUTSnapD3D11Screenshot( LPCTSTR szFileName, D3DX11_IMAGE_FILE_FORMAT iff ) +HRESULT DXUTSnapD3D11Screenshot( _In_z_ LPCWSTR szFileName, _In_ bool usedds ) { IDXGISwapChain *pSwap = DXUTGetDXGISwapChain(); @@ -1745,45 +1251,22 @@ HRESULT DXUTSnapD3D11Screenshot( LPCTSTR szFileName, D3DX11_IMAGE_FILE_FORMAT if if (hr != S_OK) return hr; - ID3D11DeviceContext *dc = DXUTGetD3D11DeviceContext(); - if (!dc) { - SAFE_RELEASE(pBackBuffer); - return E_FAIL; - } - ID3D11Device *pDevice = DXUTGetD3D11Device(); + auto dc = DXUTGetD3D11DeviceContext(); if (!dc) { SAFE_RELEASE(pBackBuffer); return E_FAIL; } - D3D11_TEXTURE2D_DESC dsc; - pBackBuffer->GetDesc(&dsc); - D3D11_RESOURCE_DIMENSION dim; - pBackBuffer->GetType(&dim); - // special case msaa textures - ID3D11Texture2D *pCompatableTexture = pBackBuffer; - if ( dsc.SampleDesc.Count > 1) { - D3D11_TEXTURE2D_DESC dsc_new = dsc; - dsc_new.SampleDesc.Count = 1; - dsc_new.SampleDesc.Quality = 0; - dsc_new.Usage = D3D11_USAGE_DEFAULT; - dsc_new.BindFlags = 0; - dsc_new.CPUAccessFlags = 0; - ID3D11Texture2D *resolveTexture; - hr = pDevice->CreateTexture2D(&dsc_new, NULL, &resolveTexture); - if ( SUCCEEDED(hr) ) - { - DXUT_SetDebugName(resolveTexture, "DXUT"); - dc->ResolveSubresource(resolveTexture, 0, pBackBuffer, 0, dsc.Format); - pCompatableTexture = resolveTexture; - } - pCompatableTexture->GetDesc(&dsc); + if ( usedds ) + { + hr = DirectX::SaveDDSTextureToFile( dc, pBackBuffer, szFileName ); + } + else + { + hr = DirectX::SaveWICTextureToFile( dc, pBackBuffer, GUID_ContainerFormatBmp, szFileName ); } - hr = D3DX11SaveTextureToFileW(dc, pCompatableTexture, iff, szFileName); - SAFE_RELEASE(pBackBuffer); - SAFE_RELEASE(pCompatableTexture); return hr; diff --git a/FriedLiver/Source/DXUT/Core/DXUTmisc.h b/FriedLiver/Source/DXUT/Core/DXUTmisc.h index 9a9593ad..a586d983 100644 --- a/FriedLiver/Source/DXUT/Core/DXUTmisc.h +++ b/FriedLiver/Source/DXUT/Core/DXUTmisc.h @@ -3,15 +3,12 @@ // // Helper functions for Direct3D programming. // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_MISC_H -#define DXUT_MISC_H - -#ifndef MAX_FVF_DECL_SIZE -#define MAX_FVF_DECL_SIZE MAXD3DDECLLENGTH + 1 // +1 for END -#endif //-------------------------------------------------------------------------------------- // XInput helper state/function @@ -61,68 +58,17 @@ struct DXUT_GAMEPAD bool bLastRightTrigger; }; -HRESULT DXUTGetGamepadState( DWORD dwPort, DXUT_GAMEPAD* pGamePad, bool bThumbstickDeadZone = true, - bool bSnapThumbstickToCardinals = true ); +HRESULT DXUTGetGamepadState( _In_ DWORD dwPort, _In_ DXUT_GAMEPAD* pGamePad, _In_ bool bThumbstickDeadZone = true, + _In_ bool bSnapThumbstickToCardinals = true ); HRESULT DXUTStopRumbleOnAllControllers(); -void DXUTEnableXInput( bool bEnable ); +void DXUTEnableXInput( _In_ bool bEnable ); //-------------------------------------------------------------------------------------- -// Takes a screen shot of a 32bit D3D9 back buffer and saves the images to a BMP file +// Takes a screen shot of a 32bit D3D11 back buffer and saves the images to a BMP or DDS file //-------------------------------------------------------------------------------------- -HRESULT DXUTSnapD3D9Screenshot( LPCTSTR szFileName ); - -//-------------------------------------------------------------------------------------- -// Takes a screen shot of a 32bit D3D11 back buffer and saves the images to a BMP file -//-------------------------------------------------------------------------------------- - -HRESULT DXUTSnapD3D11Screenshot( LPCTSTR szFileName, D3DX11_IMAGE_FILE_FORMAT iff = D3DX11_IFF_DDS ); - - -//-------------------------------------------------------------------------------------- -// A growable array -//-------------------------------------------------------------------------------------- -template class CGrowableArray -{ -public: - CGrowableArray() { m_pData = NULL; m_nSize = 0; m_nMaxSize = 0; } - CGrowableArray( const CGrowableArray& a ) { for( int i=0; i < a.m_nSize; i++ ) Add( a.m_pData[i] ); } - ~CGrowableArray() { RemoveAll(); } - - const TYPE& operator[]( int nIndex ) const { return GetAt( nIndex ); } - TYPE& operator[]( int nIndex ) { return GetAt( nIndex ); } - - CGrowableArray& operator=( const CGrowableArray& a ) { if( this == &a ) return *this; RemoveAll(); for( int i=0; i < a.m_nSize; i++ ) Add( a.m_pData[i] ); return *this; } - - HRESULT SetSize( int nNewMaxSize ); - HRESULT Add( const TYPE& value ); - HRESULT Insert( int nIndex, const TYPE& value ); - HRESULT SetAt( int nIndex, const TYPE& value ); - TYPE& GetAt( int nIndex ) const { assert( nIndex >= 0 && nIndex < m_nSize ); return m_pData[nIndex]; } - int GetSize() const { return m_nSize; } - TYPE* GetData() { return m_pData; } - bool Contains( const TYPE& value ){ return ( -1 != IndexOf( value ) ); } - - int IndexOf( const TYPE& value ) { return ( m_nSize > 0 ) ? IndexOf( value, 0, m_nSize ) : -1; } - int IndexOf( const TYPE& value, int iStart ) { return IndexOf( value, iStart, m_nSize - iStart ); } - int IndexOf( const TYPE& value, int nIndex, int nNumElements ); - - int LastIndexOf( const TYPE& value ) { return ( m_nSize > 0 ) ? LastIndexOf( value, m_nSize-1, m_nSize ) : -1; } - int LastIndexOf( const TYPE& value, int nIndex ) { return LastIndexOf( value, nIndex, nIndex+1 ); } - int LastIndexOf( const TYPE& value, int nIndex, int nNumElements ); - - HRESULT Remove( int nIndex ); - void RemoveAll() { SetSize(0); } - void Reset() { m_nSize = 0; } - -protected: - TYPE* m_pData; // the actual array of data - int m_nSize; // # of elements (upperBound - 1) - int m_nMaxSize; // max allocated - - HRESULT SetSizeInternal( int nNewMaxSize ); // This version doesn't call ctor or dtor. -}; +HRESULT DXUTSnapD3D11Screenshot( _In_z_ LPCWSTR szFileName, _In_ bool usedds = true ); //-------------------------------------------------------------------------------------- // Performs timer operations @@ -131,26 +77,25 @@ template class CGrowableArray class CDXUTTimer { public: - CDXUTTimer(); + CDXUTTimer() noexcept; void Reset(); // resets the timer void Start(); // starts the timer void Stop(); // stop (or pause) the timer void Advance(); // advance the timer by 0.1 seconds - double GetAbsoluteTime(); // get the absolute system time - double GetTime(); // get the current time + double GetAbsoluteTime() const; // get the absolute system time + double GetTime() const; // get the current time float GetElapsedTime(); // get the time that elapsed between Get*ElapsedTime() calls - void GetTimeValues( double* pfTime, double* pfAbsoluteTime, float* pfElapsedTime ); // get all time values at once - bool IsStopped(); // returns true if timer stopped + void GetTimeValues( _Out_ double* pfTime, _Out_ double* pfAbsoluteTime, _Out_ float* pfElapsedTime ); // get all time values at once + bool IsStopped() const { return m_bTimerStopped; } // returns true if timer stopped // Limit the current thread to one processor (the current one). This ensures that timing code runs // on only one processor, and will not suffer any ill effects from power management. void LimitThreadAffinityToCurrentProc(); protected: - LARGE_INTEGER GetAdjustedCurrentTime(); + LARGE_INTEGER GetAdjustedCurrentTime() const; - bool m_bUsingQPF; bool m_bTimerStopped; LONGLONG m_llQPFTicksPerSec; @@ -162,42 +107,21 @@ class CDXUTTimer CDXUTTimer* WINAPI DXUTGetGlobalTimer(); -//-------------------------------------------------------------------------------------- -// Returns the string for the given D3DFORMAT. -// bWithPrefix determines whether the string should include the "D3DFMT_" -//-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTD3DFormatToString( D3DFORMAT format, bool bWithPrefix ); - - //-------------------------------------------------------------------------------------- // Returns the string for the given DXGI_FORMAT. // bWithPrefix determines whether the string should include the "DXGI_FORMAT_" //-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTDXGIFormatToString( DXGI_FORMAT format, bool bWithPrefix ); - - -//-------------------------------------------------------------------------------------- -// Device settings conversion -//-------------------------------------------------------------------------------------- -void WINAPI DXUTConvertDeviceSettings11to9( DXUTD3D11DeviceSettings* pIn, DXUTD3D9DeviceSettings* pOut ); -void WINAPI DXUTConvertDeviceSettings9to11( DXUTD3D9DeviceSettings* pIn, DXUTD3D11DeviceSettings* pOut ); - -DXGI_FORMAT WINAPI ConvertFormatD3D9ToDXGI( D3DFORMAT fmt ); -D3DFORMAT WINAPI ConvertFormatDXGIToD3D9( DXGI_FORMAT fmt ); +LPCWSTR WINAPI DXUTDXGIFormatToString( _In_ DXGI_FORMAT format, _In_ bool bWithPrefix ); //-------------------------------------------------------------------------------------- // Debug printing support // See dxerr.h for more debug printing support //-------------------------------------------------------------------------------------- -void WINAPI DXUTOutputDebugStringW( LPCWSTR strMsg, ... ); -void WINAPI DXUTOutputDebugStringA( LPCSTR strMsg, ... ); -HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, const WCHAR* strMsg, bool bPopMsgBox ); -void WINAPI DXUTTraceDecl( D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE] ); -WCHAR* WINAPI DXUTTraceD3DDECLUSAGEtoString( BYTE u ); -WCHAR* WINAPI DXUTTraceD3DDECLMETHODtoString( BYTE m ); -WCHAR* WINAPI DXUTTraceD3DDECLTYPEtoString( BYTE t ); -WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ); +void WINAPI DXUTOutputDebugStringW( _In_z_ LPCWSTR strMsg, ... ); +void WINAPI DXUTOutputDebugStringA( _In_z_ LPCSTR strMsg, ... ); +HRESULT WINAPI DXUTTrace( _In_z_ const CHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_z_ const WCHAR* strMsg, _In_ bool bPopMsgBox ); +const WCHAR* WINAPI DXUTTraceWindowsMessage( _In_ UINT uMsg ); #ifdef UNICODE #define DXUTOutputDebugString DXUTOutputDebugStringW @@ -219,32 +143,32 @@ WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ); //-------------------------------------------------------------------------------------- -// Direct3D9 dynamic linking support -- calls top-level D3D9 APIs with graceful +// Direct3D dynamic linking support -- calls top-level D3D APIs with graceful // failure if APIs are not present. //-------------------------------------------------------------------------------------- -IDirect3D9 * WINAPI DXUT_Dynamic_Direct3DCreate9(UINT SDKVersion); -int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( D3DCOLOR col, LPCWSTR wszName ); +int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( _In_ DWORD col, _In_z_ LPCWSTR wszName ); int WINAPI DXUT_Dynamic_D3DPERF_EndEvent( void ); -void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( D3DCOLOR col, LPCWSTR wszName ); -void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( D3DCOLOR col, LPCWSTR wszName ); +void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( _In_ DWORD col, _In_z_ LPCWSTR wszName ); +void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( _In_ DWORD col, _In_z_ LPCWSTR wszName ); BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame( void ); -void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( DWORD dwOptions ); -DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus( void ); -HRESULT WINAPI DXUT_Dynamic_CreateDXGIFactory1( REFIID rInterface, void** ppOut ); +void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( _In_ DWORD dwOptions ); +DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus(); +HRESULT WINAPI DXUT_Dynamic_CreateDXGIFactory1( _In_ REFIID rInterface, _Out_ void** ppOut ); +HRESULT WINAPI DXUT_Dynamic_DXGIGetDebugInterface( _In_ REFIID rInterface, _Out_ void** ppOut ); -HRESULT WINAPI DXUT_Dynamic_D3D11CreateDevice( IDXGIAdapter* pAdapter, - D3D_DRIVER_TYPE DriverType, - HMODULE Software, - UINT32 Flags, - D3D_FEATURE_LEVEL* pFeatureLevels, - UINT FeatureLevels, - UINT32 SDKVersion, - ID3D11Device** ppDevice, - D3D_FEATURE_LEVEL* pFeatureLevel, - ID3D11DeviceContext** ppImmediateContext ); +HRESULT WINAPI DXUT_Dynamic_D3D11CreateDevice( _In_opt_ IDXGIAdapter* pAdapter, + _In_ D3D_DRIVER_TYPE DriverType, + _In_opt_ HMODULE Software, + _In_ UINT32 Flags, + _In_reads_(FeatureLevels) const D3D_FEATURE_LEVEL* pFeatureLevels, + _In_ UINT FeatureLevels, + _In_ UINT32 SDKVersion, + _Deref_out_ ID3D11Device** ppDevice, + _Out_opt_ D3D_FEATURE_LEVEL* pFeatureLevel, + _Out_opt_ ID3D11DeviceContext** ppImmediateContext ); -bool DXUT_EnsureD3D11APIs( void ); +bool DXUT_EnsureD3D11APIs(); //-------------------------------------------------------------------------------------- @@ -254,35 +178,20 @@ bool DXUT_EnsureD3D11APIs( void ); // Use DXUT_SetDebugName() to attach names to D3D objects for use by // SDKDebugLayer, PIX's object table, etc. #if defined(PROFILE) || defined(DEBUG) -inline void DXUT_SetDebugName( IDirect3DResource9* pObj, const CHAR* pstrName ) +inline void DXUT_SetDebugName( _In_ IDXGIObject* pObj, _In_z_ const CHAR* pstrName ) { if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, pstrName, lstrlenA(pstrName), 0 ); + pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); } -inline void DXUT_SetDebugName( IDXGIObject* pObj, const CHAR* pstrName ) +inline void DXUT_SetDebugName( _In_ ID3D11Device* pObj, _In_z_ const CHAR* pstrName ) { if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); + pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); } -inline void DXUT_SetDebugName( ID3D10Device* pObj, const CHAR* pstrName ) +inline void DXUT_SetDebugName( _In_ ID3D11DeviceChild* pObj, _In_z_ const CHAR* pstrName ) { if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); -} -inline void DXUT_SetDebugName( ID3D10DeviceChild* pObj, const CHAR* pstrName ) -{ - if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); -} -inline void DXUT_SetDebugName( ID3D11Device* pObj, const CHAR* pstrName ) -{ - if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); -} -inline void DXUT_SetDebugName( ID3D11DeviceChild* pObj, const CHAR* pstrName ) -{ - if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); + pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); } #else #define DXUT_SetDebugName( pObj, pstrName ) @@ -294,9 +203,9 @@ inline void DXUT_SetDebugName( ID3D11DeviceChild* pObj, const CHAR* pstrName ) // performance analysis tools. The following constants are provided for your // convenience, but you can use any colors you like. //-------------------------------------------------------------------------------------- -const D3DCOLOR DXUT_PERFEVENTCOLOR = D3DCOLOR_XRGB( 200, 100, 100 ); -const D3DCOLOR DXUT_PERFEVENTCOLOR2 = D3DCOLOR_XRGB( 100, 200, 100 ); -const D3DCOLOR DXUT_PERFEVENTCOLOR3 = D3DCOLOR_XRGB( 100, 100, 200 ); +const DWORD DXUT_PERFEVENTCOLOR = 0xFFC86464; +const DWORD DXUT_PERFEVENTCOLOR2 = 0xFF64C864; +const DWORD DXUT_PERFEVENTCOLOR3 = 0xFF6464C8; //-------------------------------------------------------------------------------------- // The following macros provide a convenient way for your code to call the D3DPERF @@ -330,11 +239,16 @@ const D3DCOLOR DXUT_PERFEVENTCOLOR3 = D3DCOLOR_XRGB( 100, 100, 200 class CDXUTPerfEventGenerator { public: -CDXUTPerfEventGenerator( D3DCOLOR color, LPCWSTR pstrMessage ) +CDXUTPerfEventGenerator( _In_ DWORD color, _In_z_ LPCWSTR pstrMessage ) { +#ifdef PROFILE DXUT_BeginPerfEvent( color, pstrMessage ); +#else + UNREFERENCED_PARAMETER(color); + UNREFERENCED_PARAMETER(pstrMessage); +#endif } -~CDXUTPerfEventGenerator( void ) +~CDXUTPerfEventGenerator() { DXUT_EndPerfEvent(); } @@ -366,269 +280,14 @@ typedef MONITORINFOEXW MONITORINFOEX; typedef LPMONITORINFOEXW LPMONITORINFOEX; #endif -HMONITOR WINAPI DXUTMonitorFromWindow( HWND hWnd, DWORD dwFlags ); -HMONITOR WINAPI DXUTMonitorFromRect( LPCRECT lprcScreenCoords, DWORD dwFlags ); -BOOL WINAPI DXUTGetMonitorInfo( HMONITOR hMonitor, LPMONITORINFO lpMonitorInfo ); -void WINAPI DXUTGetDesktopResolution( UINT AdapterOrdinal, UINT* pWidth, UINT* pHeight ); - - -//-------------------------------------------------------------------------------------- -// Implementation of CGrowableArray -//-------------------------------------------------------------------------------------- - -// This version doesn't call ctor or dtor. -template HRESULT CGrowableArray ::SetSizeInternal( int nNewMaxSize ) -{ - if( nNewMaxSize < 0 || ( nNewMaxSize > INT_MAX / sizeof( TYPE ) ) ) - { - assert( false ); - return E_INVALIDARG; - } - - if( nNewMaxSize == 0 ) - { - // Shrink to 0 size & cleanup - if( m_pData ) - { - free( m_pData ); - m_pData = NULL; - } - - m_nMaxSize = 0; - m_nSize = 0; - } - else if( m_pData == NULL || nNewMaxSize > m_nMaxSize ) - { - // Grow array - int nGrowBy = ( m_nMaxSize == 0 ) ? 16 : m_nMaxSize; - - // Limit nGrowBy to keep m_nMaxSize less than INT_MAX - if( ( UINT )m_nMaxSize + ( UINT )nGrowBy > ( UINT )INT_MAX ) - nGrowBy = INT_MAX - m_nMaxSize; - - nNewMaxSize = __max( nNewMaxSize, m_nMaxSize + nGrowBy ); - - // Verify that (nNewMaxSize * sizeof(TYPE)) is not greater than UINT_MAX or the realloc will overrun - if( sizeof( TYPE ) > UINT_MAX / ( UINT )nNewMaxSize ) - return E_INVALIDARG; - - TYPE* pDataNew = ( TYPE* )realloc( m_pData, nNewMaxSize * sizeof( TYPE ) ); - if( pDataNew == NULL ) - return E_OUTOFMEMORY; - - m_pData = pDataNew; - m_nMaxSize = nNewMaxSize; - } - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -template HRESULT CGrowableArray ::SetSize( int nNewMaxSize ) -{ - int nOldSize = m_nSize; - - if( nOldSize > nNewMaxSize ) - { - assert( m_pData ); - if( m_pData ) - { - // Removing elements. Call dtor. - - for( int i = nNewMaxSize; i < nOldSize; ++i ) - m_pData[i].~TYPE(); - } - } - - // Adjust buffer. Note that there's no need to check for error - // since if it happens, nOldSize == nNewMaxSize will be true.) - HRESULT hr = SetSizeInternal( nNewMaxSize ); - - if( nOldSize < nNewMaxSize ) - { - assert( m_pData ); - if( m_pData ) - { - // Adding elements. Call ctor. - - for( int i = nOldSize; i < nNewMaxSize; ++i ) - ::new ( &m_pData[i] ) TYPE; - } - } - - return hr; -} - - -//-------------------------------------------------------------------------------------- -template HRESULT CGrowableArray ::Add( const TYPE& value ) -{ - HRESULT hr; - if( FAILED( hr = SetSizeInternal( m_nSize + 1 ) ) ) - return hr; - - assert( m_pData != NULL ); - - // Construct the new element - ::new ( &m_pData[m_nSize] ) TYPE; - - // Assign - m_pData[m_nSize] = value; - ++m_nSize; - - return S_OK; -} +HMONITOR WINAPI DXUTMonitorFromWindow( _In_ HWND hWnd, _In_ DWORD dwFlags ); +HMONITOR WINAPI DXUTMonitorFromRect( _In_ LPCRECT lprcScreenCoords, _In_ DWORD dwFlags ); +BOOL WINAPI DXUTGetMonitorInfo( _In_ HMONITOR hMonitor, _Out_ LPMONITORINFO lpMonitorInfo ); +void WINAPI DXUTGetDesktopResolution( _In_ UINT AdapterOrdinal, _Out_ UINT* pWidth, _Out_ UINT* pHeight ); -//-------------------------------------------------------------------------------------- -template HRESULT CGrowableArray ::Insert( int nIndex, const TYPE& value ) -{ - HRESULT hr; - - // Validate index - if( nIndex < 0 || - nIndex > m_nSize ) - { - assert( false ); - return E_INVALIDARG; - } - - // Prepare the buffer - if( FAILED( hr = SetSizeInternal( m_nSize + 1 ) ) ) - return hr; - - // Shift the array - MoveMemory( &m_pData[nIndex + 1], &m_pData[nIndex], sizeof( TYPE ) * ( m_nSize - nIndex ) ); - - // Construct the new element - ::new ( &m_pData[nIndex] ) TYPE; - - // Set the value and increase the size - m_pData[nIndex] = value; - ++m_nSize; - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -template HRESULT CGrowableArray ::SetAt( int nIndex, const TYPE& value ) -{ - // Validate arguments - if( nIndex < 0 || - nIndex >= m_nSize ) - { - assert( false ); - return E_INVALIDARG; - } - - m_pData[nIndex] = value; - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -// Searches for the specified value and returns the index of the first occurrence -// within the section of the data array that extends from iStart and contains the -// specified number of elements. Returns -1 if value is not found within the given -// section. -//-------------------------------------------------------------------------------------- -template int CGrowableArray ::IndexOf( const TYPE& value, int iStart, int nNumElements ) -{ - // Validate arguments - if( iStart < 0 || - iStart >= m_nSize || - nNumElements < 0 || - iStart + nNumElements > m_nSize ) - { - assert( false ); - return -1; - } - - // Search - for( int i = iStart; i < ( iStart + nNumElements ); i++ ) - { - if( value == m_pData[i] ) - return i; - } - - // Not found - return -1; -} - - -//-------------------------------------------------------------------------------------- -// Searches for the specified value and returns the index of the last occurrence -// within the section of the data array that contains the specified number of elements -// and ends at iEnd. Returns -1 if value is not found within the given section. -//-------------------------------------------------------------------------------------- -template int CGrowableArray ::LastIndexOf( const TYPE& value, int iEnd, int nNumElements ) -{ - // Validate arguments - if( iEnd < 0 || - iEnd >= m_nSize || - nNumElements < 0 || - iEnd - nNumElements < 0 ) - { - assert( false ); - return -1; - } - - // Search - for( int i = iEnd; i > ( iEnd - nNumElements ); i-- ) - { - if( value == m_pData[i] ) - return i; - } - - // Not found - return -1; -} - - - -//-------------------------------------------------------------------------------------- -template HRESULT CGrowableArray ::Remove( int nIndex ) -{ - if( nIndex < 0 || - nIndex >= m_nSize ) - { - assert( false ); - return E_INVALIDARG; - } - - // Destruct the element to be removed - m_pData[nIndex].~TYPE(); - - // Compact the array and decrease the size - MoveMemory( &m_pData[nIndex], &m_pData[nIndex + 1], sizeof( TYPE ) * ( m_nSize - ( nIndex + 1 ) ) ); - --m_nSize; - - return S_OK; -} - -//-------------------------------------------------------------------------------------- -// Creates a REF or NULLREF D3D9 device and returns that device. The caller should call -// Release() when done with the device. -//-------------------------------------------------------------------------------------- -IDirect3DDevice9* WINAPI DXUTCreateRefDevice9( HWND hWnd, bool bNullRef = true ); - -//-------------------------------------------------------------------------------------- -// Creates a REF or NULLREF D3D10 device and returns the device. The caller should call -// Release() when done with the device. -//-------------------------------------------------------------------------------------- -//test d3d10 version ID3D10Device* WINAPI DXUTCreateRefDevice10( bool bNullRef = true ); - -//-------------------------------------------------------------------------------------- -// Helper function to launch the Media Center UI after the program terminates -//-------------------------------------------------------------------------------------- -bool DXUTReLaunchMediaCenter(); - //-------------------------------------------------------------------------------------- // Helper functions to create SRGB formats from typeless formats and vice versa //-------------------------------------------------------------------------------------- -DXGI_FORMAT MAKE_SRGB( DXGI_FORMAT format ); -DXGI_FORMAT MAKE_TYPELESS( DXGI_FORMAT format ); - -#endif +DXGI_FORMAT MAKE_SRGB( _In_ DXGI_FORMAT format ); +DXGI_FORMAT MAKE_TYPELESS( _In_ DXGI_FORMAT format ); diff --git a/FriedLiver/Source/DXUT/Core/ScreenGrab.cpp b/FriedLiver/Source/DXUT/Core/ScreenGrab.cpp new file mode 100644 index 00000000..4296091c --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/ScreenGrab.cpp @@ -0,0 +1,1204 @@ +//-------------------------------------------------------------------------------------- +// File: ScreenGrab.cpp +// +// Function for capturing a 2D texture and saving it to a file (aka a 'screenshot' +// when used on a Direct3D 11 Render Target). +// +// Note these functions are useful as a light-weight runtime screen grabber. For +// full-featured texture capture, DDS writer, and texture processing pipeline, +// see the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#include "dxut.h" + +// Does not capture 1D textures or 3D textures (volume maps) + +// Does not capture mipmap chains, only the top-most texture level is saved + +// For 2D array textures and cubemaps, it captures only the first image in the array + +#include "ScreenGrab.h" + +#include +#include + +#include + +#include + +#include +#include + +using Microsoft::WRL::ComPtr; + +//-------------------------------------------------------------------------------------- +// Macros +//-------------------------------------------------------------------------------------- +#ifndef MAKEFOURCC + #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ + ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \ + ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 )) +#endif /* defined(MAKEFOURCC) */ + +//-------------------------------------------------------------------------------------- +// DDS file structure definitions +// +// See DDS.h in the 'Texconv' sample and the 'DirectXTex' library +//-------------------------------------------------------------------------------------- +namespace +{ + #pragma pack(push,1) + + #define DDS_MAGIC 0x20534444 // "DDS " + + struct DDS_PIXELFORMAT + { + uint32_t size; + uint32_t flags; + uint32_t fourCC; + uint32_t RGBBitCount; + uint32_t RBitMask; + uint32_t GBitMask; + uint32_t BBitMask; + uint32_t ABitMask; + }; + + #define DDS_FOURCC 0x00000004 // DDPF_FOURCC + #define DDS_RGB 0x00000040 // DDPF_RGB + #define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS + #define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE + #define DDS_LUMINANCEA 0x00020001 // DDPF_LUMINANCE | DDPF_ALPHAPIXELS + #define DDS_ALPHA 0x00000002 // DDPF_ALPHA + #define DDS_BUMPDUDV 0x00080000 // DDPF_BUMPDUDV + + #define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT + #define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT + #define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH + #define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE + + #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT + #define DDS_WIDTH 0x00000004 // DDSD_WIDTH + + #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE + + typedef struct + { + uint32_t size; + uint32_t flags; + uint32_t height; + uint32_t width; + uint32_t pitchOrLinearSize; + uint32_t depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags + uint32_t mipMapCount; + uint32_t reserved1[11]; + DDS_PIXELFORMAT ddspf; + uint32_t caps; + uint32_t caps2; + uint32_t caps3; + uint32_t caps4; + uint32_t reserved2; + } DDS_HEADER; + + typedef struct + { + DXGI_FORMAT dxgiFormat; + uint32_t resourceDimension; + uint32_t miscFlag; // see D3D11_RESOURCE_MISC_FLAG + uint32_t arraySize; + uint32_t reserved; + } DDS_HEADER_DXT10; + + #pragma pack(pop) + + const DDS_PIXELFORMAT DDSPF_DXT1 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_DXT3 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_DXT5 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC4_UNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC4_SNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC5_UNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC5_SNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_YUY2 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_A8R8G8B8 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; + + const DDS_PIXELFORMAT DDSPF_X8R8G8B8 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 }; + + const DDS_PIXELFORMAT DDSPF_A8B8G8R8 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; + + const DDS_PIXELFORMAT DDSPF_G16R16 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 }; + + const DDS_PIXELFORMAT DDSPF_R5G6B5 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 }; + + const DDS_PIXELFORMAT DDSPF_A1R5G5B5 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000 }; + + const DDS_PIXELFORMAT DDSPF_A4R4G4B4 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000 }; + + const DDS_PIXELFORMAT DDSPF_L8 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0x00, 0x00, 0x00 }; + + const DDS_PIXELFORMAT DDSPF_L16 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0x0000, 0x0000, 0x0000 }; + + const DDS_PIXELFORMAT DDSPF_A8L8 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0x0000, 0x0000, 0xff00 }; + + const DDS_PIXELFORMAT DDSPF_A8 = + { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0x00, 0x00, 0x00, 0xff }; + + const DDS_PIXELFORMAT DDSPF_V8U8 = + { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 16, 0x00ff, 0xff00, 0x0000, 0x0000 }; + + const DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = + { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; + + const DDS_PIXELFORMAT DDSPF_V16U16 = + { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 }; + + // DXGI_FORMAT_R10G10B10A2_UNORM should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue + + // This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat) + const DDS_PIXELFORMAT DDSPF_DX10 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 }; + + //----------------------------------------------------------------------------- + struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; + + typedef std::unique_ptr ScopedHandle; + + inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; } + + class auto_delete_file + { + public: + auto_delete_file(HANDLE hFile) : m_handle(hFile) {} + ~auto_delete_file() + { + if (m_handle) + { + FILE_DISPOSITION_INFO info = {}; + info.DeleteFile = TRUE; + (void)SetFileInformationByHandle(m_handle, FileDispositionInfo, &info, sizeof(info)); + } + } + + void clear() { m_handle = 0; } + + private: + HANDLE m_handle; + + auto_delete_file(const auto_delete_file&) = delete; + auto_delete_file& operator=(const auto_delete_file&) = delete; + }; + + class auto_delete_file_wic + { + public: + auto_delete_file_wic(ComPtr& hFile, const wchar_t* szFile) : m_handle(hFile), m_filename(szFile) {} + ~auto_delete_file_wic() + { + if (m_filename) + { + m_handle.Reset(); + DeleteFileW(m_filename); + } + } + + void clear() { m_filename = 0; } + + private: + const wchar_t* m_filename; + ComPtr& m_handle; + + auto_delete_file_wic(const auto_delete_file_wic&) = delete; + auto_delete_file_wic& operator=(const auto_delete_file_wic&) = delete; + }; + + //-------------------------------------------------------------------------------------- + // Return the BPP for a particular format + //-------------------------------------------------------------------------------------- + size_t BitsPerPixel( _In_ DXGI_FORMAT fmt ) + { + switch( fmt ) + { + 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_R32G32B32_TYPELESS: + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: + return 96; + + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_TYPELESS: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + case DXGI_FORMAT_R32G8X24_TYPELESS: + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: + case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: + case DXGI_FORMAT_Y416: + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + return 64; + + case DXGI_FORMAT_R10G10B10A2_TYPELESS: + case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_TYPELESS: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_R16G16_TYPELESS: + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_D32_FLOAT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + case DXGI_FORMAT_R24G8_TYPELESS: + case DXGI_FORMAT_D24_UNORM_S8_UINT: + case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: + case DXGI_FORMAT_X24_TYPELESS_G8_UINT: + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + case DXGI_FORMAT_AYUV: + case DXGI_FORMAT_Y410: + case DXGI_FORMAT_YUY2: + return 32; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + return 24; + + case DXGI_FORMAT_R8G8_TYPELESS: + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8_SINT: + case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_D16_UNORM: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16_SINT: + case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: + case DXGI_FORMAT_A8P8: + case DXGI_FORMAT_B4G4R4A4_UNORM: + return 16; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + case DXGI_FORMAT_NV11: + return 12; + + case DXGI_FORMAT_R8_TYPELESS: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_A8_UNORM: + case DXGI_FORMAT_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + return 8; + + 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_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return 8; + + default: + return 0; + } + } + + + //-------------------------------------------------------------------------------------- + // Determines if the format is block compressed + //-------------------------------------------------------------------------------------- + bool IsCompressed( _In_ DXGI_FORMAT fmt ) + { + switch ( fmt ) + { + case DXGI_FORMAT_BC1_TYPELESS: + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return true; + + default: + return false; + } + } + + + //-------------------------------------------------------------------------------------- + // Get surface information for a particular format + //-------------------------------------------------------------------------------------- + void 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 ) + { + size_t numBytes = 0; + size_t rowBytes = 0; + size_t numRows = 0; + + bool bc = false; + bool packed = false; + bool planar = false; + size_t bpe = 0; + switch (fmt) + { + 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: + bc=true; + bpe = 8; + break; + + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + bc = true; + bpe = 16; + break; + + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_YUY2: + packed = true; + bpe = 4; + break; + + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + packed = true; + bpe = 8; + break; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + planar = true; + bpe = 2; + break; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + planar = true; + bpe = 4; + break; + } + + if (bc) + { + size_t numBlocksWide = 0; + if (width > 0) + { + numBlocksWide = std::max( 1, (width + 3) / 4 ); + } + size_t numBlocksHigh = 0; + if (height > 0) + { + numBlocksHigh = std::max( 1, (height + 3) / 4 ); + } + rowBytes = numBlocksWide * bpe; + numRows = numBlocksHigh; + numBytes = rowBytes * numBlocksHigh; + } + else if (packed) + { + rowBytes = ( ( width + 1 ) >> 1 ) * bpe; + numRows = height; + numBytes = rowBytes * height; + } + else if ( fmt == DXGI_FORMAT_NV11 ) + { + rowBytes = ( ( width + 3 ) >> 2 ) * 4; + numRows = height * 2; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data + numBytes = rowBytes * numRows; + } + else if (planar) + { + rowBytes = ( ( width + 1 ) >> 1 ) * bpe; + numBytes = ( rowBytes * height ) + ( ( rowBytes * height + 1 ) >> 1 ); + numRows = height + ( ( height + 1 ) >> 1 ); + } + else + { + size_t bpp = BitsPerPixel( fmt ); + rowBytes = ( width * bpp + 7 ) / 8; // round up to nearest byte + numRows = height; + numBytes = rowBytes * height; + } + + if (outNumBytes) + { + *outNumBytes = numBytes; + } + if (outRowBytes) + { + *outRowBytes = rowBytes; + } + if (outNumRows) + { + *outNumRows = numRows; + } + } + + + //-------------------------------------------------------------------------------------- + DXGI_FORMAT EnsureNotTypeless( DXGI_FORMAT fmt ) + { + // Assumes UNORM or FLOAT; doesn't use UINT or SINT + switch( fmt ) + { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT; + case DXGI_FORMAT_R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_FLOAT; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_UNORM; + case DXGI_FORMAT_R32G32_TYPELESS: return DXGI_FORMAT_R32G32_FLOAT; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_UNORM; + case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT; + case DXGI_FORMAT_R8G8_TYPELESS: return DXGI_FORMAT_R8G8_UNORM; + case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_R16_UNORM; + case DXGI_FORMAT_R8_TYPELESS: return DXGI_FORMAT_R8_UNORM; + case DXGI_FORMAT_BC1_TYPELESS: return DXGI_FORMAT_BC1_UNORM; + case DXGI_FORMAT_BC2_TYPELESS: return DXGI_FORMAT_BC2_UNORM; + case DXGI_FORMAT_BC3_TYPELESS: return DXGI_FORMAT_BC3_UNORM; + case DXGI_FORMAT_BC4_TYPELESS: return DXGI_FORMAT_BC4_UNORM; + case DXGI_FORMAT_BC5_TYPELESS: return DXGI_FORMAT_BC5_UNORM; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_UNORM; + case DXGI_FORMAT_BC7_TYPELESS: return DXGI_FORMAT_BC7_UNORM; + default: return fmt; + } + } + + + //-------------------------------------------------------------------------------------- + HRESULT CaptureTexture( + _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + D3D11_TEXTURE2D_DESC& desc, + ComPtr& pStaging ) + { + if ( !pContext || !pSource ) + return E_INVALIDARG; + + D3D11_RESOURCE_DIMENSION resType = D3D11_RESOURCE_DIMENSION_UNKNOWN; + pSource->GetType( &resType ); + + if ( resType != D3D11_RESOURCE_DIMENSION_TEXTURE2D ) + return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); + + ComPtr pTexture; + HRESULT hr = pSource->QueryInterface(IID_PPV_ARGS(pTexture.GetAddressOf())); + if ( FAILED(hr) ) + return hr; + + assert( pTexture ); + + pTexture->GetDesc( &desc ); + + ComPtr d3dDevice; + pContext->GetDevice( d3dDevice.GetAddressOf() ); + + if ( desc.SampleDesc.Count > 1 ) + { + // MSAA content must be resolved before being copied to a staging texture + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + + ComPtr pTemp; + hr = d3dDevice->CreateTexture2D( &desc, 0, pTemp.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + assert( pTemp ); + + DXGI_FORMAT fmt = EnsureNotTypeless( desc.Format ); + + UINT support = 0; + hr = d3dDevice->CheckFormatSupport( fmt, &support ); + if ( FAILED(hr) ) + return hr; + + if ( !(support & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE) ) + return E_FAIL; + + for( UINT item = 0; item < desc.ArraySize; ++item ) + { + for( UINT level = 0; level < desc.MipLevels; ++level ) + { + UINT index = D3D11CalcSubresource( level, item, desc.MipLevels ); + pContext->ResolveSubresource( pTemp.Get(), index, pSource, index, fmt ); + } + } + + desc.BindFlags = 0; + desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + desc.Usage = D3D11_USAGE_STAGING; + + hr = d3dDevice->CreateTexture2D(&desc, 0, pStaging.ReleaseAndGetAddressOf()); + if ( FAILED(hr) ) + return hr; + + assert( pStaging ); + + pContext->CopyResource( pStaging.Get(), pTemp.Get() ); + } + else if ( (desc.Usage == D3D11_USAGE_STAGING) && (desc.CPUAccessFlags & D3D11_CPU_ACCESS_READ) ) + { + // Handle case where the source is already a staging texture we can use directly + pStaging = pTexture; + } + else + { + // Otherwise, create a staging texture from the non-MSAA source + desc.BindFlags = 0; + desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + desc.Usage = D3D11_USAGE_STAGING; + + hr = d3dDevice->CreateTexture2D(&desc, 0, pStaging.ReleaseAndGetAddressOf()); + if ( FAILED(hr) ) + return hr; + + assert( pStaging ); + + pContext->CopyResource( pStaging.Get(), pSource ); + } + + return S_OK; + } + + //-------------------------------------------------------------------------------------- + bool g_WIC2 = false; + + IWICImagingFactory* _GetWIC() + { + static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; + + IWICImagingFactory* factory = nullptr; + InitOnceExecuteOnce(&s_initOnce, + [](PINIT_ONCE, PVOID, LPVOID *ifactory) -> BOOL + { + #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + HRESULT hr = CoCreateInstance( + CLSID_WICImagingFactory2, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory2), + ifactory + ); + + if ( SUCCEEDED(hr) ) + { + // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed + g_WIC2 = true; + return TRUE; + } + else + { + hr = CoCreateInstance( + CLSID_WICImagingFactory1, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + ifactory + ); + return SUCCEEDED(hr) ? TRUE : FALSE; + } + #else + return SUCCEEDED( CoCreateInstance( + CLSID_WICImagingFactory, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + ifactory) ) ? TRUE : FALSE; + #endif + }, nullptr, reinterpret_cast(&factory)); + + return factory; + } +} // anonymous namespace + + +//-------------------------------------------------------------------------------------- +HRESULT DirectX::SaveDDSTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_z_ const wchar_t* fileName ) +{ + if ( !fileName ) + return E_INVALIDARG; + + D3D11_TEXTURE2D_DESC desc = {}; + ComPtr pStaging; + HRESULT hr = CaptureTexture( pContext, pSource, desc, pStaging ); + if ( FAILED(hr) ) + return hr; + + // Create file +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) + ScopedHandle hFile( safe_handle( CreateFile2( fileName, GENERIC_WRITE | DELETE, 0, CREATE_ALWAYS, nullptr ) ) ); +#else + ScopedHandle hFile( safe_handle( CreateFileW( fileName, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, 0, nullptr ) ) ); +#endif + if ( !hFile ) + return HRESULT_FROM_WIN32( GetLastError() ); + + auto_delete_file delonfail(hFile.get()); + + // Setup header + const size_t MAX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10); + uint8_t fileHeader[ MAX_HEADER_SIZE ]; + + *reinterpret_cast(&fileHeader[0]) = DDS_MAGIC; + + auto header = reinterpret_cast( &fileHeader[0] + sizeof(uint32_t) ); + size_t headerSize = sizeof(uint32_t) + sizeof(DDS_HEADER); + memset( header, 0, sizeof(DDS_HEADER) ); + 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; + + // 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_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R16G16_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R16_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_L16, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_L8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_A8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC1_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC2_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DXT3, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC3_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DXT5, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC4_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC4_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC5_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC5_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_B5G6R5_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R16G16_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.1 + case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.1 + case DXGI_FORMAT_YUY2: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.2 + case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy_s( &header->ddspf, sizeof(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_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + case DXGI_FORMAT_A8P8: + return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); + + default: + memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DX10, sizeof(DDS_PIXELFORMAT) ); + + headerSize += sizeof(DDS_HEADER_DXT10); + extHeader = reinterpret_cast( reinterpret_cast(&fileHeader[0]) + sizeof(uint32_t) + sizeof(DDS_HEADER) ); + memset( extHeader, 0, sizeof(DDS_HEADER_DXT10) ); + extHeader->dxgiFormat = desc.Format; + extHeader->resourceDimension = D3D11_RESOURCE_DIMENSION_TEXTURE2D; + extHeader->arraySize = 1; + break; + } + + size_t rowPitch, slicePitch, rowCount; + GetSurfaceInfo( desc.Width, desc.Height, desc.Format, &slicePitch, &rowPitch, &rowCount ); + + if ( IsCompressed( desc.Format ) ) + { + header->flags |= DDS_HEADER_FLAGS_LINEARSIZE; + header->pitchOrLinearSize = static_cast( slicePitch ); + } + else + { + header->flags |= DDS_HEADER_FLAGS_PITCH; + header->pitchOrLinearSize = static_cast( rowPitch ); + } + + // Setup pixels + std::unique_ptr pixels( new (std::nothrow) uint8_t[ slicePitch ] ); + if (!pixels) + return E_OUTOFMEMORY; + + D3D11_MAPPED_SUBRESOURCE mapped; + hr = pContext->Map( pStaging.Get(), 0, D3D11_MAP_READ, 0, &mapped ); + if ( FAILED(hr) ) + return hr; + + auto sptr = reinterpret_cast( mapped.pData ); + if ( !sptr ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return E_POINTER; + } + + uint8_t* dptr = pixels.get(); + + size_t msize = std::min( rowPitch, mapped.RowPitch ); + for( size_t h = 0; h < rowCount; ++h ) + { + memcpy_s( dptr, rowPitch, sptr, msize ); + sptr += mapped.RowPitch; + dptr += rowPitch; + } + + pContext->Unmap( pStaging.Get(), 0 ); + + // Write header & pixels + DWORD bytesWritten; + if ( !WriteFile( hFile.get(), fileHeader, static_cast( headerSize ), &bytesWritten, nullptr ) ) + return HRESULT_FROM_WIN32( GetLastError() ); + + if ( bytesWritten != headerSize ) + return E_FAIL; + + if ( !WriteFile( hFile.get(), pixels.get(), static_cast( slicePitch ), &bytesWritten, nullptr ) ) + return HRESULT_FROM_WIN32( GetLastError() ); + + if ( bytesWritten != slicePitch ) + return E_FAIL; + + delonfail.clear(); + + return S_OK; +} + +//-------------------------------------------------------------------------------------- +HRESULT DirectX::SaveWICTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_ REFGUID guidContainerFormat, + _In_z_ const wchar_t* fileName, + _In_opt_ const GUID* targetFormat, + _In_opt_ std::function setCustomProps ) +{ + if ( !fileName ) + return E_INVALIDARG; + + D3D11_TEXTURE2D_DESC desc = {}; + ComPtr pStaging; + HRESULT hr = CaptureTexture( pContext, pSource, desc, pStaging ); + if ( FAILED(hr) ) + return hr; + + // Determine source format's WIC equivalent + WICPixelFormatGUID pfGuid; + bool sRGB = false; + 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_R8G8B8A8_UNORM_SRGB: + pfGuid = GUID_WICPixelFormat32bppRGBA; + sRGB = true; + break; + + case DXGI_FORMAT_B8G8R8A8_UNORM: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGRA; + break; + + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGRA; + sRGB = true; + break; + + case DXGI_FORMAT_B8G8R8X8_UNORM: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGR; + break; + + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGR; + sRGB = true; + break; + + default: + return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); + } + + auto pWIC = _GetWIC(); + if ( !pWIC ) + return E_NOINTERFACE; + + ComPtr stream; + hr = pWIC->CreateStream( stream.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + hr = stream->InitializeFromFilename( fileName, GENERIC_WRITE ); + if ( FAILED(hr) ) + return hr; + + auto_delete_file_wic delonfail(stream, fileName); + + ComPtr encoder; + hr = pWIC->CreateEncoder( guidContainerFormat, nullptr, encoder.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + hr = encoder->Initialize( stream.Get(), WICBitmapEncoderNoCache ); + if ( FAILED(hr) ) + return hr; + + ComPtr frame; + ComPtr props; + hr = encoder->CreateNewFrame( frame.GetAddressOf(), props.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + if ( targetFormat && memcmp( &guidContainerFormat, &GUID_ContainerFormatBmp, sizeof(WICPixelFormatGUID) ) == 0 && g_WIC2 ) + { + // Opt-in to the WIC2 support for writing 32-bit Windows BMP files with an alpha channel + PROPBAG2 option = {}; + option.pstrName = const_cast(L"EnableV5Header32bppBGRA"); + + VARIANT varValue; + varValue.vt = VT_BOOL; + varValue.boolVal = VARIANT_TRUE; + (void)props->Write( 1, &option, &varValue ); + } + + if ( setCustomProps ) + { + setCustomProps( props.Get() ); + } + + hr = frame->Initialize( props.Get() ); + if ( FAILED(hr) ) + return hr; + + hr = frame->SetSize( desc.Width , desc.Height ); + if ( FAILED(hr) ) + return hr; + + hr = frame->SetResolution( 72, 72 ); + if ( FAILED(hr) ) + return hr; + + // Pick a target format + WICPixelFormatGUID targetGuid; + if ( targetFormat ) + { + targetGuid = *targetFormat; + } + else + { + // Screenshots don’t typically include the alpha channel of the render target + switch ( desc.Format ) + { +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + if ( g_WIC2 ) + { + targetGuid = GUID_WICPixelFormat96bppRGBFloat; + } + else + { + targetGuid = GUID_WICPixelFormat24bppBGR; + } + break; +#endif + + case DXGI_FORMAT_R16G16B16A16_UNORM: targetGuid = GUID_WICPixelFormat48bppBGR; break; + case DXGI_FORMAT_B5G5R5A1_UNORM: targetGuid = GUID_WICPixelFormat16bppBGR555; break; + case DXGI_FORMAT_B5G6R5_UNORM: targetGuid = GUID_WICPixelFormat16bppBGR565; break; + + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_A8_UNORM: + targetGuid = GUID_WICPixelFormat8bppGray; + break; + + default: + targetGuid = GUID_WICPixelFormat24bppBGR; + break; + } + } + + hr = frame->SetPixelFormat( &targetGuid ); + if ( FAILED(hr) ) + return hr; + + if ( targetFormat && memcmp( targetFormat, &targetGuid, sizeof(WICPixelFormatGUID) ) != 0 ) + { + // Requested output pixel format is not supported by the WIC codec + return E_FAIL; + } + + // Encode WIC metadata + ComPtr metawriter; + if ( SUCCEEDED( frame->GetMetadataQueryWriter( metawriter.GetAddressOf() ) ) ) + { + PROPVARIANT value; + PropVariantInit( &value ); + + value.vt = VT_LPSTR; + value.pszVal = const_cast("DirectXTK"); + + if ( memcmp( &guidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID) ) == 0 ) + { + // Set Software name + (void)metawriter->SetMetadataByName( L"/tEXt/{str=Software}", &value ); + + // Set sRGB chunk + if (sRGB) + { + value.vt = VT_UI1; + value.bVal = 0; + (void)metawriter->SetMetadataByName(L"/sRGB/RenderingIntent", &value); + } + else + { + // add gAMA chunk with gamma 1.0 + value.vt = VT_UI4; + value.uintVal = 100000; // gama value * 100,000 -- i.e. gamma 1.0 + (void)metawriter->SetMetadataByName(L"/gAMA/ImageGamma", &value); + + // remove sRGB chunk which is added by default. + (void)metawriter->RemoveMetadataByName(L"/sRGB/RenderingIntent"); + } + } + else + { + // Set Software name + (void)metawriter->SetMetadataByName( L"System.ApplicationName", &value ); + + if ( sRGB ) + { + // Set EXIF Colorspace of sRGB + value.vt = VT_UI2; + value.uiVal = 1; + (void)metawriter->SetMetadataByName( L"System.Image.ColorSpace", &value ); + } + } + } + + D3D11_MAPPED_SUBRESOURCE mapped; + hr = pContext->Map( pStaging.Get(), 0, D3D11_MAP_READ, 0, &mapped ); + if ( FAILED(hr) ) + return hr; + + if ( memcmp( &targetGuid, &pfGuid, sizeof(WICPixelFormatGUID) ) != 0 ) + { + // Conversion required to write + ComPtr source; + hr = pWIC->CreateBitmapFromMemory( desc.Width, desc.Height, pfGuid, + mapped.RowPitch, mapped.RowPitch * desc.Height, + reinterpret_cast( mapped.pData ), source.GetAddressOf() ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + + ComPtr FC; + hr = pWIC->CreateFormatConverter( FC.GetAddressOf() ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + + BOOL canConvert = FALSE; + hr = FC->CanConvert( pfGuid, targetGuid, &canConvert ); + if ( FAILED(hr) || !canConvert ) + { + return E_UNEXPECTED; + } + + hr = FC->Initialize( source.Get(), targetGuid, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeMedianCut ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + + WICRect rect = { 0, 0, static_cast( desc.Width ), static_cast( desc.Height ) }; + hr = frame->WriteSource( FC.Get(), &rect ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + } + else + { + // No conversion required + hr = frame->WritePixels( desc.Height, mapped.RowPitch, mapped.RowPitch * desc.Height, reinterpret_cast( mapped.pData ) ); + if ( FAILED(hr) ) + return hr; + } + + pContext->Unmap( pStaging.Get(), 0 ); + + hr = frame->Commit(); + if ( FAILED(hr) ) + return hr; + + hr = encoder->Commit(); + if ( FAILED(hr) ) + return hr; + + delonfail.clear(); + + return S_OK; +} diff --git a/FriedLiver/Source/DXUT/Core/ScreenGrab.h b/FriedLiver/Source/DXUT/Core/ScreenGrab.h new file mode 100644 index 00000000..1f185394 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/ScreenGrab.h @@ -0,0 +1,39 @@ +//-------------------------------------------------------------------------------------- +// File: ScreenGrab.h +// +// Function for capturing a 2D texture and saving it to a file (aka a 'screenshot' +// when used on a Direct3D 11 Render Target). +// +// Note these functions are useful as a light-weight runtime screen grabber. For +// full-featured texture capture, DDS writer, and texture processing pipeline, +// see the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#pragma once + +#include + +#include +#include +#include + + +namespace DirectX +{ + HRESULT SaveDDSTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_z_ const wchar_t* fileName ); + + HRESULT SaveWICTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_ REFGUID guidContainerFormat, + _In_z_ const wchar_t* fileName, + _In_opt_ const GUID* targetFormat = nullptr, + _In_opt_ std::function setCustomProps = nullptr ); +} \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/WICTextureLoader.cpp b/FriedLiver/Source/DXUT/Core/WICTextureLoader.cpp new file mode 100644 index 00000000..f74bee45 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/WICTextureLoader.cpp @@ -0,0 +1,932 @@ +//-------------------------------------------------------------------------------------- +// File: WICTextureLoader.cpp +// +// Function for loading a WIC image and creating a Direct3D runtime texture for it +// (auto-generating mipmaps if possible) +// +// Note: Assumes application has already called CoInitializeEx +// +// Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for +// auto-gen mipmap support. +// +// Note these functions are useful for images created as simple 2D textures. For +// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader. +// For a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#include "dxut.h" + +// We could load multi-frame images (TIFF/GIF) into a texture array. +// For now, we just load the first frame (note: DirectXTex supports multi-frame images) + +#include "WICTextureLoader.h" + +#include +#include + +#include + +#include + +#include +#include + +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#pragma comment(lib,"dxguid.lib") +#endif + +using namespace DirectX; +using Microsoft::WRL::ComPtr; + +namespace +{ + //-------------------------------------------------------------------------------------- + template + inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_ const char(&name)[TNameLength]) + { +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) + resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name); +#else + UNREFERENCED_PARAMETER(resource); + UNREFERENCED_PARAMETER(name); +#endif + } + + //------------------------------------------------------------------------------------- + // WIC Pixel Format Translation Data + //------------------------------------------------------------------------------------- + struct WICTranslate + { + GUID wic; + DXGI_FORMAT format; + }; + + const WICTranslate g_WICFormats[] = + { + { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, + + { 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_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_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 }, + }; + + //------------------------------------------------------------------------------------- + // WIC Pixel Format nearest conversion table + //------------------------------------------------------------------------------------- + + struct WICConvert + { + GUID source; + GUID target; + }; + + const 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_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_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT + { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT + + { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_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_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_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 + + #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + #endif + + // We don't support n-channel formats + }; + + bool g_WIC2 = false; + + //-------------------------------------------------------------------------------------- + IWICImagingFactory* _GetWIC() + { + static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; + + IWICImagingFactory* factory = nullptr; + InitOnceExecuteOnce(&s_initOnce, + [](PINIT_ONCE, PVOID, PVOID *ifactory) -> BOOL + { +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + HRESULT hr = CoCreateInstance( + CLSID_WICImagingFactory2, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory2), + ifactory + ); + + if (SUCCEEDED(hr)) + { + // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed + g_WIC2 = true; + return TRUE; + } + else + { + hr = CoCreateInstance( + CLSID_WICImagingFactory1, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + ifactory + ); + return SUCCEEDED(hr) ? TRUE : FALSE; + } +#else + return SUCCEEDED(CoCreateInstance( + CLSID_WICImagingFactory, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + ifactory)) ? TRUE : FALSE; +#endif + }, nullptr, reinterpret_cast(&factory)); + + return factory; + } + + //--------------------------------------------------------------------------------- + DXGI_FORMAT _WICToDXGI(const GUID& guid) + { + for (size_t i = 0; i < _countof(g_WICFormats); ++i) + { + if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0) + return g_WICFormats[i].format; + } + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if (g_WIC2) + { + if (memcmp(&GUID_WICPixelFormat96bppRGBFloat, &guid, sizeof(GUID)) == 0) + return DXGI_FORMAT_R32G32B32_FLOAT; + } +#endif + + return DXGI_FORMAT_UNKNOWN; + } + + //--------------------------------------------------------------------------------- + size_t _WICBitsPerPixel(REFGUID targetGuid) + { + auto pWIC = _GetWIC(); + if (!pWIC) + return 0; + + ComPtr cinfo; + if (FAILED(pWIC->CreateComponentInfo(targetGuid, cinfo.GetAddressOf()))) + return 0; + + WICComponentType type; + if (FAILED(cinfo->GetComponentType(&type))) + return 0; + + if (type != WICPixelFormat) + return 0; + + ComPtr pfinfo; + if (FAILED(cinfo.As(&pfinfo))) + return 0; + + UINT bpp; + if (FAILED(pfinfo->GetBitsPerPixel(&bpp))) + return 0; + + return bpp; + } + + + //-------------------------------------------------------------------------------------- + DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format) + { + switch (format) + { + 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_BC2_UNORM: + return DXGI_FORMAT_BC2_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_B8G8R8X8_UNORM: + return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + + case DXGI_FORMAT_BC7_UNORM: + return DXGI_FORMAT_BC7_UNORM_SRGB; + + default: + return format; + } + } + + + //--------------------------------------------------------------------------------- + HRESULT CreateTextureFromWIC(_In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_ IWICBitmapFrameDecode *frame, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) + { + UINT width, height; + HRESULT hr = frame->GetSize(&width, &height); + if (FAILED(hr)) + return hr; + + assert(width > 0 && height > 0); + + if (!maxsize) + { + // This is a bit conservative because the hardware could support larger textures than + // the Feature Level defined minimums, but doing it this way is much easier and more + // performant for WIC than the 'fail and retry' model used by DDSTextureLoader + + switch (d3dDevice->GetFeatureLevel()) + { + case D3D_FEATURE_LEVEL_9_1: + case D3D_FEATURE_LEVEL_9_2: + maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + case D3D_FEATURE_LEVEL_9_3: + maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + case D3D_FEATURE_LEVEL_10_0: + case D3D_FEATURE_LEVEL_10_1: + maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + default: + maxsize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; + break; + } + } + + assert(maxsize > 0); + + UINT twidth, theight; + if (width > maxsize || height > maxsize) + { + float ar = static_cast(height) / static_cast(width); + if (width > height) + { + 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)); + } + assert(twidth <= maxsize && theight <= maxsize); + } + else + { + twidth = width; + theight = height; + } + + // Determine format + WICPixelFormatGUID pixelFormat; + hr = frame->GetPixelFormat(&pixelFormat); + if (FAILED(hr)) + return hr; + + WICPixelFormatGUID convertGUID; + memcpy(&convertGUID, &pixelFormat, sizeof(WICPixelFormatGUID)); + + size_t bpp = 0; + + DXGI_FORMAT format = _WICToDXGI(pixelFormat); + if (format == DXGI_FORMAT_UNKNOWN) + { + if (memcmp(&GUID_WICPixelFormat96bppRGBFixedPoint, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) + { +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if (g_WIC2) + { + memcpy(&convertGUID, &GUID_WICPixelFormat96bppRGBFloat, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R32G32B32_FLOAT; + bpp = 96; + } + else +#endif + { + memcpy(&convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + bpp = 128; + } + } + else + { + for (size_t i = 0; i < _countof(g_WICConvert); ++i) + { + if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) + { + memcpy(&convertGUID, &g_WICConvert[i].target, sizeof(WICPixelFormatGUID)); + + format = _WICToDXGI(g_WICConvert[i].target); + assert(format != DXGI_FORMAT_UNKNOWN); + bpp = _WICBitsPerPixel(convertGUID); + break; + } + } + } + + if (format == DXGI_FORMAT_UNKNOWN) + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + else + { + bpp = _WICBitsPerPixel(pixelFormat); + } + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if ((format == DXGI_FORMAT_R32G32B32_FLOAT) && d3dContext != 0 && textureView != 0) + { + // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT + UINT fmtSupport = 0; + 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(&convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + bpp = 128; + } + } +#endif + + if (!bpp) + return E_FAIL; + + // Handle sRGB formats + if (loadFlags & WIC_LOADER_FORCE_SRGB) + { + format = MakeSRGB(format); + } + else if (!(loadFlags & WIC_LOADER_IGNORE_SRGB)) + { + ComPtr metareader; + if (SUCCEEDED(frame->GetMetadataQueryReader(metareader.GetAddressOf()))) + { + GUID containerFormat; + if (SUCCEEDED(metareader->GetContainerFormat(&containerFormat))) + { + // Check for sRGB colorspace metadata + bool sRGB = false; + + PROPVARIANT value; + PropVariantInit(&value); + + if (memcmp(&containerFormat, &GUID_ContainerFormatPng, sizeof(GUID)) == 0) + { + // Check for sRGB chunk + if (SUCCEEDED(metareader->GetMetadataByName(L"/sRGB/RenderingIntent", &value)) && value.vt == VT_UI1) + { + sRGB = true; + } + } + else if (SUCCEEDED(metareader->GetMetadataByName(L"System.Image.ColorSpace", &value)) && value.vt == VT_UI2 && value.uiVal == 1) + { + sRGB = true; + } + + (void)PropVariantClear(&value); + + if (sRGB) + format = MakeSRGB(format); + } + } + } + + // 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); + if (FAILED(hr) || !(support & D3D11_FORMAT_SUPPORT_TEXTURE2D)) + { + // Fallback to RGBA 32-bit format which is supported by all devices + memcpy(&convertGUID, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R8G8B8A8_UNORM; + bpp = 32; + } + + // Allocate temporary memory for image + size_t rowPitch = (twidth * bpp + 7) / 8; + size_t imageSize = rowPitch * theight; + + std::unique_ptr temp(new (std::nothrow) uint8_t[imageSize]); + if (!temp) + return E_OUTOFMEMORY; + + // Load image data + 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()); + if (FAILED(hr)) + return hr; + } + else if (twidth != width || theight != height) + { + // Resize + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + ComPtr scaler; + hr = pWIC->CreateBitmapScaler(scaler.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = scaler->Initialize(frame, twidth, theight, WICBitmapInterpolationModeFant); + if (FAILED(hr)) + return hr; + + WICPixelFormatGUID pfScaler; + hr = scaler->GetPixelFormat(&pfScaler); + if (FAILED(hr)) + return hr; + + if (memcmp(&convertGUID, &pfScaler, sizeof(GUID)) == 0) + { + // No format conversion needed + hr = scaler->CopyPixels(nullptr, static_cast(rowPitch), static_cast(imageSize), temp.get()); + if (FAILED(hr)) + return hr; + } + else + { + ComPtr FC; + hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); + if (FAILED(hr)) + return hr; + + BOOL canConvert = FALSE; + hr = FC->CanConvert(pfScaler, convertGUID, &canConvert); + if (FAILED(hr) || !canConvert) + { + return E_UNEXPECTED; + } + + hr = FC->Initialize(scaler.Get(), convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); + if (FAILED(hr)) + return hr; + + hr = FC->CopyPixels(nullptr, static_cast(rowPitch), static_cast(imageSize), temp.get()); + if (FAILED(hr)) + return hr; + } + } + else + { + // Format conversion but no resize + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + ComPtr FC; + hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); + if (FAILED(hr)) + return hr; + + BOOL canConvert = FALSE; + hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert); + if (FAILED(hr) || !canConvert) + { + return E_UNEXPECTED; + } + + hr = FC->Initialize(frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); + if (FAILED(hr)) + return hr; + + hr = FC->CopyPixels(nullptr, static_cast(rowPitch), static_cast(imageSize), temp.get()); + if (FAILED(hr)) + return hr; + } + + // See if format is supported for auto-gen mipmaps (varies by feature level) + bool autogen = false; + if (d3dContext != 0 && textureView != 0) // Must have context and shader-view to auto generate mipmaps + { + UINT fmtSupport = 0; + hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); + if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) + { + autogen = true; + } + } + + // Create texture + D3D11_TEXTURE2D_DESC desc; + desc.Width = twidth; + desc.Height = theight; + desc.MipLevels = (autogen) ? 0 : 1; + desc.ArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = usage; + desc.CPUAccessFlags = cpuAccessFlags; + + if (autogen) + { + desc.BindFlags = bindFlags | D3D11_BIND_RENDER_TARGET; + desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS; + } + else + { + desc.BindFlags = bindFlags; + desc.MiscFlags = miscFlags; + } + + D3D11_SUBRESOURCE_DATA initData; + initData.pSysMem = temp.get(); + initData.SysMemPitch = static_cast(rowPitch); + initData.SysMemSlicePitch = static_cast(imageSize); + + ID3D11Texture2D* tex = nullptr; + hr = d3dDevice->CreateTexture2D(&desc, (autogen) ? nullptr : &initData, &tex); + if (SUCCEEDED(hr) && tex != 0) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = desc.Format; + + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = (autogen) ? -1 : 1; + + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + + if (autogen) + { + assert(d3dContext != 0); + d3dContext->UpdateSubresource(tex, 0, nullptr, temp.get(), static_cast(rowPitch), static_cast(imageSize)); + d3dContext->GenerateMips(*textureView); + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "WICTextureLoader"); + tex->Release(); + } + } + + return hr; + } +} // anonymous namespace + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, + const uint8_t* wicData, + size_t wicDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromMemoryEx(d3dDevice, nullptr, wicData, wicDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* wicData, + size_t wicDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromMemoryEx(d3dDevice, d3dContext, wicData, wicDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + 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, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + return CreateWICTextureFromMemoryEx(d3dDevice, nullptr, wicData, wicDataSize, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + + if (!d3dDevice || !wicData || (!texture && !textureView)) + return E_INVALIDARG; + + if (!wicDataSize) + return E_FAIL; + + if (wicDataSize > UINT32_MAX) + return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + // Create input stream for memory + ComPtr stream; + HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = stream->InitializeFromMemory(const_cast(wicData), static_cast(wicDataSize)); + if (FAILED(hr)) + return hr; + + // Initialize WIC + ComPtr decoder; + hr = pWIC->CreateDecoderFromStream(stream.Get(), nullptr, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); + if (FAILED(hr)) + return hr; + + ComPtr frame; + hr = decoder->GetFrame(0, frame.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = CreateTextureFromWIC(d3dDevice, d3dContext, frame.Get(), maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); + if (FAILED(hr)) + return hr; + + if (texture != 0 && *texture != 0) + { + SetDebugObjectName(*texture, "WICTextureLoader"); + } + + if (textureView != 0 && *textureView != 0) + { + SetDebugObjectName(*textureView, "WICTextureLoader"); + } + + return hr; +} + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromFileEx(d3dDevice, d3dContext, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + 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, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + return CreateWICTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + + if (!d3dDevice || !fileName || (!texture && !textureView)) + return E_INVALIDARG; + + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + // Initialize WIC + ComPtr decoder; + HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); + if (FAILED(hr)) + return hr; + + ComPtr frame; + hr = decoder->GetFrame(0, frame.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = CreateTextureFromWIC(d3dDevice, d3dContext, frame.Get(), maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); + +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) + if (SUCCEEDED(hr)) + { + if (texture != 0 || textureView != 0) + { + char strFileA[MAX_PATH]; + int result = WideCharToMultiByte(CP_ACP, + WC_NO_BEST_FIT_CHARS, + fileName, + -1, + strFileA, + MAX_PATH, + nullptr, + FALSE + ); + if (result > 0) + { + const char* pstrName = strrchr(strFileA, '\\'); + if (!pstrName) + { + pstrName = strFileA; + } + else + { + pstrName++; + } + + if (texture != 0 && *texture != 0) + { + (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + + if (textureView != 0 && *textureView != 0) + { + (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + } + } + } +#endif + + return hr; +} diff --git a/FriedLiver/Source/DXUT/Core/WICTextureLoader.h b/FriedLiver/Source/DXUT/Core/WICTextureLoader.h new file mode 100644 index 00000000..8843c337 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/WICTextureLoader.h @@ -0,0 +1,126 @@ +//-------------------------------------------------------------------------------------- +// File: WICTextureLoader.h +// +// Function for loading a WIC image and creating a Direct3D runtime texture for it +// (auto-generating mipmaps if possible) +// +// Note: Assumes application has already called CoInitializeEx +// +// Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for +// auto-gen mipmap support. +// +// Note these functions are useful for images created as simple 2D textures. For +// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader. +// For a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#pragma once + +#include +#include + + +namespace DirectX +{ + enum WIC_LOADER_FLAGS + { + WIC_LOADER_DEFAULT = 0, + WIC_LOADER_FORCE_SRGB = 0x1, + WIC_LOADER_IGNORE_SRGB = 0x2, + }; + + // Standard version + HRESULT 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); + + HRESULT CreateWICTextureFromFile( + _In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0); + + // Standard version with optional auto-gen mipmap support + HRESULT CreateWICTextureFromMemory( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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); + + HRESULT CreateWICTextureFromFile( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0); + + // Extended version + HRESULT 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_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); + + HRESULT 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_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); + + // Extended version with optional auto-gen mipmap support + HRESULT CreateWICTextureFromMemoryEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); + + HRESULT CreateWICTextureFromFileEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _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_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); +} \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/dxerr.cpp b/FriedLiver/Source/DXUT/Core/dxerr.cpp new file mode 100644 index 00000000..4b56fa9e --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/dxerr.cpp @@ -0,0 +1,3655 @@ +//-------------------------------------------------------------------------------------- +// File: DXErr.cpp +// +// DirectX Error Library +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +//-------------------------------------------------------------------------------------- +#include "dxut.h" + +// This version only supports UNICODE. + +#include "dxerr.h" + +#include + +#include +#include +#include +#include +#include +#include + +#define XAUDIO2_E_INVALID_CALL 0x88960001 +#define XAUDIO2_E_XMA_DECODER_ERROR 0x88960002 +#define XAUDIO2_E_XAPO_CREATION_FAILED 0x88960003 +#define XAUDIO2_E_DEVICE_INVALIDATED 0x88960004 + +#define XAPO_E_FORMAT_UNSUPPORTED MAKE_HRESULT(SEVERITY_ERROR, 0x897, 0x01) + +#define DXUTERR_NODIRECT3D MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0901) +#define DXUTERR_NOCOMPATIBLEDEVICES MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0902) +#define DXUTERR_MEDIANOTFOUND MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0903) +#define DXUTERR_NONZEROREFCOUNT MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0904) +#define DXUTERR_CREATINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0905) +#define DXUTERR_RESETTINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0906) +#define DXUTERR_CREATINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0907) +#define DXUTERR_RESETTINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0908) +#define DXUTERR_INCORRECTVERSION MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0909) +#define DXUTERR_DEVICEREMOVED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090A) + +//----------------------------------------------------------------------------- +#define BUFFER_SIZE 3000 + +#pragma warning( disable : 6001 6221 ) + +//-------------------------------------------------------------------------------------- +#define CHK_ERR(hrchk, strOut) \ + case hrchk: \ + return L##strOut; + +#define CHK_ERRA(hrchk) \ + case hrchk: \ + return L#hrchk; + +#define HRESULT_FROM_WIN32b(x) ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : ((HRESULT) (((x) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000))) + +#define CHK_ERR_WIN32A(hrchk) \ + case HRESULT_FROM_WIN32b(hrchk): \ + case hrchk: \ + return L#hrchk; + +#define CHK_ERR_WIN32_ONLY(hrchk, strOut) \ + case HRESULT_FROM_WIN32b(hrchk): \ + return L##strOut; + +//----------------------------------------------------- +const WCHAR* WINAPI DXGetErrorStringW( _In_ HRESULT hr ) +{ + switch(hr) + { +// Commmented out codes are actually alises for other codes + +// ------------------------------------------------------------- +// Common Win32 error codes +// ------------------------------------------------------------- + CHK_ERRA(S_OK) + CHK_ERRA(S_FALSE) + + CHK_ERRA(E_UNEXPECTED) + CHK_ERRA(E_NOTIMPL) + CHK_ERRA(E_OUTOFMEMORY) + CHK_ERRA(E_INVALIDARG) + CHK_ERRA(E_NOINTERFACE) + CHK_ERRA(E_POINTER) + CHK_ERRA(E_HANDLE) + CHK_ERRA(E_ABORT) + CHK_ERRA(E_FAIL) + CHK_ERRA(E_ACCESSDENIED) + CHK_ERRA(E_PENDING) + CHK_ERRA(CO_E_INIT_TLS) + CHK_ERRA(CO_E_INIT_SHARED_ALLOCATOR) + CHK_ERRA(CO_E_INIT_MEMORY_ALLOCATOR) + CHK_ERRA(CO_E_INIT_CLASS_CACHE) + CHK_ERRA(CO_E_INIT_RPC_CHANNEL) + CHK_ERRA(CO_E_INIT_TLS_SET_CHANNEL_CONTROL) + CHK_ERRA(CO_E_INIT_TLS_CHANNEL_CONTROL) + CHK_ERRA(CO_E_INIT_UNACCEPTED_USER_ALLOCATOR) + CHK_ERRA(CO_E_INIT_SCM_MUTEX_EXISTS) + CHK_ERRA(CO_E_INIT_SCM_FILE_MAPPING_EXISTS) + CHK_ERRA(CO_E_INIT_SCM_MAP_VIEW_OF_FILE) + CHK_ERRA(CO_E_INIT_SCM_EXEC_FAILURE) + CHK_ERRA(CO_E_INIT_ONLY_SINGLE_THREADED) + CHK_ERRA(CO_E_CANT_REMOTE) + CHK_ERRA(CO_E_BAD_SERVER_NAME) + CHK_ERRA(CO_E_WRONG_SERVER_IDENTITY) + CHK_ERRA(CO_E_OLE1DDE_DISABLED) + CHK_ERRA(CO_E_RUNAS_SYNTAX) + CHK_ERRA(CO_E_CREATEPROCESS_FAILURE) + CHK_ERRA(CO_E_RUNAS_CREATEPROCESS_FAILURE) + CHK_ERRA(CO_E_RUNAS_LOGON_FAILURE) + CHK_ERRA(CO_E_LAUNCH_PERMSSION_DENIED) + CHK_ERRA(CO_E_START_SERVICE_FAILURE) + CHK_ERRA(CO_E_REMOTE_COMMUNICATION_FAILURE) + CHK_ERRA(CO_E_SERVER_START_TIMEOUT) + CHK_ERRA(CO_E_CLSREG_INCONSISTENT) + CHK_ERRA(CO_E_IIDREG_INCONSISTENT) + CHK_ERRA(CO_E_NOT_SUPPORTED) + CHK_ERRA(CO_E_RELOAD_DLL) + CHK_ERRA(CO_E_MSI_ERROR) + CHK_ERRA(OLE_E_FIRST) + CHK_ERRA(OLE_E_LAST) + CHK_ERRA(OLE_S_FIRST) + CHK_ERRA(OLE_S_LAST) +// CHK_ERRA(OLE_E_OLEVERB) + CHK_ERRA(OLE_E_ADVF) + CHK_ERRA(OLE_E_ENUM_NOMORE) + CHK_ERRA(OLE_E_ADVISENOTSUPPORTED) + CHK_ERRA(OLE_E_NOCONNECTION) + CHK_ERRA(OLE_E_NOTRUNNING) + CHK_ERRA(OLE_E_NOCACHE) + CHK_ERRA(OLE_E_BLANK) + CHK_ERRA(OLE_E_CLASSDIFF) + CHK_ERRA(OLE_E_CANT_GETMONIKER) + CHK_ERRA(OLE_E_CANT_BINDTOSOURCE) + CHK_ERRA(OLE_E_STATIC) + CHK_ERRA(OLE_E_PROMPTSAVECANCELLED) + CHK_ERRA(OLE_E_INVALIDRECT) + CHK_ERRA(OLE_E_WRONGCOMPOBJ) + CHK_ERRA(OLE_E_INVALIDHWND) + CHK_ERRA(OLE_E_NOT_INPLACEACTIVE) + CHK_ERRA(OLE_E_CANTCONVERT) + CHK_ERRA(OLE_E_NOSTORAGE) + CHK_ERRA(DV_E_FORMATETC) + CHK_ERRA(DV_E_DVTARGETDEVICE) + CHK_ERRA(DV_E_STGMEDIUM) + CHK_ERRA(DV_E_STATDATA) + CHK_ERRA(DV_E_LINDEX) + CHK_ERRA(DV_E_TYMED) + CHK_ERRA(DV_E_CLIPFORMAT) + CHK_ERRA(DV_E_DVASPECT) + CHK_ERRA(DV_E_DVTARGETDEVICE_SIZE) + CHK_ERRA(DV_E_NOIVIEWOBJECT) + CHK_ERRA(DRAGDROP_E_FIRST) + CHK_ERRA(DRAGDROP_E_LAST) + CHK_ERRA(DRAGDROP_S_FIRST) + CHK_ERRA(DRAGDROP_S_LAST) +// CHK_ERRA(DRAGDROP_E_NOTREGISTERED) + CHK_ERRA(DRAGDROP_E_ALREADYREGISTERED) + CHK_ERRA(DRAGDROP_E_INVALIDHWND) + CHK_ERRA(CLASSFACTORY_E_FIRST) + CHK_ERRA(CLASSFACTORY_E_LAST) + CHK_ERRA(CLASSFACTORY_S_FIRST) + CHK_ERRA(CLASSFACTORY_S_LAST) +// CHK_ERRA(CLASS_E_NOAGGREGATION) + CHK_ERRA(CLASS_E_CLASSNOTAVAILABLE) + CHK_ERRA(CLASS_E_NOTLICENSED) + CHK_ERRA(MARSHAL_E_FIRST) + CHK_ERRA(MARSHAL_E_LAST) + CHK_ERRA(MARSHAL_S_FIRST) + CHK_ERRA(MARSHAL_S_LAST) + CHK_ERRA(DATA_E_FIRST) + CHK_ERRA(DATA_E_LAST) + CHK_ERRA(DATA_S_FIRST) + CHK_ERRA(DATA_S_LAST) + CHK_ERRA(VIEW_E_FIRST) + CHK_ERRA(VIEW_E_LAST) + CHK_ERRA(VIEW_S_FIRST) + CHK_ERRA(VIEW_S_LAST) +// CHK_ERRA(VIEW_E_DRAW) + CHK_ERRA(REGDB_E_FIRST) + CHK_ERRA(REGDB_E_LAST) + CHK_ERRA(REGDB_S_FIRST) + CHK_ERRA(REGDB_S_LAST) +// CHK_ERRA(REGDB_E_READREGDB) + CHK_ERRA(REGDB_E_WRITEREGDB) + CHK_ERRA(REGDB_E_KEYMISSING) + CHK_ERRA(REGDB_E_INVALIDVALUE) + CHK_ERRA(REGDB_E_CLASSNOTREG) + CHK_ERRA(REGDB_E_IIDNOTREG) + CHK_ERRA(CAT_E_FIRST) + CHK_ERRA(CAT_E_LAST) +// CHK_ERRA(CAT_E_CATIDNOEXIST) +// CHK_ERRA(CAT_E_NODESCRIPTION) + CHK_ERRA(CS_E_FIRST) + CHK_ERRA(CS_E_LAST) +// CHK_ERRA(CS_E_PACKAGE_NOTFOUND) + CHK_ERRA(CS_E_NOT_DELETABLE) + CHK_ERRA(CS_E_CLASS_NOTFOUND) + CHK_ERRA(CS_E_INVALID_VERSION) + CHK_ERRA(CS_E_NO_CLASSSTORE) + CHK_ERRA(CS_E_OBJECT_NOTFOUND) + CHK_ERRA(CS_E_OBJECT_ALREADY_EXISTS) + CHK_ERRA(CS_E_INVALID_PATH) + CHK_ERRA(CS_E_NETWORK_ERROR) + CHK_ERRA(CS_E_ADMIN_LIMIT_EXCEEDED) + CHK_ERRA(CS_E_SCHEMA_MISMATCH) +// CHK_ERRA(CS_E_INTERNAL_ERROR) + CHK_ERRA(CACHE_E_FIRST) + CHK_ERRA(CACHE_E_LAST) + CHK_ERRA(CACHE_S_FIRST) + CHK_ERRA(CACHE_S_LAST) +// CHK_ERRA(CACHE_E_NOCACHE_UPDATED) + CHK_ERRA(OLEOBJ_E_FIRST) + CHK_ERRA(OLEOBJ_E_LAST) + CHK_ERRA(OLEOBJ_S_FIRST) + CHK_ERRA(OLEOBJ_S_LAST) +// CHK_ERRA(OLEOBJ_E_NOVERBS) + CHK_ERRA(OLEOBJ_E_INVALIDVERB) + CHK_ERRA(CLIENTSITE_E_FIRST) + CHK_ERRA(CLIENTSITE_E_LAST) + CHK_ERRA(CLIENTSITE_S_FIRST) + CHK_ERRA(CLIENTSITE_S_LAST) + CHK_ERRA(INPLACE_E_NOTUNDOABLE) + CHK_ERRA(INPLACE_E_NOTOOLSPACE) +// CHK_ERRA(INPLACE_E_FIRST) + CHK_ERRA(INPLACE_E_LAST) + CHK_ERRA(INPLACE_S_FIRST) + CHK_ERRA(INPLACE_S_LAST) + CHK_ERRA(ENUM_E_FIRST) + CHK_ERRA(ENUM_E_LAST) + CHK_ERRA(ENUM_S_FIRST) + CHK_ERRA(ENUM_S_LAST) + CHK_ERRA(CONVERT10_E_FIRST) + CHK_ERRA(CONVERT10_E_LAST) + CHK_ERRA(CONVERT10_S_FIRST) + CHK_ERRA(CONVERT10_S_LAST) +// CHK_ERRA(CONVERT10_E_OLESTREAM_GET) + CHK_ERRA(CONVERT10_E_OLESTREAM_PUT) + CHK_ERRA(CONVERT10_E_OLESTREAM_FMT) + CHK_ERRA(CONVERT10_E_OLESTREAM_BITMAP_TO_DIB) + CHK_ERRA(CONVERT10_E_STG_FMT) + CHK_ERRA(CONVERT10_E_STG_NO_STD_STREAM) + CHK_ERRA(CONVERT10_E_STG_DIB_TO_BITMAP) + CHK_ERRA(CLIPBRD_E_FIRST) + CHK_ERRA(CLIPBRD_E_LAST) + CHK_ERRA(CLIPBRD_S_FIRST) + CHK_ERRA(CLIPBRD_S_LAST) +// CHK_ERRA(CLIPBRD_E_CANT_OPEN) + CHK_ERRA(CLIPBRD_E_CANT_EMPTY) + CHK_ERRA(CLIPBRD_E_CANT_SET) + CHK_ERRA(CLIPBRD_E_BAD_DATA) + CHK_ERRA(CLIPBRD_E_CANT_CLOSE) + CHK_ERRA(MK_E_FIRST) + CHK_ERRA(MK_E_LAST) + CHK_ERRA(MK_S_FIRST) + CHK_ERRA(MK_S_LAST) +// CHK_ERRA(MK_E_CONNECTMANUALLY) + CHK_ERRA(MK_E_EXCEEDEDDEADLINE) + CHK_ERRA(MK_E_NEEDGENERIC) + CHK_ERRA(MK_E_UNAVAILABLE) + CHK_ERRA(MK_E_SYNTAX) + CHK_ERRA(MK_E_NOOBJECT) + CHK_ERRA(MK_E_INVALIDEXTENSION) + CHK_ERRA(MK_E_INTERMEDIATEINTERFACENOTSUPPORTED) + CHK_ERRA(MK_E_NOTBINDABLE) + CHK_ERRA(MK_E_NOTBOUND) + CHK_ERRA(MK_E_CANTOPENFILE) + CHK_ERRA(MK_E_MUSTBOTHERUSER) + CHK_ERRA(MK_E_NOINVERSE) + CHK_ERRA(MK_E_NOSTORAGE) + CHK_ERRA(MK_E_NOPREFIX) +// CHK_ERRA(MK_E_ENUMERATION_FAILED) + CHK_ERRA(CO_E_NOTINITIALIZED) + CHK_ERRA(CO_E_ALREADYINITIALIZED) + CHK_ERRA(CO_E_CANTDETERMINECLASS) + CHK_ERRA(CO_E_CLASSSTRING) + CHK_ERRA(CO_E_IIDSTRING) + CHK_ERRA(CO_E_APPNOTFOUND) + CHK_ERRA(CO_E_APPSINGLEUSE) + CHK_ERRA(CO_E_ERRORINAPP) + CHK_ERRA(CO_E_DLLNOTFOUND) + CHK_ERRA(CO_E_ERRORINDLL) + CHK_ERRA(CO_E_WRONGOSFORAPP) + CHK_ERRA(CO_E_OBJNOTREG) + CHK_ERRA(CO_E_OBJISREG) + CHK_ERRA(CO_E_OBJNOTCONNECTED) + CHK_ERRA(CO_E_APPDIDNTREG) + CHK_ERRA(CO_E_RELEASED) +// CHK_ERRA(OLE_S_USEREG) + CHK_ERRA(OLE_S_STATIC) + CHK_ERRA(OLE_S_MAC_CLIPFORMAT) +// CHK_ERRA(DRAGDROP_S_DROP) + CHK_ERRA(DRAGDROP_S_CANCEL) + CHK_ERRA(DRAGDROP_S_USEDEFAULTCURSORS) +// CHK_ERRA(DATA_S_SAMEFORMATETC) +// CHK_ERRA(VIEW_S_ALREADY_FROZEN) +// CHK_ERRA(CACHE_S_FORMATETC_NOTSUPPORTED) + CHK_ERRA(CACHE_S_SAMECACHE) + CHK_ERRA(CACHE_S_SOMECACHES_NOTUPDATED) +// CHK_ERRA(OLEOBJ_S_INVALIDVERB) + CHK_ERRA(OLEOBJ_S_CANNOT_DOVERB_NOW) + CHK_ERRA(OLEOBJ_S_INVALIDHWND) +// CHK_ERRA(INPLACE_S_TRUNCATED) +// CHK_ERRA(CONVERT10_S_NO_PRESENTATION) + CHK_ERRA(MK_S_REDUCED_TO_SELF) + CHK_ERRA(MK_S_ME) + CHK_ERRA(MK_S_HIM) + CHK_ERRA(MK_S_US) + CHK_ERRA(MK_S_MONIKERALREADYREGISTERED) + CHK_ERRA(CO_E_CLASS_CREATE_FAILED) + CHK_ERRA(CO_E_SCM_ERROR) + CHK_ERRA(CO_E_SCM_RPC_FAILURE) + CHK_ERRA(CO_E_BAD_PATH) + CHK_ERRA(CO_E_SERVER_EXEC_FAILURE) + CHK_ERRA(CO_E_OBJSRV_RPC_FAILURE) + CHK_ERRA(MK_E_NO_NORMALIZED) + CHK_ERRA(CO_E_SERVER_STOPPING) + CHK_ERRA(MEM_E_INVALID_ROOT) + CHK_ERRA(MEM_E_INVALID_LINK) + CHK_ERRA(MEM_E_INVALID_SIZE) + CHK_ERRA(CO_S_NOTALLINTERFACES) + CHK_ERRA(DISP_E_UNKNOWNINTERFACE) + CHK_ERRA(DISP_E_MEMBERNOTFOUND) + CHK_ERRA(DISP_E_PARAMNOTFOUND) + CHK_ERRA(DISP_E_TYPEMISMATCH) + CHK_ERRA(DISP_E_UNKNOWNNAME) + CHK_ERRA(DISP_E_NONAMEDARGS) + CHK_ERRA(DISP_E_BADVARTYPE) + CHK_ERRA(DISP_E_EXCEPTION) + CHK_ERRA(DISP_E_OVERFLOW) + CHK_ERRA(DISP_E_BADINDEX) + CHK_ERRA(DISP_E_UNKNOWNLCID) + CHK_ERRA(DISP_E_ARRAYISLOCKED) + CHK_ERRA(DISP_E_BADPARAMCOUNT) + CHK_ERRA(DISP_E_PARAMNOTOPTIONAL) + CHK_ERRA(DISP_E_BADCALLEE) + CHK_ERRA(DISP_E_NOTACOLLECTION) + CHK_ERRA(DISP_E_DIVBYZERO) + CHK_ERRA(DISP_E_BUFFERTOOSMALL) + CHK_ERRA(TYPE_E_BUFFERTOOSMALL) + CHK_ERRA(TYPE_E_FIELDNOTFOUND) + CHK_ERRA(TYPE_E_INVDATAREAD) + CHK_ERRA(TYPE_E_UNSUPFORMAT) + CHK_ERRA(TYPE_E_REGISTRYACCESS) + CHK_ERRA(TYPE_E_LIBNOTREGISTERED) + CHK_ERRA(TYPE_E_UNDEFINEDTYPE) + CHK_ERRA(TYPE_E_QUALIFIEDNAMEDISALLOWED) + CHK_ERRA(TYPE_E_INVALIDSTATE) + CHK_ERRA(TYPE_E_WRONGTYPEKIND) + CHK_ERRA(TYPE_E_ELEMENTNOTFOUND) + CHK_ERRA(TYPE_E_AMBIGUOUSNAME) + CHK_ERRA(TYPE_E_NAMECONFLICT) + CHK_ERRA(TYPE_E_UNKNOWNLCID) + CHK_ERRA(TYPE_E_DLLFUNCTIONNOTFOUND) + CHK_ERRA(TYPE_E_BADMODULEKIND) + CHK_ERRA(TYPE_E_SIZETOOBIG) + CHK_ERRA(TYPE_E_DUPLICATEID) + CHK_ERRA(TYPE_E_INVALIDID) + CHK_ERRA(TYPE_E_TYPEMISMATCH) + CHK_ERRA(TYPE_E_OUTOFBOUNDS) + CHK_ERRA(TYPE_E_IOERROR) + CHK_ERRA(TYPE_E_CANTCREATETMPFILE) + CHK_ERRA(TYPE_E_CANTLOADLIBRARY) + CHK_ERRA(TYPE_E_INCONSISTENTPROPFUNCS) + CHK_ERRA(TYPE_E_CIRCULARTYPE) + CHK_ERRA(STG_E_INVALIDFUNCTION) + CHK_ERRA(STG_E_FILENOTFOUND) + CHK_ERRA(STG_E_PATHNOTFOUND) + CHK_ERRA(STG_E_TOOMANYOPENFILES) + CHK_ERRA(STG_E_ACCESSDENIED) + CHK_ERRA(STG_E_INVALIDHANDLE) + CHK_ERRA(STG_E_INSUFFICIENTMEMORY) + CHK_ERRA(STG_E_INVALIDPOINTER) + CHK_ERRA(STG_E_NOMOREFILES) + CHK_ERRA(STG_E_DISKISWRITEPROTECTED) + CHK_ERRA(STG_E_SEEKERROR) + CHK_ERRA(STG_E_WRITEFAULT) + CHK_ERRA(STG_E_READFAULT) + CHK_ERRA(STG_E_SHAREVIOLATION) + CHK_ERRA(STG_E_LOCKVIOLATION) + CHK_ERRA(STG_E_FILEALREADYEXISTS) + CHK_ERRA(STG_E_INVALIDPARAMETER) + CHK_ERRA(STG_E_MEDIUMFULL) + CHK_ERRA(STG_E_PROPSETMISMATCHED) + CHK_ERRA(STG_E_ABNORMALAPIEXIT) + CHK_ERRA(STG_E_INVALIDHEADER) + CHK_ERRA(STG_E_INVALIDNAME) + CHK_ERRA(STG_E_UNKNOWN) + CHK_ERRA(STG_E_UNIMPLEMENTEDFUNCTION) + CHK_ERRA(STG_E_INVALIDFLAG) + CHK_ERRA(STG_E_INUSE) + CHK_ERRA(STG_E_NOTCURRENT) + CHK_ERRA(STG_E_REVERTED) + CHK_ERRA(STG_E_CANTSAVE) + CHK_ERRA(STG_E_OLDFORMAT) + CHK_ERRA(STG_E_OLDDLL) + CHK_ERRA(STG_E_SHAREREQUIRED) + CHK_ERRA(STG_E_NOTFILEBASEDSTORAGE) + CHK_ERRA(STG_E_EXTANTMARSHALLINGS) + CHK_ERRA(STG_E_DOCFILECORRUPT) + CHK_ERRA(STG_E_BADBASEADDRESS) + CHK_ERRA(STG_E_DOCFILETOOLARGE) + CHK_ERRA(STG_E_NOTSIMPLEFORMAT) + CHK_ERRA(STG_E_INCOMPLETE) + CHK_ERRA(STG_E_TERMINATED) + CHK_ERRA(STG_S_CONVERTED) + CHK_ERRA(STG_S_BLOCK) + CHK_ERRA(STG_S_RETRYNOW) + CHK_ERRA(STG_S_MONITORING) + CHK_ERRA(STG_S_MULTIPLEOPENS) + CHK_ERRA(STG_S_CONSOLIDATIONFAILED) + CHK_ERRA(STG_S_CANNOTCONSOLIDATE) + CHK_ERRA(RPC_E_CALL_REJECTED) + CHK_ERRA(RPC_E_CALL_CANCELED) + CHK_ERRA(RPC_E_CANTPOST_INSENDCALL) + CHK_ERRA(RPC_E_CANTCALLOUT_INASYNCCALL) + CHK_ERRA(RPC_E_CANTCALLOUT_INEXTERNALCALL) + CHK_ERRA(RPC_E_CONNECTION_TERMINATED) + CHK_ERRA(RPC_E_SERVER_DIED) + CHK_ERRA(RPC_E_CLIENT_DIED) + CHK_ERRA(RPC_E_INVALID_DATAPACKET) + CHK_ERRA(RPC_E_CANTTRANSMIT_CALL) + CHK_ERRA(RPC_E_CLIENT_CANTMARSHAL_DATA) + CHK_ERRA(RPC_E_CLIENT_CANTUNMARSHAL_DATA) + CHK_ERRA(RPC_E_SERVER_CANTMARSHAL_DATA) + CHK_ERRA(RPC_E_SERVER_CANTUNMARSHAL_DATA) + CHK_ERRA(RPC_E_INVALID_DATA) + CHK_ERRA(RPC_E_INVALID_PARAMETER) + CHK_ERRA(RPC_E_CANTCALLOUT_AGAIN) + CHK_ERRA(RPC_E_SERVER_DIED_DNE) + CHK_ERRA(RPC_E_SYS_CALL_FAILED) + CHK_ERRA(RPC_E_OUT_OF_RESOURCES) + CHK_ERRA(RPC_E_ATTEMPTED_MULTITHREAD) + CHK_ERRA(RPC_E_NOT_REGISTERED) + CHK_ERRA(RPC_E_FAULT) + CHK_ERRA(RPC_E_SERVERFAULT) + CHK_ERRA(RPC_E_CHANGED_MODE) + CHK_ERRA(RPC_E_INVALIDMETHOD) + CHK_ERRA(RPC_E_DISCONNECTED) + CHK_ERRA(RPC_E_RETRY) + CHK_ERRA(RPC_E_SERVERCALL_RETRYLATER) + CHK_ERRA(RPC_E_SERVERCALL_REJECTED) + CHK_ERRA(RPC_E_INVALID_CALLDATA) + CHK_ERRA(RPC_E_CANTCALLOUT_ININPUTSYNCCALL) + CHK_ERRA(RPC_E_WRONG_THREAD) + CHK_ERRA(RPC_E_THREAD_NOT_INIT) + CHK_ERRA(RPC_E_VERSION_MISMATCH) + CHK_ERRA(RPC_E_INVALID_HEADER) + CHK_ERRA(RPC_E_INVALID_EXTENSION) + CHK_ERRA(RPC_E_INVALID_IPID) + CHK_ERRA(RPC_E_INVALID_OBJECT) + CHK_ERRA(RPC_S_CALLPENDING) + CHK_ERRA(RPC_S_WAITONTIMER) + CHK_ERRA(RPC_E_CALL_COMPLETE) + CHK_ERRA(RPC_E_UNSECURE_CALL) + CHK_ERRA(RPC_E_TOO_LATE) + CHK_ERRA(RPC_E_NO_GOOD_SECURITY_PACKAGES) + CHK_ERRA(RPC_E_ACCESS_DENIED) + CHK_ERRA(RPC_E_REMOTE_DISABLED) + CHK_ERRA(RPC_E_INVALID_OBJREF) + CHK_ERRA(RPC_E_NO_CONTEXT) + CHK_ERRA(RPC_E_TIMEOUT) + CHK_ERRA(RPC_E_NO_SYNC) + CHK_ERRA(RPC_E_FULLSIC_REQUIRED) + CHK_ERRA(RPC_E_INVALID_STD_NAME) + CHK_ERRA(CO_E_FAILEDTOIMPERSONATE) + CHK_ERRA(CO_E_FAILEDTOGETSECCTX) + CHK_ERRA(CO_E_FAILEDTOOPENTHREADTOKEN) + CHK_ERRA(CO_E_FAILEDTOGETTOKENINFO) + CHK_ERRA(CO_E_TRUSTEEDOESNTMATCHCLIENT) + CHK_ERRA(CO_E_FAILEDTOQUERYCLIENTBLANKET) + CHK_ERRA(CO_E_FAILEDTOSETDACL) + CHK_ERRA(CO_E_ACCESSCHECKFAILED) + CHK_ERRA(CO_E_NETACCESSAPIFAILED) + CHK_ERRA(CO_E_WRONGTRUSTEENAMESYNTAX) + CHK_ERRA(CO_E_INVALIDSID) + CHK_ERRA(CO_E_CONVERSIONFAILED) + CHK_ERRA(CO_E_NOMATCHINGSIDFOUND) + CHK_ERRA(CO_E_LOOKUPACCSIDFAILED) + CHK_ERRA(CO_E_NOMATCHINGNAMEFOUND) + CHK_ERRA(CO_E_LOOKUPACCNAMEFAILED) + CHK_ERRA(CO_E_SETSERLHNDLFAILED) + CHK_ERRA(CO_E_FAILEDTOGETWINDIR) + CHK_ERRA(CO_E_PATHTOOLONG) + CHK_ERRA(CO_E_FAILEDTOGENUUID) + CHK_ERRA(CO_E_FAILEDTOCREATEFILE) + CHK_ERRA(CO_E_FAILEDTOCLOSEHANDLE) + CHK_ERRA(CO_E_EXCEEDSYSACLLIMIT) + CHK_ERRA(CO_E_ACESINWRONGORDER) + CHK_ERRA(CO_E_INCOMPATIBLESTREAMVERSION) + CHK_ERRA(CO_E_FAILEDTOOPENPROCESSTOKEN) + CHK_ERRA(CO_E_DECODEFAILED) + CHK_ERRA(CO_E_ACNOTINITIALIZED) + CHK_ERRA(RPC_E_UNEXPECTED) + CHK_ERRA(NTE_BAD_UID) + CHK_ERRA(NTE_BAD_HASH) + CHK_ERRA(NTE_BAD_KEY) + CHK_ERRA(NTE_BAD_LEN) + CHK_ERRA(NTE_BAD_DATA) + CHK_ERRA(NTE_BAD_SIGNATURE) + CHK_ERRA(NTE_BAD_VER) + CHK_ERRA(NTE_BAD_ALGID) + CHK_ERRA(NTE_BAD_FLAGS) + CHK_ERRA(NTE_BAD_TYPE) + CHK_ERRA(NTE_BAD_KEY_STATE) + CHK_ERRA(NTE_BAD_HASH_STATE) + CHK_ERRA(NTE_NO_KEY) + CHK_ERRA(NTE_NO_MEMORY) + CHK_ERRA(NTE_EXISTS) + CHK_ERRA(NTE_PERM) + CHK_ERRA(NTE_NOT_FOUND) + CHK_ERRA(NTE_DOUBLE_ENCRYPT) + CHK_ERRA(NTE_BAD_PROVIDER) + CHK_ERRA(NTE_BAD_PROV_TYPE) + CHK_ERRA(NTE_BAD_PUBLIC_KEY) + CHK_ERRA(NTE_BAD_KEYSET) + CHK_ERRA(NTE_PROV_TYPE_NOT_DEF) + CHK_ERRA(NTE_PROV_TYPE_ENTRY_BAD) + CHK_ERRA(NTE_KEYSET_NOT_DEF) + CHK_ERRA(NTE_KEYSET_ENTRY_BAD) + CHK_ERRA(NTE_PROV_TYPE_NO_MATCH) + CHK_ERRA(NTE_SIGNATURE_FILE_BAD) + CHK_ERRA(NTE_PROVIDER_DLL_FAIL) + CHK_ERRA(NTE_PROV_DLL_NOT_FOUND) + CHK_ERRA(NTE_BAD_KEYSET_PARAM) + CHK_ERRA(NTE_FAIL) + CHK_ERRA(NTE_SYS_ERR) + CHK_ERRA(NTE_SILENT_CONTEXT) + CHK_ERRA(NTE_TOKEN_KEYSET_STORAGE_FULL) + CHK_ERRA(CRYPT_E_MSG_ERROR) + CHK_ERRA(CRYPT_E_UNKNOWN_ALGO) + CHK_ERRA(CRYPT_E_OID_FORMAT) + CHK_ERRA(CRYPT_E_INVALID_MSG_TYPE) + CHK_ERRA(CRYPT_E_UNEXPECTED_ENCODING) + CHK_ERRA(CRYPT_E_AUTH_ATTR_MISSING) + CHK_ERRA(CRYPT_E_HASH_VALUE) + CHK_ERRA(CRYPT_E_INVALID_INDEX) + CHK_ERRA(CRYPT_E_ALREADY_DECRYPTED) + CHK_ERRA(CRYPT_E_NOT_DECRYPTED) + CHK_ERRA(CRYPT_E_RECIPIENT_NOT_FOUND) + CHK_ERRA(CRYPT_E_CONTROL_TYPE) + CHK_ERRA(CRYPT_E_ISSUER_SERIALNUMBER) + CHK_ERRA(CRYPT_E_SIGNER_NOT_FOUND) + CHK_ERRA(CRYPT_E_ATTRIBUTES_MISSING) + CHK_ERRA(CRYPT_E_STREAM_MSG_NOT_READY) + CHK_ERRA(CRYPT_E_STREAM_INSUFFICIENT_DATA) + CHK_ERRA(CRYPT_E_BAD_LEN) + CHK_ERRA(CRYPT_E_BAD_ENCODE) + CHK_ERRA(CRYPT_E_FILE_ERROR) + CHK_ERRA(CRYPT_E_NOT_FOUND) + CHK_ERRA(CRYPT_E_EXISTS) + CHK_ERRA(CRYPT_E_NO_PROVIDER) + CHK_ERRA(CRYPT_E_SELF_SIGNED) + CHK_ERRA(CRYPT_E_DELETED_PREV) + CHK_ERRA(CRYPT_E_NO_MATCH) + CHK_ERRA(CRYPT_E_UNEXPECTED_MSG_TYPE) + CHK_ERRA(CRYPT_E_NO_KEY_PROPERTY) + CHK_ERRA(CRYPT_E_NO_DECRYPT_CERT) + CHK_ERRA(CRYPT_E_BAD_MSG) + CHK_ERRA(CRYPT_E_NO_SIGNER) + CHK_ERRA(CRYPT_E_PENDING_CLOSE) + CHK_ERRA(CRYPT_E_REVOKED) + CHK_ERRA(CRYPT_E_NO_REVOCATION_DLL) + CHK_ERRA(CRYPT_E_NO_REVOCATION_CHECK) + CHK_ERRA(CRYPT_E_REVOCATION_OFFLINE) + CHK_ERRA(CRYPT_E_NOT_IN_REVOCATION_DATABASE) + CHK_ERRA(CRYPT_E_INVALID_NUMERIC_STRING) + CHK_ERRA(CRYPT_E_INVALID_PRINTABLE_STRING) + CHK_ERRA(CRYPT_E_INVALID_IA5_STRING) + CHK_ERRA(CRYPT_E_INVALID_X500_STRING) + CHK_ERRA(CRYPT_E_NOT_CHAR_STRING) + CHK_ERRA(CRYPT_E_FILERESIZED) + CHK_ERRA(CRYPT_E_SECURITY_SETTINGS) + CHK_ERRA(CRYPT_E_NO_VERIFY_USAGE_DLL) + CHK_ERRA(CRYPT_E_NO_VERIFY_USAGE_CHECK) + CHK_ERRA(CRYPT_E_VERIFY_USAGE_OFFLINE) + CHK_ERRA(CRYPT_E_NOT_IN_CTL) + CHK_ERRA(CRYPT_E_NO_TRUSTED_SIGNER) + CHK_ERRA(CRYPT_E_OSS_ERROR) + CHK_ERRA(OSS_MORE_BUF) + CHK_ERRA(OSS_NEGATIVE_UINTEGER) + CHK_ERRA(OSS_PDU_RANGE) + CHK_ERRA(OSS_MORE_INPUT) + CHK_ERRA(OSS_DATA_ERROR) + CHK_ERRA(OSS_BAD_ARG) + CHK_ERRA(OSS_BAD_VERSION) + CHK_ERRA(OSS_OUT_MEMORY) + CHK_ERRA(OSS_PDU_MISMATCH) + CHK_ERRA(OSS_LIMITED) + CHK_ERRA(OSS_BAD_PTR) + CHK_ERRA(OSS_BAD_TIME) + CHK_ERRA(OSS_INDEFINITE_NOT_SUPPORTED) + CHK_ERRA(OSS_MEM_ERROR) + CHK_ERRA(OSS_BAD_TABLE) + CHK_ERRA(OSS_TOO_LONG) + CHK_ERRA(OSS_CONSTRAINT_VIOLATED) + CHK_ERRA(OSS_FATAL_ERROR) + CHK_ERRA(OSS_ACCESS_SERIALIZATION_ERROR) + CHK_ERRA(OSS_NULL_TBL) + CHK_ERRA(OSS_NULL_FCN) + CHK_ERRA(OSS_BAD_ENCRULES) + CHK_ERRA(OSS_UNAVAIL_ENCRULES) + CHK_ERRA(OSS_CANT_OPEN_TRACE_WINDOW) + CHK_ERRA(OSS_UNIMPLEMENTED) + CHK_ERRA(OSS_OID_DLL_NOT_LINKED) + CHK_ERRA(OSS_CANT_OPEN_TRACE_FILE) + CHK_ERRA(OSS_TRACE_FILE_ALREADY_OPEN) + CHK_ERRA(OSS_TABLE_MISMATCH) + CHK_ERRA(OSS_TYPE_NOT_SUPPORTED) + CHK_ERRA(OSS_REAL_DLL_NOT_LINKED) + CHK_ERRA(OSS_REAL_CODE_NOT_LINKED) + CHK_ERRA(OSS_OUT_OF_RANGE) + CHK_ERRA(OSS_COPIER_DLL_NOT_LINKED) + CHK_ERRA(OSS_CONSTRAINT_DLL_NOT_LINKED) + CHK_ERRA(OSS_COMPARATOR_DLL_NOT_LINKED) + CHK_ERRA(OSS_COMPARATOR_CODE_NOT_LINKED) + CHK_ERRA(OSS_MEM_MGR_DLL_NOT_LINKED) + CHK_ERRA(OSS_PDV_DLL_NOT_LINKED) + CHK_ERRA(OSS_PDV_CODE_NOT_LINKED) + CHK_ERRA(OSS_API_DLL_NOT_LINKED) + CHK_ERRA(OSS_BERDER_DLL_NOT_LINKED) + CHK_ERRA(OSS_PER_DLL_NOT_LINKED) + CHK_ERRA(OSS_OPEN_TYPE_ERROR) + CHK_ERRA(OSS_MUTEX_NOT_CREATED) + CHK_ERRA(OSS_CANT_CLOSE_TRACE_FILE) + CHK_ERRA(CERTSRV_E_BAD_REQUESTSUBJECT) + CHK_ERRA(CERTSRV_E_NO_REQUEST) + CHK_ERRA(CERTSRV_E_BAD_REQUESTSTATUS) + CHK_ERRA(CERTSRV_E_PROPERTY_EMPTY) + CHK_ERRA(CERTSRV_E_INVALID_CA_CERTIFICATE) + CHK_ERRA(CERTSRV_E_UNSUPPORTED_CERT_TYPE) + CHK_ERRA(CERTSRV_E_NO_CERT_TYPE) + CHK_ERRA(TRUST_E_SYSTEM_ERROR) + CHK_ERRA(TRUST_E_NO_SIGNER_CERT) + CHK_ERRA(TRUST_E_COUNTER_SIGNER) + CHK_ERRA(TRUST_E_CERT_SIGNATURE) + CHK_ERRA(TRUST_E_TIME_STAMP) + CHK_ERRA(TRUST_E_BAD_DIGEST) + CHK_ERRA(TRUST_E_BASIC_CONSTRAINTS) + CHK_ERRA(TRUST_E_FINANCIAL_CRITERIA) +// CHK_ERRA(NTE_OP_OK) + CHK_ERRA(TRUST_E_PROVIDER_UNKNOWN) + CHK_ERRA(TRUST_E_ACTION_UNKNOWN) + CHK_ERRA(TRUST_E_SUBJECT_FORM_UNKNOWN) + CHK_ERRA(TRUST_E_SUBJECT_NOT_TRUSTED) + CHK_ERRA(DIGSIG_E_ENCODE) + CHK_ERRA(DIGSIG_E_DECODE) + CHK_ERRA(DIGSIG_E_EXTENSIBILITY) + CHK_ERRA(DIGSIG_E_CRYPTO) + CHK_ERRA(PERSIST_E_SIZEDEFINITE) + CHK_ERRA(PERSIST_E_SIZEINDEFINITE) + CHK_ERRA(PERSIST_E_NOTSELFSIZING) + CHK_ERRA(TRUST_E_NOSIGNATURE) + CHK_ERRA(CERT_E_EXPIRED) + CHK_ERRA(CERT_E_VALIDITYPERIODNESTING) + CHK_ERRA(CERT_E_ROLE) + CHK_ERRA(CERT_E_PATHLENCONST) + CHK_ERRA(CERT_E_CRITICAL) + CHK_ERRA(CERT_E_PURPOSE) + CHK_ERRA(CERT_E_ISSUERCHAINING) + CHK_ERRA(CERT_E_MALFORMED) + CHK_ERRA(CERT_E_UNTRUSTEDROOT) + CHK_ERRA(CERT_E_CHAINING) + CHK_ERRA(TRUST_E_FAIL) + CHK_ERRA(CERT_E_REVOKED) + CHK_ERRA(CERT_E_UNTRUSTEDTESTROOT) + CHK_ERRA(CERT_E_REVOCATION_FAILURE) + CHK_ERRA(CERT_E_CN_NO_MATCH) + CHK_ERRA(CERT_E_WRONG_USAGE) + CHK_ERRA(SPAPI_E_EXPECTED_SECTION_NAME) + CHK_ERRA(SPAPI_E_BAD_SECTION_NAME_LINE) + CHK_ERRA(SPAPI_E_SECTION_NAME_TOO_LONG) + CHK_ERRA(SPAPI_E_GENERAL_SYNTAX) + CHK_ERRA(SPAPI_E_WRONG_INF_STYLE) + CHK_ERRA(SPAPI_E_SECTION_NOT_FOUND) + CHK_ERRA(SPAPI_E_LINE_NOT_FOUND) + CHK_ERRA(SPAPI_E_NO_BACKUP) + CHK_ERRA(SPAPI_E_NO_ASSOCIATED_CLASS) + CHK_ERRA(SPAPI_E_CLASS_MISMATCH) + CHK_ERRA(SPAPI_E_DUPLICATE_FOUND) + CHK_ERRA(SPAPI_E_NO_DRIVER_SELECTED) + CHK_ERRA(SPAPI_E_KEY_DOES_NOT_EXIST) + CHK_ERRA(SPAPI_E_INVALID_DEVINST_NAME) + CHK_ERRA(SPAPI_E_INVALID_CLASS) + CHK_ERRA(SPAPI_E_DEVINST_ALREADY_EXISTS) + CHK_ERRA(SPAPI_E_DEVINFO_NOT_REGISTERED) + CHK_ERRA(SPAPI_E_INVALID_REG_PROPERTY) + CHK_ERRA(SPAPI_E_NO_INF) + CHK_ERRA(SPAPI_E_NO_SUCH_DEVINST) + CHK_ERRA(SPAPI_E_CANT_LOAD_CLASS_ICON) + CHK_ERRA(SPAPI_E_INVALID_CLASS_INSTALLER) + CHK_ERRA(SPAPI_E_DI_DO_DEFAULT) + CHK_ERRA(SPAPI_E_DI_NOFILECOPY) + CHK_ERRA(SPAPI_E_INVALID_HWPROFILE) + CHK_ERRA(SPAPI_E_NO_DEVICE_SELECTED) + CHK_ERRA(SPAPI_E_DEVINFO_LIST_LOCKED) + CHK_ERRA(SPAPI_E_DEVINFO_DATA_LOCKED) + CHK_ERRA(SPAPI_E_DI_BAD_PATH) + CHK_ERRA(SPAPI_E_NO_CLASSINSTALL_PARAMS) + CHK_ERRA(SPAPI_E_FILEQUEUE_LOCKED) + CHK_ERRA(SPAPI_E_BAD_SERVICE_INSTALLSECT) + CHK_ERRA(SPAPI_E_NO_CLASS_DRIVER_LIST) + CHK_ERRA(SPAPI_E_NO_ASSOCIATED_SERVICE) + CHK_ERRA(SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE) + CHK_ERRA(SPAPI_E_DEVICE_INTERFACE_ACTIVE) + CHK_ERRA(SPAPI_E_DEVICE_INTERFACE_REMOVED) + CHK_ERRA(SPAPI_E_BAD_INTERFACE_INSTALLSECT) + CHK_ERRA(SPAPI_E_NO_SUCH_INTERFACE_CLASS) + CHK_ERRA(SPAPI_E_INVALID_REFERENCE_STRING) + CHK_ERRA(SPAPI_E_INVALID_MACHINENAME) + CHK_ERRA(SPAPI_E_REMOTE_COMM_FAILURE) + CHK_ERRA(SPAPI_E_MACHINE_UNAVAILABLE) + CHK_ERRA(SPAPI_E_NO_CONFIGMGR_SERVICES) + CHK_ERRA(SPAPI_E_INVALID_PROPPAGE_PROVIDER) + CHK_ERRA(SPAPI_E_NO_SUCH_DEVICE_INTERFACE) + CHK_ERRA(SPAPI_E_DI_POSTPROCESSING_REQUIRED) + CHK_ERRA(SPAPI_E_INVALID_COINSTALLER) + CHK_ERRA(SPAPI_E_NO_COMPAT_DRIVERS) + CHK_ERRA(SPAPI_E_NO_DEVICE_ICON) + CHK_ERRA(SPAPI_E_INVALID_INF_LOGCONFIG) + CHK_ERRA(SPAPI_E_DI_DONT_INSTALL) + CHK_ERRA(SPAPI_E_INVALID_FILTER_DRIVER) + CHK_ERRA(SPAPI_E_NON_WINDOWS_NT_DRIVER) + CHK_ERRA(SPAPI_E_NON_WINDOWS_DRIVER) + CHK_ERRA(SPAPI_E_NO_CATALOG_FOR_OEM_INF) + CHK_ERRA(SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE) + CHK_ERRA(SPAPI_E_ERROR_NOT_INSTALLED) +// CHK_ERRA(SCARD_S_SUCCESS) + CHK_ERRA(SCARD_F_INTERNAL_ERROR) + CHK_ERRA(SCARD_E_CANCELLED) + CHK_ERRA(SCARD_E_INVALID_HANDLE) + CHK_ERRA(SCARD_E_INVALID_PARAMETER) + CHK_ERRA(SCARD_E_INVALID_TARGET) + CHK_ERRA(SCARD_E_NO_MEMORY) + CHK_ERRA(SCARD_F_WAITED_TOO_LONG) + CHK_ERRA(SCARD_E_INSUFFICIENT_BUFFER) + CHK_ERRA(SCARD_E_UNKNOWN_READER) + CHK_ERRA(SCARD_E_TIMEOUT) + CHK_ERRA(SCARD_E_SHARING_VIOLATION) + CHK_ERRA(SCARD_E_NO_SMARTCARD) + CHK_ERRA(SCARD_E_UNKNOWN_CARD) + CHK_ERRA(SCARD_E_CANT_DISPOSE) + CHK_ERRA(SCARD_E_PROTO_MISMATCH) + CHK_ERRA(SCARD_E_NOT_READY) + CHK_ERRA(SCARD_E_INVALID_VALUE) + CHK_ERRA(SCARD_E_SYSTEM_CANCELLED) + CHK_ERRA(SCARD_F_COMM_ERROR) + CHK_ERRA(SCARD_F_UNKNOWN_ERROR) + CHK_ERRA(SCARD_E_INVALID_ATR) + CHK_ERRA(SCARD_E_NOT_TRANSACTED) + CHK_ERRA(SCARD_E_READER_UNAVAILABLE) + CHK_ERRA(SCARD_P_SHUTDOWN) + CHK_ERRA(SCARD_E_PCI_TOO_SMALL) + CHK_ERRA(SCARD_E_READER_UNSUPPORTED) + CHK_ERRA(SCARD_E_DUPLICATE_READER) + CHK_ERRA(SCARD_E_CARD_UNSUPPORTED) + CHK_ERRA(SCARD_E_NO_SERVICE) + CHK_ERRA(SCARD_E_SERVICE_STOPPED) + CHK_ERRA(SCARD_E_UNEXPECTED) + CHK_ERRA(SCARD_E_ICC_INSTALLATION) + CHK_ERRA(SCARD_E_ICC_CREATEORDER) + CHK_ERRA(SCARD_E_UNSUPPORTED_FEATURE) + CHK_ERRA(SCARD_E_DIR_NOT_FOUND) + CHK_ERRA(SCARD_E_FILE_NOT_FOUND) + CHK_ERRA(SCARD_E_NO_DIR) + CHK_ERRA(SCARD_E_NO_FILE) + CHK_ERRA(SCARD_E_NO_ACCESS) + CHK_ERRA(SCARD_E_WRITE_TOO_MANY) + CHK_ERRA(SCARD_E_BAD_SEEK) + CHK_ERRA(SCARD_E_INVALID_CHV) + CHK_ERRA(SCARD_E_UNKNOWN_RES_MNG) + CHK_ERRA(SCARD_E_NO_SUCH_CERTIFICATE) + CHK_ERRA(SCARD_E_CERTIFICATE_UNAVAILABLE) + CHK_ERRA(SCARD_E_NO_READERS_AVAILABLE) + CHK_ERRA(SCARD_E_COMM_DATA_LOST) + CHK_ERRA(SCARD_W_UNSUPPORTED_CARD) + CHK_ERRA(SCARD_W_UNRESPONSIVE_CARD) + CHK_ERRA(SCARD_W_UNPOWERED_CARD) + CHK_ERRA(SCARD_W_RESET_CARD) + CHK_ERRA(SCARD_W_REMOVED_CARD) + CHK_ERRA(SCARD_W_SECURITY_VIOLATION) + CHK_ERRA(SCARD_W_WRONG_CHV) + CHK_ERRA(SCARD_W_CHV_BLOCKED) + CHK_ERRA(SCARD_W_EOF) + CHK_ERRA(SCARD_W_CANCELLED_BY_USER) + CHK_ERR_WIN32_ONLY(ERROR_INVALID_FUNCTION, "ERROR_INVALID_FUNCTION") + CHK_ERR_WIN32A(ERROR_FILE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_PATH_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_TOO_MANY_OPEN_FILES) + CHK_ERRA(ERROR_ACCESS_DENIED) + CHK_ERRA(ERROR_INVALID_HANDLE) + CHK_ERR_WIN32A(ERROR_ARENA_TRASHED) + CHK_ERR_WIN32A(ERROR_NOT_ENOUGH_MEMORY) + CHK_ERR_WIN32A(ERROR_INVALID_BLOCK) + CHK_ERR_WIN32A(ERROR_BAD_ENVIRONMENT) + CHK_ERR_WIN32A(ERROR_BAD_FORMAT) + CHK_ERR_WIN32A(ERROR_INVALID_ACCESS) + CHK_ERR_WIN32A(ERROR_INVALID_DATA) + CHK_ERRA(ERROR_OUTOFMEMORY) + CHK_ERR_WIN32A(ERROR_INVALID_DRIVE) + CHK_ERR_WIN32A(ERROR_CURRENT_DIRECTORY) + CHK_ERR_WIN32A(ERROR_NOT_SAME_DEVICE) + CHK_ERR_WIN32A(ERROR_NO_MORE_FILES) + CHK_ERR_WIN32A(ERROR_WRITE_PROTECT) + CHK_ERR_WIN32A(ERROR_BAD_UNIT) + CHK_ERR_WIN32A(ERROR_NOT_READY) + CHK_ERR_WIN32A(ERROR_BAD_COMMAND) + CHK_ERR_WIN32A(ERROR_CRC) + CHK_ERR_WIN32A(ERROR_BAD_LENGTH) + CHK_ERR_WIN32A(ERROR_SEEK) + CHK_ERR_WIN32A(ERROR_NOT_DOS_DISK) + CHK_ERR_WIN32A(ERROR_SECTOR_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_OUT_OF_PAPER) + CHK_ERR_WIN32A(ERROR_WRITE_FAULT) + CHK_ERR_WIN32A(ERROR_READ_FAULT) + CHK_ERR_WIN32A(ERROR_GEN_FAILURE) + CHK_ERR_WIN32A(ERROR_SHARING_VIOLATION) + CHK_ERR_WIN32A(ERROR_LOCK_VIOLATION) + CHK_ERR_WIN32A(ERROR_WRONG_DISK) + CHK_ERR_WIN32A(ERROR_SHARING_BUFFER_EXCEEDED) + CHK_ERR_WIN32A(ERROR_HANDLE_EOF) + CHK_ERR_WIN32A(ERROR_HANDLE_DISK_FULL) + CHK_ERR_WIN32A(ERROR_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_REM_NOT_LIST) + CHK_ERR_WIN32A(ERROR_DUP_NAME) + CHK_ERR_WIN32A(ERROR_BAD_NETPATH) + CHK_ERR_WIN32A(ERROR_NETWORK_BUSY) + CHK_ERR_WIN32A(ERROR_DEV_NOT_EXIST) + CHK_ERR_WIN32A(ERROR_TOO_MANY_CMDS) + CHK_ERR_WIN32A(ERROR_ADAP_HDW_ERR) + CHK_ERR_WIN32A(ERROR_BAD_NET_RESP) + CHK_ERR_WIN32A(ERROR_UNEXP_NET_ERR) + CHK_ERR_WIN32A(ERROR_BAD_REM_ADAP) + CHK_ERR_WIN32A(ERROR_PRINTQ_FULL) + CHK_ERR_WIN32A(ERROR_NO_SPOOL_SPACE) + CHK_ERR_WIN32A(ERROR_PRINT_CANCELLED) + CHK_ERR_WIN32A(ERROR_NETNAME_DELETED) + CHK_ERR_WIN32A(ERROR_NETWORK_ACCESS_DENIED) + CHK_ERR_WIN32A(ERROR_BAD_DEV_TYPE) + CHK_ERR_WIN32A(ERROR_BAD_NET_NAME) + CHK_ERR_WIN32A(ERROR_TOO_MANY_NAMES) + CHK_ERR_WIN32A(ERROR_TOO_MANY_SESS) + CHK_ERR_WIN32A(ERROR_SHARING_PAUSED) + CHK_ERR_WIN32A(ERROR_REQ_NOT_ACCEP) + CHK_ERR_WIN32A(ERROR_REDIR_PAUSED) + CHK_ERR_WIN32A(ERROR_FILE_EXISTS) + CHK_ERR_WIN32A(ERROR_CANNOT_MAKE) + CHK_ERR_WIN32A(ERROR_FAIL_I24) + CHK_ERR_WIN32A(ERROR_OUT_OF_STRUCTURES) + CHK_ERR_WIN32A(ERROR_ALREADY_ASSIGNED) + CHK_ERR_WIN32A(ERROR_INVALID_PASSWORD) + CHK_ERRA(ERROR_INVALID_PARAMETER) + CHK_ERR_WIN32A(ERROR_NET_WRITE_FAULT) + CHK_ERR_WIN32A(ERROR_NO_PROC_SLOTS) + CHK_ERR_WIN32A(ERROR_TOO_MANY_SEMAPHORES) + CHK_ERR_WIN32A(ERROR_EXCL_SEM_ALREADY_OWNED) + CHK_ERR_WIN32A(ERROR_SEM_IS_SET) + CHK_ERR_WIN32A(ERROR_TOO_MANY_SEM_REQUESTS) + CHK_ERR_WIN32A(ERROR_INVALID_AT_INTERRUPT_TIME) + CHK_ERR_WIN32A(ERROR_SEM_OWNER_DIED) + CHK_ERR_WIN32A(ERROR_SEM_USER_LIMIT) + CHK_ERR_WIN32A(ERROR_DISK_CHANGE) + CHK_ERR_WIN32A(ERROR_DRIVE_LOCKED) + CHK_ERR_WIN32A(ERROR_BROKEN_PIPE) + CHK_ERR_WIN32A(ERROR_OPEN_FAILED) + CHK_ERR_WIN32A(ERROR_BUFFER_OVERFLOW) + CHK_ERR_WIN32A(ERROR_DISK_FULL) + CHK_ERR_WIN32A(ERROR_NO_MORE_SEARCH_HANDLES) + CHK_ERR_WIN32A(ERROR_INVALID_TARGET_HANDLE) + CHK_ERR_WIN32A(ERROR_INVALID_CATEGORY) + CHK_ERR_WIN32A(ERROR_INVALID_VERIFY_SWITCH) + CHK_ERR_WIN32A(ERROR_BAD_DRIVER_LEVEL) + CHK_ERR_WIN32A(ERROR_CALL_NOT_IMPLEMENTED) + CHK_ERR_WIN32A(ERROR_SEM_TIMEOUT) + CHK_ERR_WIN32A(ERROR_INSUFFICIENT_BUFFER) + CHK_ERR_WIN32A(ERROR_INVALID_NAME) + CHK_ERR_WIN32A(ERROR_INVALID_LEVEL) + CHK_ERR_WIN32A(ERROR_NO_VOLUME_LABEL) + CHK_ERR_WIN32A(ERROR_MOD_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_PROC_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_WAIT_NO_CHILDREN) + CHK_ERR_WIN32A(ERROR_CHILD_NOT_COMPLETE) + CHK_ERR_WIN32A(ERROR_DIRECT_ACCESS_HANDLE) + CHK_ERR_WIN32A(ERROR_NEGATIVE_SEEK) + CHK_ERR_WIN32A(ERROR_SEEK_ON_DEVICE) + CHK_ERR_WIN32A(ERROR_IS_JOIN_TARGET) + CHK_ERR_WIN32A(ERROR_IS_JOINED) + CHK_ERR_WIN32A(ERROR_IS_SUBSTED) + CHK_ERR_WIN32A(ERROR_NOT_JOINED) + CHK_ERR_WIN32A(ERROR_NOT_SUBSTED) + CHK_ERR_WIN32A(ERROR_JOIN_TO_JOIN) + CHK_ERR_WIN32A(ERROR_SUBST_TO_SUBST) + CHK_ERR_WIN32A(ERROR_JOIN_TO_SUBST) + CHK_ERR_WIN32A(ERROR_SUBST_TO_JOIN) + CHK_ERR_WIN32A(ERROR_BUSY_DRIVE) + CHK_ERR_WIN32A(ERROR_SAME_DRIVE) + CHK_ERR_WIN32A(ERROR_DIR_NOT_ROOT) + CHK_ERR_WIN32A(ERROR_DIR_NOT_EMPTY) + CHK_ERR_WIN32A(ERROR_IS_SUBST_PATH) + CHK_ERR_WIN32A(ERROR_IS_JOIN_PATH) + CHK_ERR_WIN32A(ERROR_PATH_BUSY) + CHK_ERR_WIN32A(ERROR_IS_SUBST_TARGET) + CHK_ERR_WIN32A(ERROR_SYSTEM_TRACE) + CHK_ERR_WIN32A(ERROR_INVALID_EVENT_COUNT) + CHK_ERR_WIN32A(ERROR_TOO_MANY_MUXWAITERS) + CHK_ERR_WIN32A(ERROR_INVALID_LIST_FORMAT) + CHK_ERR_WIN32A(ERROR_LABEL_TOO_LONG) + CHK_ERR_WIN32A(ERROR_TOO_MANY_TCBS) + CHK_ERR_WIN32A(ERROR_SIGNAL_REFUSED) + CHK_ERR_WIN32A(ERROR_DISCARDED) + CHK_ERR_WIN32A(ERROR_NOT_LOCKED) + CHK_ERR_WIN32A(ERROR_BAD_THREADID_ADDR) + CHK_ERR_WIN32A(ERROR_BAD_ARGUMENTS) + CHK_ERR_WIN32A(ERROR_BAD_PATHNAME) + CHK_ERR_WIN32A(ERROR_SIGNAL_PENDING) + CHK_ERR_WIN32A(ERROR_MAX_THRDS_REACHED) + CHK_ERR_WIN32A(ERROR_LOCK_FAILED) + CHK_ERR_WIN32A(ERROR_BUSY) + CHK_ERR_WIN32A(ERROR_CANCEL_VIOLATION) + CHK_ERR_WIN32A(ERROR_ATOMIC_LOCKS_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_INVALID_SEGMENT_NUMBER) + CHK_ERR_WIN32A(ERROR_INVALID_ORDINAL) + CHK_ERR_WIN32A(ERROR_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_INVALID_FLAG_NUMBER) + CHK_ERR_WIN32A(ERROR_SEM_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_INVALID_STARTING_CODESEG) + CHK_ERR_WIN32A(ERROR_INVALID_STACKSEG) + CHK_ERR_WIN32A(ERROR_INVALID_MODULETYPE) + CHK_ERR_WIN32A(ERROR_INVALID_EXE_SIGNATURE) + CHK_ERR_WIN32A(ERROR_EXE_MARKED_INVALID) + CHK_ERR_WIN32A(ERROR_BAD_EXE_FORMAT) + CHK_ERR_WIN32A(ERROR_ITERATED_DATA_EXCEEDS_64k) + CHK_ERR_WIN32A(ERROR_INVALID_MINALLOCSIZE) + CHK_ERR_WIN32A(ERROR_DYNLINK_FROM_INVALID_RING) + CHK_ERR_WIN32A(ERROR_IOPL_NOT_ENABLED) + CHK_ERR_WIN32A(ERROR_INVALID_SEGDPL) + CHK_ERR_WIN32A(ERROR_AUTODATASEG_EXCEEDS_64k) + CHK_ERRA(ERROR_RING2SEG_MUST_BE_MOVABLE) + CHK_ERRA(ERROR_RELOC_CHAIN_XEEDS_SEGLIM) + CHK_ERR_WIN32A(ERROR_INFLOOP_IN_RELOC_CHAIN) + CHK_ERR_WIN32A(ERROR_ENVVAR_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NO_SIGNAL_SENT) + CHK_ERR_WIN32A(ERROR_FILENAME_EXCED_RANGE) + CHK_ERR_WIN32A(ERROR_RING2_STACK_IN_USE) + CHK_ERR_WIN32A(ERROR_META_EXPANSION_TOO_LONG) + CHK_ERR_WIN32A(ERROR_INVALID_SIGNAL_NUMBER) + CHK_ERR_WIN32A(ERROR_THREAD_1_INACTIVE) + CHK_ERR_WIN32A(ERROR_LOCKED) + CHK_ERR_WIN32A(ERROR_TOO_MANY_MODULES) + CHK_ERR_WIN32A(ERROR_NESTING_NOT_ALLOWED) + CHK_ERR_WIN32A(ERROR_EXE_MACHINE_TYPE_MISMATCH) + CHK_ERR_WIN32A(ERROR_BAD_PIPE) + CHK_ERR_WIN32A(ERROR_PIPE_BUSY) + CHK_ERR_WIN32A(ERROR_NO_DATA) + CHK_ERR_WIN32A(ERROR_PIPE_NOT_CONNECTED) + CHK_ERR_WIN32A(ERROR_MORE_DATA) + CHK_ERR_WIN32A(ERROR_VC_DISCONNECTED) + CHK_ERR_WIN32A(ERROR_INVALID_EA_NAME) + CHK_ERR_WIN32A(ERROR_EA_LIST_INCONSISTENT) + CHK_ERR_WIN32A(WAIT_TIMEOUT) + CHK_ERR_WIN32A(ERROR_NO_MORE_ITEMS) + CHK_ERR_WIN32A(ERROR_CANNOT_COPY) + CHK_ERR_WIN32A(ERROR_DIRECTORY) + CHK_ERR_WIN32A(ERROR_EAS_DIDNT_FIT) + CHK_ERR_WIN32A(ERROR_EA_FILE_CORRUPT) + CHK_ERR_WIN32A(ERROR_EA_TABLE_FULL) + CHK_ERR_WIN32A(ERROR_INVALID_EA_HANDLE) + CHK_ERR_WIN32A(ERROR_EAS_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_NOT_OWNER) + CHK_ERR_WIN32A(ERROR_TOO_MANY_POSTS) + CHK_ERR_WIN32A(ERROR_PARTIAL_COPY) + CHK_ERR_WIN32A(ERROR_OPLOCK_NOT_GRANTED) + CHK_ERR_WIN32A(ERROR_INVALID_OPLOCK_PROTOCOL) + CHK_ERR_WIN32A(ERROR_MR_MID_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_INVALID_ADDRESS) + CHK_ERR_WIN32A(ERROR_ARITHMETIC_OVERFLOW) + CHK_ERR_WIN32A(ERROR_PIPE_CONNECTED) + CHK_ERR_WIN32A(ERROR_PIPE_LISTENING) + CHK_ERR_WIN32A(ERROR_EA_ACCESS_DENIED) + CHK_ERR_WIN32A(ERROR_OPERATION_ABORTED) + CHK_ERR_WIN32A(ERROR_IO_INCOMPLETE) + CHK_ERR_WIN32A(ERROR_IO_PENDING) + CHK_ERR_WIN32A(ERROR_NOACCESS) + CHK_ERR_WIN32A(ERROR_SWAPERROR) + CHK_ERR_WIN32A(ERROR_STACK_OVERFLOW) + CHK_ERR_WIN32A(ERROR_INVALID_MESSAGE) + CHK_ERR_WIN32A(ERROR_CAN_NOT_COMPLETE) + CHK_ERR_WIN32A(ERROR_INVALID_FLAGS) + CHK_ERR_WIN32A(ERROR_UNRECOGNIZED_VOLUME) + CHK_ERR_WIN32A(ERROR_FILE_INVALID) + CHK_ERR_WIN32A(ERROR_FULLSCREEN_MODE) + CHK_ERR_WIN32A(ERROR_NO_TOKEN) + CHK_ERR_WIN32A(ERROR_BADDB) + CHK_ERR_WIN32A(ERROR_BADKEY) + CHK_ERR_WIN32A(ERROR_CANTOPEN) + CHK_ERR_WIN32A(ERROR_CANTREAD) + CHK_ERR_WIN32A(ERROR_CANTWRITE) + CHK_ERR_WIN32A(ERROR_REGISTRY_RECOVERED) + CHK_ERR_WIN32A(ERROR_REGISTRY_CORRUPT) + CHK_ERR_WIN32A(ERROR_REGISTRY_IO_FAILED) + CHK_ERR_WIN32A(ERROR_NOT_REGISTRY_FILE) + CHK_ERR_WIN32A(ERROR_KEY_DELETED) + CHK_ERR_WIN32A(ERROR_NO_LOG_SPACE) + CHK_ERR_WIN32A(ERROR_KEY_HAS_CHILDREN) + CHK_ERR_WIN32A(ERROR_CHILD_MUST_BE_VOLATILE) + CHK_ERR_WIN32A(ERROR_NOTIFY_ENUM_DIR) + CHK_ERR_WIN32A(ERROR_DEPENDENT_SERVICES_RUNNING) + CHK_ERR_WIN32A(ERROR_INVALID_SERVICE_CONTROL) + CHK_ERR_WIN32A(ERROR_SERVICE_REQUEST_TIMEOUT) + CHK_ERR_WIN32A(ERROR_SERVICE_NO_THREAD) + CHK_ERR_WIN32A(ERROR_SERVICE_DATABASE_LOCKED) + CHK_ERR_WIN32A(ERROR_SERVICE_ALREADY_RUNNING) + CHK_ERR_WIN32A(ERROR_INVALID_SERVICE_ACCOUNT) + CHK_ERR_WIN32A(ERROR_SERVICE_DISABLED) + CHK_ERR_WIN32A(ERROR_CIRCULAR_DEPENDENCY) + CHK_ERR_WIN32A(ERROR_SERVICE_DOES_NOT_EXIST) + CHK_ERR_WIN32A(ERROR_SERVICE_CANNOT_ACCEPT_CTRL) + CHK_ERR_WIN32A(ERROR_SERVICE_NOT_ACTIVE) + CHK_ERR_WIN32A(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) + CHK_ERR_WIN32A(ERROR_EXCEPTION_IN_SERVICE) + CHK_ERR_WIN32A(ERROR_DATABASE_DOES_NOT_EXIST) + CHK_ERR_WIN32A(ERROR_SERVICE_SPECIFIC_ERROR) + CHK_ERR_WIN32A(ERROR_PROCESS_ABORTED) + CHK_ERR_WIN32A(ERROR_SERVICE_DEPENDENCY_FAIL) + CHK_ERR_WIN32A(ERROR_SERVICE_LOGON_FAILED) + CHK_ERR_WIN32A(ERROR_SERVICE_START_HANG) + CHK_ERR_WIN32A(ERROR_INVALID_SERVICE_LOCK) + CHK_ERR_WIN32A(ERROR_SERVICE_MARKED_FOR_DELETE) + CHK_ERR_WIN32A(ERROR_SERVICE_EXISTS) + CHK_ERR_WIN32A(ERROR_ALREADY_RUNNING_LKG) + CHK_ERR_WIN32A(ERROR_SERVICE_DEPENDENCY_DELETED) + CHK_ERR_WIN32A(ERROR_BOOT_ALREADY_ACCEPTED) + CHK_ERR_WIN32A(ERROR_SERVICE_NEVER_STARTED) + CHK_ERR_WIN32A(ERROR_DUPLICATE_SERVICE_NAME) + CHK_ERR_WIN32A(ERROR_DIFFERENT_SERVICE_ACCOUNT) + CHK_ERR_WIN32A(ERROR_CANNOT_DETECT_DRIVER_FAILURE) + CHK_ERR_WIN32A(ERROR_CANNOT_DETECT_PROCESS_ABORT) + CHK_ERR_WIN32A(ERROR_NO_RECOVERY_PROGRAM) + CHK_ERR_WIN32A(ERROR_SERVICE_NOT_IN_EXE) + CHK_ERR_WIN32A(ERROR_END_OF_MEDIA) + CHK_ERR_WIN32A(ERROR_FILEMARK_DETECTED) + CHK_ERR_WIN32A(ERROR_BEGINNING_OF_MEDIA) + CHK_ERR_WIN32A(ERROR_SETMARK_DETECTED) + CHK_ERR_WIN32A(ERROR_NO_DATA_DETECTED) + CHK_ERR_WIN32A(ERROR_PARTITION_FAILURE) + CHK_ERR_WIN32A(ERROR_INVALID_BLOCK_LENGTH) + CHK_ERR_WIN32A(ERROR_DEVICE_NOT_PARTITIONED) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_LOCK_MEDIA) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_UNLOAD_MEDIA) + CHK_ERR_WIN32A(ERROR_MEDIA_CHANGED) + CHK_ERR_WIN32A(ERROR_BUS_RESET) + CHK_ERR_WIN32A(ERROR_NO_MEDIA_IN_DRIVE) + CHK_ERR_WIN32A(ERROR_NO_UNICODE_TRANSLATION) + CHK_ERR_WIN32A(ERROR_DLL_INIT_FAILED) + CHK_ERR_WIN32A(ERROR_SHUTDOWN_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_NO_SHUTDOWN_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_IO_DEVICE) + CHK_ERR_WIN32A(ERROR_SERIAL_NO_DEVICE) + CHK_ERR_WIN32A(ERROR_IRQ_BUSY) + CHK_ERR_WIN32A(ERROR_MORE_WRITES) + CHK_ERR_WIN32A(ERROR_COUNTER_TIMEOUT) + CHK_ERR_WIN32A(ERROR_FLOPPY_ID_MARK_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_FLOPPY_WRONG_CYLINDER) + CHK_ERR_WIN32A(ERROR_FLOPPY_UNKNOWN_ERROR) + CHK_ERR_WIN32A(ERROR_FLOPPY_BAD_REGISTERS) + CHK_ERR_WIN32A(ERROR_DISK_RECALIBRATE_FAILED) + CHK_ERR_WIN32A(ERROR_DISK_OPERATION_FAILED) + CHK_ERR_WIN32A(ERROR_DISK_RESET_FAILED) + CHK_ERR_WIN32A(ERROR_EOM_OVERFLOW) + CHK_ERR_WIN32A(ERROR_NOT_ENOUGH_SERVER_MEMORY) + CHK_ERR_WIN32A(ERROR_POSSIBLE_DEADLOCK) + CHK_ERR_WIN32A(ERROR_MAPPED_ALIGNMENT) + CHK_ERR_WIN32A(ERROR_SET_POWER_STATE_VETOED) + CHK_ERR_WIN32A(ERROR_SET_POWER_STATE_FAILED) + CHK_ERR_WIN32A(ERROR_TOO_MANY_LINKS) + CHK_ERR_WIN32A(ERROR_OLD_WIN_VERSION) + CHK_ERR_WIN32A(ERROR_APP_WRONG_OS) + CHK_ERR_WIN32A(ERROR_SINGLE_INSTANCE_APP) + CHK_ERR_WIN32A(ERROR_RMODE_APP) + CHK_ERR_WIN32A(ERROR_INVALID_DLL) + CHK_ERR_WIN32A(ERROR_NO_ASSOCIATION) + CHK_ERR_WIN32A(ERROR_DDE_FAIL) + CHK_ERR_WIN32A(ERROR_DLL_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NO_MORE_USER_HANDLES) + CHK_ERR_WIN32A(ERROR_MESSAGE_SYNC_ONLY) + CHK_ERR_WIN32A(ERROR_SOURCE_ELEMENT_EMPTY) + CHK_ERR_WIN32A(ERROR_DESTINATION_ELEMENT_FULL) + CHK_ERR_WIN32A(ERROR_ILLEGAL_ELEMENT_ADDRESS) + CHK_ERR_WIN32A(ERROR_MAGAZINE_NOT_PRESENT) + CHK_ERR_WIN32A(ERROR_DEVICE_REINITIALIZATION_NEEDED) + CHK_ERR_WIN32A(ERROR_DEVICE_REQUIRES_CLEANING) + CHK_ERR_WIN32A(ERROR_DEVICE_DOOR_OPEN) + CHK_ERR_WIN32A(ERROR_DEVICE_NOT_CONNECTED) + CHK_ERR_WIN32A(ERROR_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NO_MATCH) + CHK_ERR_WIN32A(ERROR_SET_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_POINT_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NO_TRACKING_SERVICE) + CHK_ERR_WIN32A(ERROR_NO_VOLUME_ID) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_REMOVE_REPLACED) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_MOVE_REPLACEMENT) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_MOVE_REPLACEMENT_2) + CHK_ERR_WIN32A(ERROR_JOURNAL_DELETE_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_JOURNAL_NOT_ACTIVE) + CHK_ERR_WIN32A(ERROR_POTENTIAL_FILE_FOUND) + CHK_ERR_WIN32A(ERROR_BAD_DEVICE) + CHK_ERR_WIN32A(ERROR_CONNECTION_UNAVAIL) + CHK_ERR_WIN32A(ERROR_DEVICE_ALREADY_REMEMBERED) + CHK_ERR_WIN32A(ERROR_NO_NET_OR_BAD_PATH) + CHK_ERR_WIN32A(ERROR_BAD_PROVIDER) + CHK_ERR_WIN32A(ERROR_CANNOT_OPEN_PROFILE) + CHK_ERR_WIN32A(ERROR_BAD_PROFILE) + CHK_ERR_WIN32A(ERROR_NOT_CONTAINER) + CHK_ERR_WIN32A(ERROR_EXTENDED_ERROR) + CHK_ERR_WIN32A(ERROR_INVALID_GROUPNAME) + CHK_ERR_WIN32A(ERROR_INVALID_COMPUTERNAME) + CHK_ERR_WIN32A(ERROR_INVALID_EVENTNAME) + CHK_ERR_WIN32A(ERROR_INVALID_DOMAINNAME) + CHK_ERR_WIN32A(ERROR_INVALID_SERVICENAME) + CHK_ERR_WIN32A(ERROR_INVALID_NETNAME) + CHK_ERR_WIN32A(ERROR_INVALID_SHARENAME) + CHK_ERR_WIN32A(ERROR_INVALID_PASSWORDNAME) + CHK_ERR_WIN32A(ERROR_INVALID_MESSAGENAME) + CHK_ERR_WIN32A(ERROR_INVALID_MESSAGEDEST) + CHK_ERR_WIN32A(ERROR_SESSION_CREDENTIAL_CONFLICT) + CHK_ERR_WIN32A(ERROR_REMOTE_SESSION_LIMIT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DUP_DOMAINNAME) + CHK_ERR_WIN32A(ERROR_NO_NETWORK) + CHK_ERR_WIN32A(ERROR_CANCELLED) + CHK_ERR_WIN32A(ERROR_USER_MAPPED_FILE) + CHK_ERR_WIN32A(ERROR_CONNECTION_REFUSED) + CHK_ERR_WIN32A(ERROR_GRACEFUL_DISCONNECT) + CHK_ERR_WIN32A(ERROR_ADDRESS_ALREADY_ASSOCIATED) + CHK_ERR_WIN32A(ERROR_ADDRESS_NOT_ASSOCIATED) + CHK_ERR_WIN32A(ERROR_CONNECTION_INVALID) + CHK_ERR_WIN32A(ERROR_CONNECTION_ACTIVE) + CHK_ERR_WIN32A(ERROR_NETWORK_UNREACHABLE) + CHK_ERR_WIN32A(ERROR_HOST_UNREACHABLE) + CHK_ERR_WIN32A(ERROR_PROTOCOL_UNREACHABLE) + CHK_ERR_WIN32A(ERROR_PORT_UNREACHABLE) + CHK_ERR_WIN32A(ERROR_REQUEST_ABORTED) + CHK_ERR_WIN32A(ERROR_CONNECTION_ABORTED) + CHK_ERR_WIN32A(ERROR_RETRY) + CHK_ERR_WIN32A(ERROR_CONNECTION_COUNT_LIMIT) + CHK_ERR_WIN32A(ERROR_LOGIN_TIME_RESTRICTION) + CHK_ERR_WIN32A(ERROR_LOGIN_WKSTA_RESTRICTION) + CHK_ERR_WIN32A(ERROR_INCORRECT_ADDRESS) + CHK_ERR_WIN32A(ERROR_ALREADY_REGISTERED) + CHK_ERR_WIN32A(ERROR_SERVICE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NOT_AUTHENTICATED) + CHK_ERR_WIN32A(ERROR_NOT_LOGGED_ON) + CHK_ERR_WIN32A(ERROR_CONTINUE) + CHK_ERR_WIN32A(ERROR_ALREADY_INITIALIZED) + CHK_ERR_WIN32A(ERROR_NO_MORE_DEVICES) + CHK_ERR_WIN32A(ERROR_NO_SUCH_SITE) + CHK_ERR_WIN32A(ERROR_DOMAIN_CONTROLLER_EXISTS) + CHK_ERR_WIN32A(ERROR_NOT_ALL_ASSIGNED) + CHK_ERR_WIN32A(ERROR_SOME_NOT_MAPPED) + CHK_ERR_WIN32A(ERROR_NO_QUOTAS_FOR_ACCOUNT) + CHK_ERR_WIN32A(ERROR_LOCAL_USER_SESSION_KEY) + CHK_ERR_WIN32A(ERROR_NULL_LM_PASSWORD) + CHK_ERR_WIN32A(ERROR_UNKNOWN_REVISION) + CHK_ERR_WIN32A(ERROR_REVISION_MISMATCH) + CHK_ERR_WIN32A(ERROR_INVALID_OWNER) + CHK_ERR_WIN32A(ERROR_INVALID_PRIMARY_GROUP) + CHK_ERR_WIN32A(ERROR_NO_IMPERSONATION_TOKEN) + CHK_ERR_WIN32A(ERROR_CANT_DISABLE_MANDATORY) + CHK_ERR_WIN32A(ERROR_NO_LOGON_SERVERS) + CHK_ERR_WIN32A(ERROR_NO_SUCH_LOGON_SESSION) + CHK_ERR_WIN32A(ERROR_NO_SUCH_PRIVILEGE) + CHK_ERR_WIN32A(ERROR_PRIVILEGE_NOT_HELD) + CHK_ERR_WIN32A(ERROR_INVALID_ACCOUNT_NAME) + CHK_ERR_WIN32A(ERROR_USER_EXISTS) + CHK_ERR_WIN32A(ERROR_NO_SUCH_USER) + CHK_ERR_WIN32A(ERROR_GROUP_EXISTS) + CHK_ERR_WIN32A(ERROR_NO_SUCH_GROUP) + CHK_ERR_WIN32A(ERROR_MEMBER_IN_GROUP) + CHK_ERR_WIN32A(ERROR_MEMBER_NOT_IN_GROUP) + CHK_ERR_WIN32A(ERROR_LAST_ADMIN) + CHK_ERR_WIN32A(ERROR_WRONG_PASSWORD) + CHK_ERR_WIN32A(ERROR_ILL_FORMED_PASSWORD) + CHK_ERR_WIN32A(ERROR_PASSWORD_RESTRICTION) + CHK_ERR_WIN32A(ERROR_LOGON_FAILURE) + CHK_ERR_WIN32A(ERROR_ACCOUNT_RESTRICTION) + CHK_ERR_WIN32A(ERROR_INVALID_LOGON_HOURS) + CHK_ERR_WIN32A(ERROR_INVALID_WORKSTATION) + CHK_ERR_WIN32A(ERROR_PASSWORD_EXPIRED) + CHK_ERR_WIN32A(ERROR_ACCOUNT_DISABLED) + CHK_ERR_WIN32A(ERROR_NONE_MAPPED) + CHK_ERR_WIN32A(ERROR_TOO_MANY_LUIDS_REQUESTED) + CHK_ERR_WIN32A(ERROR_LUIDS_EXHAUSTED) + CHK_ERR_WIN32A(ERROR_INVALID_SUB_AUTHORITY) + CHK_ERR_WIN32A(ERROR_INVALID_ACL) + CHK_ERR_WIN32A(ERROR_INVALID_SID) + CHK_ERR_WIN32A(ERROR_INVALID_SECURITY_DESCR) + CHK_ERR_WIN32A(ERROR_BAD_INHERITANCE_ACL) + CHK_ERR_WIN32A(ERROR_SERVER_DISABLED) + CHK_ERR_WIN32A(ERROR_SERVER_NOT_DISABLED) + CHK_ERR_WIN32A(ERROR_INVALID_ID_AUTHORITY) + CHK_ERR_WIN32A(ERROR_ALLOTTED_SPACE_EXCEEDED) + CHK_ERR_WIN32A(ERROR_INVALID_GROUP_ATTRIBUTES) + CHK_ERR_WIN32A(ERROR_BAD_IMPERSONATION_LEVEL) + CHK_ERR_WIN32A(ERROR_CANT_OPEN_ANONYMOUS) + CHK_ERR_WIN32A(ERROR_BAD_VALIDATION_CLASS) + CHK_ERR_WIN32A(ERROR_BAD_TOKEN_TYPE) + CHK_ERR_WIN32A(ERROR_NO_SECURITY_ON_OBJECT) + CHK_ERR_WIN32A(ERROR_CANT_ACCESS_DOMAIN_INFO) + CHK_ERR_WIN32A(ERROR_INVALID_SERVER_STATE) + CHK_ERR_WIN32A(ERROR_INVALID_DOMAIN_STATE) + CHK_ERR_WIN32A(ERROR_INVALID_DOMAIN_ROLE) + CHK_ERR_WIN32A(ERROR_NO_SUCH_DOMAIN) + CHK_ERR_WIN32A(ERROR_DOMAIN_EXISTS) + CHK_ERR_WIN32A(ERROR_DOMAIN_LIMIT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_INTERNAL_DB_CORRUPTION) + CHK_ERR_WIN32A(ERROR_INTERNAL_ERROR) + CHK_ERR_WIN32A(ERROR_GENERIC_NOT_MAPPED) + CHK_ERR_WIN32A(ERROR_BAD_DESCRIPTOR_FORMAT) + CHK_ERR_WIN32A(ERROR_NOT_LOGON_PROCESS) + CHK_ERR_WIN32A(ERROR_LOGON_SESSION_EXISTS) + CHK_ERR_WIN32A(ERROR_NO_SUCH_PACKAGE) + CHK_ERR_WIN32A(ERROR_BAD_LOGON_SESSION_STATE) + CHK_ERR_WIN32A(ERROR_LOGON_SESSION_COLLISION) + CHK_ERR_WIN32A(ERROR_INVALID_LOGON_TYPE) + CHK_ERR_WIN32A(ERROR_CANNOT_IMPERSONATE) + CHK_ERR_WIN32A(ERROR_RXACT_INVALID_STATE) + CHK_ERR_WIN32A(ERROR_RXACT_COMMIT_FAILURE) + CHK_ERR_WIN32A(ERROR_SPECIAL_ACCOUNT) + CHK_ERR_WIN32A(ERROR_SPECIAL_GROUP) + CHK_ERR_WIN32A(ERROR_SPECIAL_USER) + CHK_ERR_WIN32A(ERROR_MEMBERS_PRIMARY_GROUP) + CHK_ERR_WIN32A(ERROR_TOKEN_ALREADY_IN_USE) + CHK_ERR_WIN32A(ERROR_NO_SUCH_ALIAS) + CHK_ERR_WIN32A(ERROR_MEMBER_NOT_IN_ALIAS) + CHK_ERR_WIN32A(ERROR_MEMBER_IN_ALIAS) + CHK_ERR_WIN32A(ERROR_ALIAS_EXISTS) + CHK_ERR_WIN32A(ERROR_LOGON_NOT_GRANTED) + CHK_ERR_WIN32A(ERROR_TOO_MANY_SECRETS) + CHK_ERR_WIN32A(ERROR_SECRET_TOO_LONG) + CHK_ERR_WIN32A(ERROR_INTERNAL_DB_ERROR) + CHK_ERR_WIN32A(ERROR_TOO_MANY_CONTEXT_IDS) + CHK_ERR_WIN32A(ERROR_LOGON_TYPE_NOT_GRANTED) + CHK_ERR_WIN32A(ERROR_NT_CROSS_ENCRYPTION_REQUIRED) + CHK_ERR_WIN32A(ERROR_NO_SUCH_MEMBER) + CHK_ERR_WIN32A(ERROR_INVALID_MEMBER) + CHK_ERR_WIN32A(ERROR_TOO_MANY_SIDS) + CHK_ERR_WIN32A(ERROR_LM_CROSS_ENCRYPTION_REQUIRED) + CHK_ERR_WIN32A(ERROR_NO_INHERITANCE) + CHK_ERR_WIN32A(ERROR_FILE_CORRUPT) + CHK_ERR_WIN32A(ERROR_DISK_CORRUPT) + CHK_ERR_WIN32A(ERROR_NO_USER_SESSION_KEY) + CHK_ERR_WIN32A(ERROR_LICENSE_QUOTA_EXCEEDED) + CHK_ERR_WIN32A(ERROR_WRONG_TARGET_NAME) + CHK_ERR_WIN32A(ERROR_MUTUAL_AUTH_FAILED) + CHK_ERR_WIN32A(ERROR_TIME_SKEW) + CHK_ERR_WIN32A(ERROR_INVALID_WINDOW_HANDLE) + CHK_ERR_WIN32A(ERROR_INVALID_MENU_HANDLE) + CHK_ERR_WIN32A(ERROR_INVALID_CURSOR_HANDLE) + CHK_ERR_WIN32A(ERROR_INVALID_ACCEL_HANDLE) + CHK_ERR_WIN32A(ERROR_INVALID_HOOK_HANDLE) + CHK_ERR_WIN32A(ERROR_INVALID_DWP_HANDLE) + CHK_ERR_WIN32A(ERROR_TLW_WITH_WSCHILD) + CHK_ERR_WIN32A(ERROR_CANNOT_FIND_WND_CLASS) + CHK_ERR_WIN32A(ERROR_WINDOW_OF_OTHER_THREAD) + CHK_ERR_WIN32A(ERROR_HOTKEY_ALREADY_REGISTERED) + CHK_ERR_WIN32A(ERROR_CLASS_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_CLASS_DOES_NOT_EXIST) + CHK_ERR_WIN32A(ERROR_CLASS_HAS_WINDOWS) + CHK_ERR_WIN32A(ERROR_INVALID_INDEX) + CHK_ERR_WIN32A(ERROR_INVALID_ICON_HANDLE) + CHK_ERR_WIN32A(ERROR_PRIVATE_DIALOG_INDEX) + CHK_ERR_WIN32A(ERROR_LISTBOX_ID_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NO_WILDCARD_CHARACTERS) + CHK_ERR_WIN32A(ERROR_CLIPBOARD_NOT_OPEN) + CHK_ERR_WIN32A(ERROR_HOTKEY_NOT_REGISTERED) + CHK_ERR_WIN32A(ERROR_WINDOW_NOT_DIALOG) + CHK_ERR_WIN32A(ERROR_CONTROL_ID_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_INVALID_COMBOBOX_MESSAGE) + CHK_ERR_WIN32A(ERROR_WINDOW_NOT_COMBOBOX) + CHK_ERR_WIN32A(ERROR_INVALID_EDIT_HEIGHT) + CHK_ERR_WIN32A(ERROR_DC_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_INVALID_HOOK_FILTER) + CHK_ERR_WIN32A(ERROR_INVALID_FILTER_PROC) + CHK_ERR_WIN32A(ERROR_HOOK_NEEDS_HMOD) + CHK_ERR_WIN32A(ERROR_GLOBAL_ONLY_HOOK) + CHK_ERR_WIN32A(ERROR_JOURNAL_HOOK_SET) + CHK_ERR_WIN32A(ERROR_HOOK_NOT_INSTALLED) + CHK_ERR_WIN32A(ERROR_INVALID_LB_MESSAGE) + CHK_ERR_WIN32A(ERROR_SETCOUNT_ON_BAD_LB) + CHK_ERR_WIN32A(ERROR_LB_WITHOUT_TABSTOPS) + CHK_ERR_WIN32A(ERROR_DESTROY_OBJECT_OF_OTHER_THREAD) + CHK_ERR_WIN32A(ERROR_CHILD_WINDOW_MENU) + CHK_ERR_WIN32A(ERROR_NO_SYSTEM_MENU) + CHK_ERR_WIN32A(ERROR_INVALID_MSGBOX_STYLE) + CHK_ERR_WIN32A(ERROR_INVALID_SPI_VALUE) + CHK_ERR_WIN32A(ERROR_SCREEN_ALREADY_LOCKED) + CHK_ERR_WIN32A(ERROR_HWNDS_HAVE_DIFF_PARENT) + CHK_ERR_WIN32A(ERROR_NOT_CHILD_WINDOW) + CHK_ERR_WIN32A(ERROR_INVALID_GW_COMMAND) + CHK_ERR_WIN32A(ERROR_INVALID_THREAD_ID) + CHK_ERR_WIN32A(ERROR_NON_MDICHILD_WINDOW) + CHK_ERR_WIN32A(ERROR_POPUP_ALREADY_ACTIVE) + CHK_ERR_WIN32A(ERROR_NO_SCROLLBARS) + CHK_ERR_WIN32A(ERROR_INVALID_SCROLLBAR_RANGE) + CHK_ERR_WIN32A(ERROR_INVALID_SHOWWIN_COMMAND) + CHK_ERR_WIN32A(ERROR_NO_SYSTEM_RESOURCES) + CHK_ERR_WIN32A(ERROR_NONPAGED_SYSTEM_RESOURCES) + CHK_ERR_WIN32A(ERROR_PAGED_SYSTEM_RESOURCES) + CHK_ERR_WIN32A(ERROR_WORKING_SET_QUOTA) + CHK_ERR_WIN32A(ERROR_PAGEFILE_QUOTA) + CHK_ERR_WIN32A(ERROR_COMMITMENT_LIMIT) + CHK_ERR_WIN32A(ERROR_MENU_ITEM_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_INVALID_KEYBOARD_HANDLE) + CHK_ERR_WIN32A(ERROR_HOOK_TYPE_NOT_ALLOWED) + CHK_ERR_WIN32A(ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION) + CHK_ERR_WIN32A(ERROR_TIMEOUT) + CHK_ERR_WIN32A(ERROR_INVALID_MONITOR_HANDLE) + CHK_ERR_WIN32A(ERROR_EVENTLOG_FILE_CORRUPT) + CHK_ERR_WIN32A(ERROR_EVENTLOG_CANT_START) + CHK_ERR_WIN32A(ERROR_LOG_FILE_FULL) + CHK_ERR_WIN32A(ERROR_EVENTLOG_FILE_CHANGED) + CHK_ERR_WIN32A(ERROR_INSTALL_USEREXIT) + CHK_ERR_WIN32A(ERROR_INSTALL_FAILURE) + CHK_ERR_WIN32A(ERROR_INSTALL_SUSPEND) + CHK_ERR_WIN32A(ERROR_UNKNOWN_PRODUCT) + CHK_ERR_WIN32A(ERROR_UNKNOWN_FEATURE) + CHK_ERR_WIN32A(ERROR_UNKNOWN_COMPONENT) + CHK_ERR_WIN32A(ERROR_UNKNOWN_PROPERTY) + CHK_ERR_WIN32A(ERROR_INVALID_HANDLE_STATE) + CHK_ERR_WIN32A(ERROR_BAD_CONFIGURATION) + CHK_ERR_WIN32A(ERROR_INDEX_ABSENT) + CHK_ERR_WIN32A(ERROR_INSTALL_SOURCE_ABSENT) + CHK_ERR_WIN32A(ERROR_PRODUCT_UNINSTALLED) + CHK_ERR_WIN32A(ERROR_BAD_QUERY_SYNTAX) + CHK_ERR_WIN32A(ERROR_INVALID_FIELD) + CHK_ERR_WIN32A(ERROR_DEVICE_REMOVED) + CHK_ERR_WIN32A(RPC_S_INVALID_STRING_BINDING) + CHK_ERR_WIN32A(RPC_S_WRONG_KIND_OF_BINDING) + CHK_ERR_WIN32A(RPC_S_INVALID_BINDING) + CHK_ERR_WIN32A(RPC_S_PROTSEQ_NOT_SUPPORTED) + CHK_ERR_WIN32A(RPC_S_INVALID_RPC_PROTSEQ) + CHK_ERR_WIN32A(RPC_S_INVALID_STRING_UUID) + CHK_ERR_WIN32A(RPC_S_INVALID_ENDPOINT_FORMAT) + CHK_ERR_WIN32A(RPC_S_INVALID_NET_ADDR) + CHK_ERR_WIN32A(RPC_S_NO_ENDPOINT_FOUND) + CHK_ERR_WIN32A(RPC_S_INVALID_TIMEOUT) + CHK_ERR_WIN32A(RPC_S_OBJECT_NOT_FOUND) + CHK_ERR_WIN32A(RPC_S_ALREADY_REGISTERED) + CHK_ERR_WIN32A(RPC_S_TYPE_ALREADY_REGISTERED) + CHK_ERR_WIN32A(RPC_S_ALREADY_LISTENING) + CHK_ERR_WIN32A(RPC_S_NO_PROTSEQS_REGISTERED) + CHK_ERR_WIN32A(RPC_S_NOT_LISTENING) + CHK_ERR_WIN32A(RPC_S_UNKNOWN_MGR_TYPE) + CHK_ERR_WIN32A(RPC_S_UNKNOWN_IF) + CHK_ERR_WIN32A(RPC_S_NO_BINDINGS) + CHK_ERR_WIN32A(RPC_S_NO_PROTSEQS) + CHK_ERR_WIN32A(RPC_S_CANT_CREATE_ENDPOINT) + CHK_ERR_WIN32A(RPC_S_OUT_OF_RESOURCES) + CHK_ERR_WIN32A(RPC_S_SERVER_UNAVAILABLE) + CHK_ERR_WIN32A(RPC_S_SERVER_TOO_BUSY) + CHK_ERR_WIN32A(RPC_S_INVALID_NETWORK_OPTIONS) + CHK_ERR_WIN32A(RPC_S_NO_CALL_ACTIVE) + CHK_ERR_WIN32A(RPC_S_CALL_FAILED) + CHK_ERR_WIN32A(RPC_S_CALL_FAILED_DNE) + CHK_ERR_WIN32A(RPC_S_PROTOCOL_ERROR) + CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_TRANS_SYN) + CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_TYPE) + CHK_ERR_WIN32A(RPC_S_INVALID_TAG) + CHK_ERR_WIN32A(RPC_S_INVALID_BOUND) + CHK_ERR_WIN32A(RPC_S_NO_ENTRY_NAME) + CHK_ERR_WIN32A(RPC_S_INVALID_NAME_SYNTAX) + CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_NAME_SYNTAX) + CHK_ERR_WIN32A(RPC_S_UUID_NO_ADDRESS) + CHK_ERR_WIN32A(RPC_S_DUPLICATE_ENDPOINT) + CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHN_TYPE) + CHK_ERR_WIN32A(RPC_S_MAX_CALLS_TOO_SMALL) + CHK_ERR_WIN32A(RPC_S_STRING_TOO_LONG) + CHK_ERR_WIN32A(RPC_S_PROTSEQ_NOT_FOUND) + CHK_ERR_WIN32A(RPC_S_PROCNUM_OUT_OF_RANGE) + CHK_ERR_WIN32A(RPC_S_BINDING_HAS_NO_AUTH) + CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHN_SERVICE) + CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHN_LEVEL) + CHK_ERR_WIN32A(RPC_S_INVALID_AUTH_IDENTITY) + CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHZ_SERVICE) + CHK_ERR_WIN32A(EPT_S_INVALID_ENTRY) + CHK_ERR_WIN32A(EPT_S_CANT_PERFORM_OP) + CHK_ERR_WIN32A(EPT_S_NOT_REGISTERED) + CHK_ERR_WIN32A(RPC_S_NOTHING_TO_EXPORT) + CHK_ERR_WIN32A(RPC_S_INCOMPLETE_NAME) + CHK_ERR_WIN32A(RPC_S_INVALID_VERS_OPTION) + CHK_ERR_WIN32A(RPC_S_NO_MORE_MEMBERS) + CHK_ERR_WIN32A(RPC_S_NOT_ALL_OBJS_UNEXPORTED) + CHK_ERR_WIN32A(RPC_S_INTERFACE_NOT_FOUND) + CHK_ERR_WIN32A(RPC_S_ENTRY_ALREADY_EXISTS) + CHK_ERR_WIN32A(RPC_S_ENTRY_NOT_FOUND) + CHK_ERR_WIN32A(RPC_S_NAME_SERVICE_UNAVAILABLE) + CHK_ERR_WIN32A(RPC_S_INVALID_NAF_ID) + CHK_ERR_WIN32A(RPC_S_CANNOT_SUPPORT) + CHK_ERR_WIN32A(RPC_S_NO_CONTEXT_AVAILABLE) + CHK_ERR_WIN32A(RPC_S_INTERNAL_ERROR) + CHK_ERR_WIN32A(RPC_S_ZERO_DIVIDE) + CHK_ERR_WIN32A(RPC_S_ADDRESS_ERROR) + CHK_ERR_WIN32A(RPC_S_FP_DIV_ZERO) + CHK_ERR_WIN32A(RPC_S_FP_UNDERFLOW) + CHK_ERR_WIN32A(RPC_S_FP_OVERFLOW) + CHK_ERR_WIN32A(RPC_X_NO_MORE_ENTRIES) + CHK_ERR_WIN32A(RPC_X_SS_CHAR_TRANS_OPEN_FAIL) + CHK_ERR_WIN32A(RPC_X_SS_CHAR_TRANS_SHORT_FILE) + CHK_ERR_WIN32A(RPC_X_SS_IN_NULL_CONTEXT) + CHK_ERR_WIN32A(RPC_X_SS_CONTEXT_DAMAGED) + CHK_ERR_WIN32A(RPC_X_SS_HANDLES_MISMATCH) + CHK_ERR_WIN32A(RPC_X_SS_CANNOT_GET_CALL_HANDLE) + CHK_ERR_WIN32A(RPC_X_NULL_REF_POINTER) + CHK_ERR_WIN32A(RPC_X_ENUM_VALUE_OUT_OF_RANGE) + CHK_ERR_WIN32A(RPC_X_BYTE_COUNT_TOO_SMALL) + CHK_ERR_WIN32A(RPC_X_BAD_STUB_DATA) + CHK_ERR_WIN32A(ERROR_INVALID_USER_BUFFER) + CHK_ERR_WIN32A(ERROR_UNRECOGNIZED_MEDIA) + CHK_ERR_WIN32A(ERROR_NO_TRUST_LSA_SECRET) + CHK_ERR_WIN32A(ERROR_NO_TRUST_SAM_ACCOUNT) + CHK_ERR_WIN32A(ERROR_TRUSTED_DOMAIN_FAILURE) + CHK_ERR_WIN32A(ERROR_TRUSTED_RELATIONSHIP_FAILURE) + CHK_ERR_WIN32A(ERROR_TRUST_FAILURE) + CHK_ERR_WIN32A(RPC_S_CALL_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_NETLOGON_NOT_STARTED) + CHK_ERR_WIN32A(ERROR_ACCOUNT_EXPIRED) + CHK_ERR_WIN32A(ERROR_REDIRECTOR_HAS_OPEN_HANDLES) + CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_ALREADY_INSTALLED) + CHK_ERR_WIN32A(ERROR_UNKNOWN_PORT) + CHK_ERR_WIN32A(ERROR_UNKNOWN_PRINTER_DRIVER) + CHK_ERR_WIN32A(ERROR_UNKNOWN_PRINTPROCESSOR) + CHK_ERR_WIN32A(ERROR_INVALID_SEPARATOR_FILE) + CHK_ERR_WIN32A(ERROR_INVALID_PRIORITY) + CHK_ERR_WIN32A(ERROR_INVALID_PRINTER_NAME) + CHK_ERR_WIN32A(ERROR_PRINTER_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_INVALID_PRINTER_COMMAND) + CHK_ERR_WIN32A(ERROR_INVALID_DATATYPE) + CHK_ERR_WIN32A(ERROR_INVALID_ENVIRONMENT) + CHK_ERR_WIN32A(RPC_S_NO_MORE_BINDINGS) + CHK_ERR_WIN32A(ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT) + CHK_ERR_WIN32A(ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT) + CHK_ERR_WIN32A(ERROR_NOLOGON_SERVER_TRUST_ACCOUNT) + CHK_ERR_WIN32A(ERROR_DOMAIN_TRUST_INCONSISTENT) + CHK_ERR_WIN32A(ERROR_SERVER_HAS_OPEN_HANDLES) + CHK_ERR_WIN32A(ERROR_RESOURCE_DATA_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_RESOURCE_TYPE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_RESOURCE_NAME_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_RESOURCE_LANG_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NOT_ENOUGH_QUOTA) + CHK_ERR_WIN32A(RPC_S_NO_INTERFACES) + CHK_ERR_WIN32A(RPC_S_CALL_CANCELLED) + CHK_ERR_WIN32A(RPC_S_BINDING_INCOMPLETE) + CHK_ERR_WIN32A(RPC_S_COMM_FAILURE) + CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_AUTHN_LEVEL) + CHK_ERR_WIN32A(RPC_S_NO_PRINC_NAME) + CHK_ERR_WIN32A(RPC_S_NOT_RPC_ERROR) + CHK_ERR_WIN32A(RPC_S_UUID_LOCAL_ONLY) + CHK_ERR_WIN32A(RPC_S_SEC_PKG_ERROR) + CHK_ERR_WIN32A(RPC_S_NOT_CANCELLED) + CHK_ERR_WIN32A(RPC_X_INVALID_ES_ACTION) + CHK_ERR_WIN32A(RPC_X_WRONG_ES_VERSION) + CHK_ERR_WIN32A(RPC_X_WRONG_STUB_VERSION) + CHK_ERR_WIN32A(RPC_X_INVALID_PIPE_OBJECT) + CHK_ERR_WIN32A(RPC_X_WRONG_PIPE_ORDER) + CHK_ERR_WIN32A(RPC_X_WRONG_PIPE_VERSION) + CHK_ERR_WIN32A(RPC_S_GROUP_MEMBER_NOT_FOUND) + CHK_ERR_WIN32A(EPT_S_CANT_CREATE) + CHK_ERR_WIN32A(RPC_S_INVALID_OBJECT) + CHK_ERR_WIN32A(ERROR_INVALID_TIME) + CHK_ERR_WIN32A(ERROR_INVALID_FORM_NAME) + CHK_ERR_WIN32A(ERROR_INVALID_FORM_SIZE) + CHK_ERR_WIN32A(ERROR_ALREADY_WAITING) + CHK_ERR_WIN32A(ERROR_PRINTER_DELETED) + CHK_ERR_WIN32A(ERROR_INVALID_PRINTER_STATE) + CHK_ERR_WIN32A(ERROR_PASSWORD_MUST_CHANGE) + CHK_ERR_WIN32A(ERROR_DOMAIN_CONTROLLER_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_ACCOUNT_LOCKED_OUT) + CHK_ERR_WIN32A(OR_INVALID_OXID) + CHK_ERR_WIN32A(OR_INVALID_OID) + CHK_ERR_WIN32A(OR_INVALID_SET) + CHK_ERR_WIN32A(RPC_S_SEND_INCOMPLETE) + CHK_ERR_WIN32A(RPC_S_INVALID_ASYNC_HANDLE) + CHK_ERR_WIN32A(RPC_S_INVALID_ASYNC_CALL) + CHK_ERR_WIN32A(RPC_X_PIPE_CLOSED) + CHK_ERR_WIN32A(RPC_X_PIPE_DISCIPLINE_ERROR) + CHK_ERR_WIN32A(RPC_X_PIPE_EMPTY) + CHK_ERR_WIN32A(ERROR_NO_SITENAME) + CHK_ERR_WIN32A(ERROR_CANT_ACCESS_FILE) + CHK_ERR_WIN32A(ERROR_CANT_RESOLVE_FILENAME) + CHK_ERR_WIN32A(ERROR_INVALID_PIXEL_FORMAT) + CHK_ERR_WIN32A(ERROR_BAD_DRIVER) + CHK_ERR_WIN32A(ERROR_INVALID_WINDOW_STYLE) + CHK_ERR_WIN32A(ERROR_METAFILE_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_TRANSFORM_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_CLIPPING_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_INVALID_CMM) + CHK_ERR_WIN32A(ERROR_INVALID_PROFILE) + CHK_ERR_WIN32A(ERROR_TAG_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_TAG_NOT_PRESENT) + CHK_ERR_WIN32A(ERROR_DUPLICATE_TAG) + CHK_ERR_WIN32A(ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE) + CHK_ERR_WIN32A(ERROR_PROFILE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_INVALID_COLORSPACE) + CHK_ERR_WIN32A(ERROR_ICM_NOT_ENABLED) + CHK_ERR_WIN32A(ERROR_DELETING_ICM_XFORM) + CHK_ERR_WIN32A(ERROR_INVALID_TRANSFORM) + CHK_ERR_WIN32A(ERROR_COLORSPACE_MISMATCH) + CHK_ERR_WIN32A(ERROR_INVALID_COLORINDEX) + CHK_ERR_WIN32A(ERROR_CONNECTED_OTHER_PASSWORD) + CHK_ERR_WIN32A(ERROR_BAD_USERNAME) + CHK_ERR_WIN32A(ERROR_NOT_CONNECTED) + CHK_ERR_WIN32A(ERROR_OPEN_FILES) + CHK_ERR_WIN32A(ERROR_ACTIVE_CONNECTIONS) + CHK_ERR_WIN32A(ERROR_DEVICE_IN_USE) + CHK_ERR_WIN32A(ERROR_UNKNOWN_PRINT_MONITOR) + CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_IN_USE) + CHK_ERR_WIN32A(ERROR_SPOOL_FILE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_SPL_NO_STARTDOC) + CHK_ERR_WIN32A(ERROR_SPL_NO_ADDJOB) + CHK_ERR_WIN32A(ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED) + CHK_ERR_WIN32A(ERROR_PRINT_MONITOR_ALREADY_INSTALLED) + CHK_ERR_WIN32A(ERROR_INVALID_PRINT_MONITOR) + CHK_ERR_WIN32A(ERROR_PRINT_MONITOR_IN_USE) + CHK_ERR_WIN32A(ERROR_PRINTER_HAS_JOBS_QUEUED) + CHK_ERR_WIN32A(ERROR_SUCCESS_REBOOT_REQUIRED) + CHK_ERR_WIN32A(ERROR_SUCCESS_RESTART_REQUIRED) + CHK_ERR_WIN32A(ERROR_PRINTER_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_WINS_INTERNAL) + CHK_ERR_WIN32A(ERROR_CAN_NOT_DEL_LOCAL_WINS) + CHK_ERR_WIN32A(ERROR_STATIC_INIT) + CHK_ERR_WIN32A(ERROR_INC_BACKUP) + CHK_ERR_WIN32A(ERROR_FULL_BACKUP) + CHK_ERR_WIN32A(ERROR_REC_NON_EXISTENT) + CHK_ERR_WIN32A(ERROR_RPL_NOT_ALLOWED) + CHK_ERR_WIN32A(ERROR_DHCP_ADDRESS_CONFLICT) + CHK_ERR_WIN32A(ERROR_WMI_GUID_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_WMI_INSTANCE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_WMI_ITEMID_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_WMI_TRY_AGAIN) + CHK_ERR_WIN32A(ERROR_WMI_DP_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_WMI_UNRESOLVED_INSTANCE_REF) + CHK_ERR_WIN32A(ERROR_WMI_ALREADY_ENABLED) + CHK_ERR_WIN32A(ERROR_WMI_GUID_DISCONNECTED) + CHK_ERR_WIN32A(ERROR_WMI_SERVER_UNAVAILABLE) + CHK_ERR_WIN32A(ERROR_WMI_DP_FAILED) + CHK_ERR_WIN32A(ERROR_WMI_INVALID_MOF) + CHK_ERR_WIN32A(ERROR_WMI_INVALID_REGINFO) + CHK_ERR_WIN32A(ERROR_WMI_ALREADY_DISABLED) + CHK_ERR_WIN32A(ERROR_WMI_READ_ONLY) + CHK_ERR_WIN32A(ERROR_WMI_SET_FAILURE) + CHK_ERR_WIN32A(ERROR_INVALID_MEDIA) + CHK_ERR_WIN32A(ERROR_INVALID_LIBRARY) + CHK_ERR_WIN32A(ERROR_INVALID_MEDIA_POOL) + CHK_ERR_WIN32A(ERROR_DRIVE_MEDIA_MISMATCH) + CHK_ERR_WIN32A(ERROR_MEDIA_OFFLINE) + CHK_ERR_WIN32A(ERROR_LIBRARY_OFFLINE) + CHK_ERR_WIN32A(ERROR_EMPTY) + CHK_ERR_WIN32A(ERROR_NOT_EMPTY) + CHK_ERR_WIN32A(ERROR_MEDIA_UNAVAILABLE) + CHK_ERR_WIN32A(ERROR_RESOURCE_DISABLED) + CHK_ERR_WIN32A(ERROR_INVALID_CLEANER) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_CLEAN) + CHK_ERR_WIN32A(ERROR_OBJECT_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_DATABASE_FAILURE) + CHK_ERR_WIN32A(ERROR_DATABASE_FULL) + CHK_ERR_WIN32A(ERROR_MEDIA_INCOMPATIBLE) + CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_PRESENT) + CHK_ERR_WIN32A(ERROR_INVALID_OPERATION) + CHK_ERR_WIN32A(ERROR_MEDIA_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_DEVICE_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_REQUEST_REFUSED) + CHK_ERR_WIN32A(ERROR_INVALID_DRIVE_OBJECT) + CHK_ERR_WIN32A(ERROR_LIBRARY_FULL) + CHK_ERR_WIN32A(ERROR_MEDIUM_NOT_ACCESSIBLE) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_LOAD_MEDIUM) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_INVENTORY_DRIVE) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_INVENTORY_SLOT) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_INVENTORY_TRANSPORT) + CHK_ERR_WIN32A(ERROR_TRANSPORT_FULL) + CHK_ERR_WIN32A(ERROR_CONTROLLING_IEPORT) + CHK_ERR_WIN32A(ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA) + CHK_ERR_WIN32A(ERROR_CLEANER_SLOT_SET) + CHK_ERR_WIN32A(ERROR_CLEANER_SLOT_NOT_SET) + CHK_ERR_WIN32A(ERROR_CLEANER_CARTRIDGE_SPENT) + CHK_ERR_WIN32A(ERROR_UNEXPECTED_OMID) + CHK_ERR_WIN32A(ERROR_CANT_DELETE_LAST_ITEM) + CHK_ERR_WIN32A(ERROR_MESSAGE_EXCEEDS_MAX_SIZE) + CHK_ERR_WIN32A(ERROR_FILE_OFFLINE) + CHK_ERR_WIN32A(ERROR_REMOTE_STORAGE_NOT_ACTIVE) + CHK_ERR_WIN32A(ERROR_REMOTE_STORAGE_MEDIA_ERROR) + CHK_ERR_WIN32A(ERROR_NOT_A_REPARSE_POINT) + CHK_ERR_WIN32A(ERROR_REPARSE_ATTRIBUTE_CONFLICT) + CHK_ERR_WIN32A(ERROR_INVALID_REPARSE_DATA) + CHK_ERR_WIN32A(ERROR_DEPENDENT_RESOURCE_EXISTS) + CHK_ERR_WIN32A(ERROR_DEPENDENCY_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_DEPENDENCY_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_ONLINE) + CHK_ERR_WIN32A(ERROR_HOST_NODE_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_SHUTDOWN_CLUSTER) + CHK_ERR_WIN32A(ERROR_CANT_EVICT_ACTIVE_NODE) + CHK_ERR_WIN32A(ERROR_OBJECT_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_OBJECT_IN_LIST) + CHK_ERR_WIN32A(ERROR_GROUP_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_GROUP_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_GROUP_NOT_ONLINE) + CHK_ERR_WIN32A(ERROR_HOST_NODE_NOT_RESOURCE_OWNER) + CHK_ERR_WIN32A(ERROR_HOST_NODE_NOT_GROUP_OWNER) + CHK_ERR_WIN32A(ERROR_RESMON_CREATE_FAILED) + CHK_ERR_WIN32A(ERROR_RESMON_ONLINE_FAILED) + CHK_ERR_WIN32A(ERROR_RESOURCE_ONLINE) + CHK_ERR_WIN32A(ERROR_QUORUM_RESOURCE) + CHK_ERR_WIN32A(ERROR_NOT_QUORUM_CAPABLE) + CHK_ERR_WIN32A(ERROR_CLUSTER_SHUTTING_DOWN) + CHK_ERR_WIN32A(ERROR_INVALID_STATE) + CHK_ERR_WIN32A(ERROR_RESOURCE_PROPERTIES_STORED) + CHK_ERR_WIN32A(ERROR_NOT_QUORUM_CLASS) + CHK_ERR_WIN32A(ERROR_CORE_RESOURCE) + CHK_ERR_WIN32A(ERROR_QUORUM_RESOURCE_ONLINE_FAILED) + CHK_ERR_WIN32A(ERROR_QUORUMLOG_OPEN_FAILED) + CHK_ERR_WIN32A(ERROR_CLUSTERLOG_CORRUPT) + CHK_ERR_WIN32A(ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE) + CHK_ERR_WIN32A(ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE) + CHK_ERR_WIN32A(ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE) + CHK_ERR_WIN32A(ERROR_ENCRYPTION_FAILED) + CHK_ERR_WIN32A(ERROR_DECRYPTION_FAILED) + CHK_ERR_WIN32A(ERROR_FILE_ENCRYPTED) + CHK_ERR_WIN32A(ERROR_NO_RECOVERY_POLICY) + CHK_ERR_WIN32A(ERROR_NO_EFS) + CHK_ERR_WIN32A(ERROR_WRONG_EFS) + CHK_ERR_WIN32A(ERROR_NO_USER_KEYS) + CHK_ERR_WIN32A(ERROR_FILE_NOT_ENCRYPTED) + CHK_ERR_WIN32A(ERROR_NOT_EXPORT_FORMAT) + CHK_ERR_WIN32A(ERROR_NO_BROWSER_SERVERS_FOUND) + CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_NAME_INVALID) + CHK_ERR_WIN32A(ERROR_CTX_INVALID_PD) + CHK_ERR_WIN32A(ERROR_CTX_PD_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CTX_WD_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY) + CHK_ERR_WIN32A(ERROR_CTX_SERVICE_NAME_COLLISION) + CHK_ERR_WIN32A(ERROR_CTX_CLOSE_PENDING) + CHK_ERR_WIN32A(ERROR_CTX_NO_OUTBUF) + CHK_ERR_WIN32A(ERROR_CTX_MODEM_INF_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CTX_INVALID_MODEMNAME) + CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_ERROR) + CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_TIMEOUT) + CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_NO_CARRIER) + CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE) + CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_BUSY) + CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_VOICE) + CHK_ERR_WIN32A(ERROR_CTX_TD_ERROR) + CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_BUSY) + CHK_ERR_WIN32A(ERROR_CTX_BAD_VIDEO_MODE) + CHK_ERR_WIN32A(ERROR_CTX_GRAPHICS_INVALID) + CHK_ERR_WIN32A(ERROR_CTX_LOGON_DISABLED) + CHK_ERR_WIN32A(ERROR_CTX_NOT_CONSOLE) + CHK_ERR_WIN32A(ERROR_CTX_CLIENT_QUERY_TIMEOUT) + CHK_ERR_WIN32A(ERROR_CTX_CONSOLE_DISCONNECT) + CHK_ERR_WIN32A(ERROR_CTX_CONSOLE_CONNECT) + CHK_ERR_WIN32A(ERROR_CTX_SHADOW_DENIED) + CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_ACCESS_DENIED) + CHK_ERR_WIN32A(ERROR_CTX_INVALID_WD) + CHK_ERR_WIN32A(ERROR_CTX_SHADOW_INVALID) + CHK_ERR_WIN32A(ERROR_CTX_SHADOW_DISABLED) + CHK_ERR_WIN32A(FRS_ERR_INVALID_API_SEQUENCE) + CHK_ERR_WIN32A(FRS_ERR_STARTING_SERVICE) + CHK_ERR_WIN32A(FRS_ERR_STOPPING_SERVICE) + CHK_ERR_WIN32A(FRS_ERR_INTERNAL_API) + CHK_ERR_WIN32A(FRS_ERR_INTERNAL) + CHK_ERR_WIN32A(FRS_ERR_SERVICE_COMM) + CHK_ERR_WIN32A(FRS_ERR_INSUFFICIENT_PRIV) + CHK_ERR_WIN32A(FRS_ERR_AUTHENTICATION) + CHK_ERR_WIN32A(FRS_ERR_PARENT_INSUFFICIENT_PRIV) + CHK_ERR_WIN32A(FRS_ERR_PARENT_AUTHENTICATION) + CHK_ERR_WIN32A(FRS_ERR_CHILD_TO_PARENT_COMM) + CHK_ERR_WIN32A(FRS_ERR_PARENT_TO_CHILD_COMM) + CHK_ERR_WIN32A(FRS_ERR_SYSVOL_POPULATE) + CHK_ERR_WIN32A(FRS_ERR_SYSVOL_POPULATE_TIMEOUT) + CHK_ERR_WIN32A(FRS_ERR_SYSVOL_IS_BUSY) + CHK_ERR_WIN32A(FRS_ERR_SYSVOL_DEMOTE) + CHK_ERR_WIN32A(FRS_ERR_INVALID_SERVICE_PARAMETER) +// CHK_ERR_WIN32A(DS_S_SUCCESS) + CHK_ERR_WIN32A(ERROR_DS_NOT_INSTALLED) + CHK_ERR_WIN32A(ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY) + CHK_ERR_WIN32A(ERROR_DS_NO_ATTRIBUTE_OR_VALUE) + CHK_ERR_WIN32A(ERROR_DS_INVALID_ATTRIBUTE_SYNTAX) + CHK_ERR_WIN32A(ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED) + CHK_ERR_WIN32A(ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_BUSY) + CHK_ERR_WIN32A(ERROR_DS_UNAVAILABLE) + CHK_ERR_WIN32A(ERROR_DS_NO_RIDS_ALLOCATED) + CHK_ERR_WIN32A(ERROR_DS_NO_MORE_RIDS) + CHK_ERR_WIN32A(ERROR_DS_INCORRECT_ROLE_OWNER) + CHK_ERR_WIN32A(ERROR_DS_RIDMGR_INIT_ERROR) + CHK_ERR_WIN32A(ERROR_DS_OBJ_CLASS_VIOLATION) + CHK_ERR_WIN32A(ERROR_DS_CANT_ON_NON_LEAF) + CHK_ERR_WIN32A(ERROR_DS_CANT_ON_RDN) + CHK_ERR_WIN32A(ERROR_DS_CANT_MOD_OBJ_CLASS) + CHK_ERR_WIN32A(ERROR_DS_CROSS_DOM_MOVE_ERROR) + CHK_ERR_WIN32A(ERROR_DS_GC_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_SHARED_POLICY) + CHK_ERR_WIN32A(ERROR_POLICY_OBJECT_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_POLICY_ONLY_IN_DS) + CHK_ERR_WIN32A(ERROR_PROMOTION_ACTIVE) + CHK_ERR_WIN32A(ERROR_NO_PROMOTION_ACTIVE) + CHK_ERR_WIN32A(ERROR_DS_OPERATIONS_ERROR) + CHK_ERR_WIN32A(ERROR_DS_PROTOCOL_ERROR) + CHK_ERR_WIN32A(ERROR_DS_TIMELIMIT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_SIZELIMIT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_ADMIN_LIMIT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_COMPARE_FALSE) + CHK_ERR_WIN32A(ERROR_DS_COMPARE_TRUE) + CHK_ERR_WIN32A(ERROR_DS_AUTH_METHOD_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_DS_STRONG_AUTH_REQUIRED) + CHK_ERR_WIN32A(ERROR_DS_INAPPROPRIATE_AUTH) + CHK_ERR_WIN32A(ERROR_DS_AUTH_UNKNOWN) + CHK_ERR_WIN32A(ERROR_DS_REFERRAL) + CHK_ERR_WIN32A(ERROR_DS_UNAVAILABLE_CRIT_EXTENSION) + CHK_ERR_WIN32A(ERROR_DS_CONFIDENTIALITY_REQUIRED) + CHK_ERR_WIN32A(ERROR_DS_INAPPROPRIATE_MATCHING) + CHK_ERR_WIN32A(ERROR_DS_CONSTRAINT_VIOLATION) + CHK_ERR_WIN32A(ERROR_DS_NO_SUCH_OBJECT) + CHK_ERR_WIN32A(ERROR_DS_ALIAS_PROBLEM) + CHK_ERR_WIN32A(ERROR_DS_INVALID_DN_SYNTAX) + CHK_ERR_WIN32A(ERROR_DS_IS_LEAF) + CHK_ERR_WIN32A(ERROR_DS_ALIAS_DEREF_PROBLEM) + CHK_ERR_WIN32A(ERROR_DS_UNWILLING_TO_PERFORM) + CHK_ERR_WIN32A(ERROR_DS_LOOP_DETECT) + CHK_ERR_WIN32A(ERROR_DS_NAMING_VIOLATION) + CHK_ERR_WIN32A(ERROR_DS_OBJECT_RESULTS_TOO_LARGE) + CHK_ERR_WIN32A(ERROR_DS_AFFECTS_MULTIPLE_DSAS) + CHK_ERR_WIN32A(ERROR_DS_SERVER_DOWN) + CHK_ERR_WIN32A(ERROR_DS_LOCAL_ERROR) + CHK_ERR_WIN32A(ERROR_DS_ENCODING_ERROR) + CHK_ERR_WIN32A(ERROR_DS_DECODING_ERROR) + CHK_ERR_WIN32A(ERROR_DS_FILTER_UNKNOWN) + CHK_ERR_WIN32A(ERROR_DS_PARAM_ERROR) + CHK_ERR_WIN32A(ERROR_DS_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_DS_NO_RESULTS_RETURNED) + CHK_ERR_WIN32A(ERROR_DS_CONTROL_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_DS_CLIENT_LOOP) + CHK_ERR_WIN32A(ERROR_DS_REFERRAL_LIMIT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_ROOT_MUST_BE_NC) + CHK_ERR_WIN32A(ERROR_DS_ADD_REPLICA_INHIBITED) + CHK_ERR_WIN32A(ERROR_DS_ATT_NOT_DEF_IN_SCHEMA) + CHK_ERR_WIN32A(ERROR_DS_MAX_OBJ_SIZE_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_OBJ_STRING_NAME_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA) + CHK_ERR_WIN32A(ERROR_DS_RDN_DOESNT_MATCH_SCHEMA) + CHK_ERR_WIN32A(ERROR_DS_NO_REQUESTED_ATTS_FOUND) + CHK_ERR_WIN32A(ERROR_DS_USER_BUFFER_TO_SMALL) + CHK_ERR_WIN32A(ERROR_DS_ATT_IS_NOT_ON_OBJ) + CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_MOD_OPERATION) + CHK_ERR_WIN32A(ERROR_DS_OBJ_TOO_LARGE) + CHK_ERR_WIN32A(ERROR_DS_BAD_INSTANCE_TYPE) + CHK_ERR_WIN32A(ERROR_DS_MASTERDSA_REQUIRED) + CHK_ERR_WIN32A(ERROR_DS_OBJECT_CLASS_REQUIRED) + CHK_ERR_WIN32A(ERROR_DS_MISSING_REQUIRED_ATT) + CHK_ERR_WIN32A(ERROR_DS_ATT_NOT_DEF_FOR_CLASS) + CHK_ERR_WIN32A(ERROR_DS_ATT_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_CANT_ADD_ATT_VALUES) + CHK_ERR_WIN32A(ERROR_DS_SINGLE_VALUE_CONSTRAINT) + CHK_ERR_WIN32A(ERROR_DS_RANGE_CONSTRAINT) + CHK_ERR_WIN32A(ERROR_DS_ATT_VAL_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_CANT_REM_MISSING_ATT) + CHK_ERR_WIN32A(ERROR_DS_CANT_REM_MISSING_ATT_VAL) + CHK_ERR_WIN32A(ERROR_DS_ROOT_CANT_BE_SUBREF) + CHK_ERR_WIN32A(ERROR_DS_NO_CHAINING) + CHK_ERR_WIN32A(ERROR_DS_NO_CHAINED_EVAL) + CHK_ERR_WIN32A(ERROR_DS_NO_PARENT_OBJECT) + CHK_ERR_WIN32A(ERROR_DS_PARENT_IS_AN_ALIAS) + CHK_ERR_WIN32A(ERROR_DS_CANT_MIX_MASTER_AND_REPS) + CHK_ERR_WIN32A(ERROR_DS_CHILDREN_EXIST) + CHK_ERR_WIN32A(ERROR_DS_OBJ_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_DS_ALIASED_OBJ_MISSING) + CHK_ERR_WIN32A(ERROR_DS_BAD_NAME_SYNTAX) + CHK_ERR_WIN32A(ERROR_DS_ALIAS_POINTS_TO_ALIAS) + CHK_ERR_WIN32A(ERROR_DS_CANT_DEREF_ALIAS) + CHK_ERR_WIN32A(ERROR_DS_OUT_OF_SCOPE) + CHK_ERR_WIN32A(ERROR_DS_CANT_DELETE_DSA_OBJ) + CHK_ERR_WIN32A(ERROR_DS_GENERIC_ERROR) + CHK_ERR_WIN32A(ERROR_DS_DSA_MUST_BE_INT_MASTER) + CHK_ERR_WIN32A(ERROR_DS_CLASS_NOT_DSA) + CHK_ERR_WIN32A(ERROR_DS_INSUFF_ACCESS_RIGHTS) + CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_SUPERIOR) + CHK_ERR_WIN32A(ERROR_DS_ATTRIBUTE_OWNED_BY_SAM) + CHK_ERR_WIN32A(ERROR_DS_NAME_TOO_MANY_PARTS) + CHK_ERR_WIN32A(ERROR_DS_NAME_TOO_LONG) + CHK_ERR_WIN32A(ERROR_DS_NAME_VALUE_TOO_LONG) + CHK_ERR_WIN32A(ERROR_DS_NAME_UNPARSEABLE) + CHK_ERR_WIN32A(ERROR_DS_NAME_TYPE_UNKNOWN) + CHK_ERR_WIN32A(ERROR_DS_NOT_AN_OBJECT) + CHK_ERR_WIN32A(ERROR_DS_SEC_DESC_TOO_SHORT) + CHK_ERR_WIN32A(ERROR_DS_SEC_DESC_INVALID) + CHK_ERR_WIN32A(ERROR_DS_NO_DELETED_NAME) + CHK_ERR_WIN32A(ERROR_DS_SUBREF_MUST_HAVE_PARENT) + CHK_ERR_WIN32A(ERROR_DS_NCNAME_MUST_BE_NC) + CHK_ERR_WIN32A(ERROR_DS_CANT_ADD_SYSTEM_ONLY) + CHK_ERR_WIN32A(ERROR_DS_CLASS_MUST_BE_CONCRETE) + CHK_ERR_WIN32A(ERROR_DS_INVALID_DMD) + CHK_ERR_WIN32A(ERROR_DS_OBJ_GUID_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_NOT_ON_BACKLINK) + CHK_ERR_WIN32A(ERROR_DS_NO_CROSSREF_FOR_NC) + CHK_ERR_WIN32A(ERROR_DS_SHUTTING_DOWN) + CHK_ERR_WIN32A(ERROR_DS_UNKNOWN_OPERATION) + CHK_ERR_WIN32A(ERROR_DS_INVALID_ROLE_OWNER) + CHK_ERR_WIN32A(ERROR_DS_COULDNT_CONTACT_FSMO) + CHK_ERR_WIN32A(ERROR_DS_CROSS_NC_DN_RENAME) + CHK_ERR_WIN32A(ERROR_DS_CANT_MOD_SYSTEM_ONLY) + CHK_ERR_WIN32A(ERROR_DS_REPLICATOR_ONLY) + CHK_ERR_WIN32A(ERROR_DS_OBJ_CLASS_NOT_DEFINED) + CHK_ERR_WIN32A(ERROR_DS_OBJ_CLASS_NOT_SUBCLASS) + CHK_ERR_WIN32A(ERROR_DS_NAME_REFERENCE_INVALID) + CHK_ERR_WIN32A(ERROR_DS_CROSS_REF_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_CANT_DEL_MASTER_CROSSREF) + CHK_ERR_WIN32A(ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD) + CHK_ERR_WIN32A(ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX) + CHK_ERR_WIN32A(ERROR_DS_DUP_RDN) + CHK_ERR_WIN32A(ERROR_DS_DUP_OID) + CHK_ERR_WIN32A(ERROR_DS_DUP_MAPI_ID) + CHK_ERR_WIN32A(ERROR_DS_DUP_SCHEMA_ID_GUID) + CHK_ERR_WIN32A(ERROR_DS_DUP_LDAP_DISPLAY_NAME) + CHK_ERR_WIN32A(ERROR_DS_SEMANTIC_ATT_TEST) + CHK_ERR_WIN32A(ERROR_DS_SYNTAX_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_MUST_HAVE) + CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_MAY_HAVE) + CHK_ERR_WIN32A(ERROR_DS_NONEXISTENT_MAY_HAVE) + CHK_ERR_WIN32A(ERROR_DS_NONEXISTENT_MUST_HAVE) + CHK_ERR_WIN32A(ERROR_DS_AUX_CLS_TEST_FAIL) + CHK_ERR_WIN32A(ERROR_DS_NONEXISTENT_POSS_SUP) + CHK_ERR_WIN32A(ERROR_DS_SUB_CLS_TEST_FAIL) + CHK_ERR_WIN32A(ERROR_DS_BAD_RDN_ATT_ID_SYNTAX) + CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_AUX_CLS) + CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_SUB_CLS) + CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_POSS_SUP) + CHK_ERR_WIN32A(ERROR_DS_RECALCSCHEMA_FAILED) + CHK_ERR_WIN32A(ERROR_DS_TREE_DELETE_NOT_FINISHED) + CHK_ERR_WIN32A(ERROR_DS_CANT_DELETE) + CHK_ERR_WIN32A(ERROR_DS_ATT_SCHEMA_REQ_ID) + CHK_ERR_WIN32A(ERROR_DS_BAD_ATT_SCHEMA_SYNTAX) + CHK_ERR_WIN32A(ERROR_DS_CANT_CACHE_ATT) + CHK_ERR_WIN32A(ERROR_DS_CANT_CACHE_CLASS) + CHK_ERR_WIN32A(ERROR_DS_CANT_REMOVE_ATT_CACHE) + CHK_ERR_WIN32A(ERROR_DS_CANT_REMOVE_CLASS_CACHE) + CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_DN) + CHK_ERR_WIN32A(ERROR_DS_MISSING_SUPREF) + CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_INSTANCE) + CHK_ERR_WIN32A(ERROR_DS_CODE_INCONSISTENCY) + CHK_ERR_WIN32A(ERROR_DS_DATABASE_ERROR) + CHK_ERR_WIN32A(ERROR_DS_GOVERNSID_MISSING) + CHK_ERR_WIN32A(ERROR_DS_MISSING_EXPECTED_ATT) + CHK_ERR_WIN32A(ERROR_DS_NCNAME_MISSING_CR_REF) + CHK_ERR_WIN32A(ERROR_DS_SECURITY_CHECKING_ERROR) + CHK_ERR_WIN32A(ERROR_DS_SCHEMA_NOT_LOADED) + CHK_ERR_WIN32A(ERROR_DS_SCHEMA_ALLOC_FAILED) + CHK_ERR_WIN32A(ERROR_DS_ATT_SCHEMA_REQ_SYNTAX) + CHK_ERR_WIN32A(ERROR_DS_GCVERIFY_ERROR) + CHK_ERR_WIN32A(ERROR_DS_DRA_SCHEMA_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_DSA_OBJ) + CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_EXPECTED_NC) + CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_NC_IN_CACHE) + CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_CHILD) + CHK_ERR_WIN32A(ERROR_DS_SECURITY_ILLEGAL_MODIFY) + CHK_ERR_WIN32A(ERROR_DS_CANT_REPLACE_HIDDEN_REC) + CHK_ERR_WIN32A(ERROR_DS_BAD_HIERARCHY_FILE) + CHK_ERR_WIN32A(ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED) + CHK_ERR_WIN32A(ERROR_DS_CONFIG_PARAM_MISSING) + CHK_ERR_WIN32A(ERROR_DS_COUNTING_AB_INDICES_FAILED) + CHK_ERR_WIN32A(ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED) + CHK_ERR_WIN32A(ERROR_DS_INTERNAL_FAILURE) + CHK_ERR_WIN32A(ERROR_DS_UNKNOWN_ERROR) + CHK_ERR_WIN32A(ERROR_DS_ROOT_REQUIRES_CLASS_TOP) + CHK_ERR_WIN32A(ERROR_DS_REFUSING_FSMO_ROLES) + CHK_ERR_WIN32A(ERROR_DS_MISSING_FSMO_SETTINGS) + CHK_ERR_WIN32A(ERROR_DS_UNABLE_TO_SURRENDER_ROLES) + CHK_ERR_WIN32A(ERROR_DS_DRA_GENERIC) + CHK_ERR_WIN32A(ERROR_DS_DRA_INVALID_PARAMETER) + CHK_ERR_WIN32A(ERROR_DS_DRA_BUSY) + CHK_ERR_WIN32A(ERROR_DS_DRA_BAD_DN) + CHK_ERR_WIN32A(ERROR_DS_DRA_BAD_NC) + CHK_ERR_WIN32A(ERROR_DS_DRA_DN_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_DRA_INTERNAL_ERROR) + CHK_ERR_WIN32A(ERROR_DS_DRA_INCONSISTENT_DIT) + CHK_ERR_WIN32A(ERROR_DS_DRA_CONNECTION_FAILED) + CHK_ERR_WIN32A(ERROR_DS_DRA_BAD_INSTANCE_TYPE) + CHK_ERR_WIN32A(ERROR_DS_DRA_OUT_OF_MEM) + CHK_ERR_WIN32A(ERROR_DS_DRA_MAIL_PROBLEM) + CHK_ERR_WIN32A(ERROR_DS_DRA_REF_ALREADY_EXISTS) + CHK_ERR_WIN32A(ERROR_DS_DRA_REF_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_DS_DRA_OBJ_IS_REP_SOURCE) + CHK_ERR_WIN32A(ERROR_DS_DRA_DB_ERROR) + CHK_ERR_WIN32A(ERROR_DS_DRA_NO_REPLICA) + CHK_ERR_WIN32A(ERROR_DS_DRA_ACCESS_DENIED) + CHK_ERR_WIN32A(ERROR_DS_DRA_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_DS_DRA_RPC_CANCELLED) + CHK_ERR_WIN32A(ERROR_DS_DRA_SOURCE_DISABLED) + CHK_ERR_WIN32A(ERROR_DS_DRA_SINK_DISABLED) + CHK_ERR_WIN32A(ERROR_DS_DRA_NAME_COLLISION) + CHK_ERR_WIN32A(ERROR_DS_DRA_SOURCE_REINSTALLED) + CHK_ERR_WIN32A(ERROR_DS_DRA_MISSING_PARENT) + CHK_ERR_WIN32A(ERROR_DS_DRA_PREEMPTED) + CHK_ERR_WIN32A(ERROR_DS_DRA_ABANDON_SYNC) + CHK_ERR_WIN32A(ERROR_DS_DRA_SHUTDOWN) + CHK_ERR_WIN32A(ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET) + CHK_ERR_WIN32A(ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA) + CHK_ERR_WIN32A(ERROR_DS_DRA_EXTN_CONNECTION_FAILED) + CHK_ERR_WIN32A(ERROR_DS_INSTALL_SCHEMA_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_DUP_LINK_ID) + CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_RESOLVING) + CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NOT_UNIQUE) + CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NO_MAPPING) + CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_DOMAIN_ONLY) + CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING) + CHK_ERR_WIN32A(ERROR_DS_CONSTRUCTED_ATT_MOD) + CHK_ERR_WIN32A(ERROR_DS_WRONG_OM_OBJ_CLASS) + CHK_ERR_WIN32A(ERROR_DS_DRA_REPL_PENDING) + CHK_ERR_WIN32A(DNS_ERROR_RESPONSE_CODES_BASE) +// CHK_ERR_WIN32A(DNS_ERROR_MASK) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_FORMAT_ERROR) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_SERVER_FAILURE) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_NAME_ERROR) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_NOT_IMPLEMENTED) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_REFUSED) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_YXDOMAIN) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_YXRRSET) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_NXRRSET) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_NOTAUTH) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_NOTZONE) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_BADSIG) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_BADKEY) + CHK_ERR_WIN32A(DNS_ERROR_RCODE_BADTIME) + CHK_ERR_WIN32A(DNS_ERROR_PACKET_FMT_BASE) + CHK_ERR_WIN32A(DNS_INFO_NO_RECORDS) + CHK_ERR_WIN32A(DNS_ERROR_BAD_PACKET) + CHK_ERR_WIN32A(DNS_ERROR_NO_PACKET) + CHK_ERR_WIN32A(DNS_ERROR_RCODE) + CHK_ERR_WIN32A(DNS_ERROR_UNSECURE_PACKET) + CHK_ERR_WIN32A(DNS_ERROR_GENERAL_API_BASE) + CHK_ERR_WIN32A(DNS_ERROR_INVALID_TYPE) + CHK_ERR_WIN32A(DNS_ERROR_INVALID_IP_ADDRESS) + CHK_ERR_WIN32A(DNS_ERROR_INVALID_PROPERTY) + CHK_ERR_WIN32A(DNS_ERROR_TRY_AGAIN_LATER) + CHK_ERR_WIN32A(DNS_ERROR_NOT_UNIQUE) + CHK_ERR_WIN32A(DNS_ERROR_NON_RFC_NAME) + CHK_ERR_WIN32A(DNS_STATUS_FQDN) + CHK_ERR_WIN32A(DNS_STATUS_DOTTED_NAME) + CHK_ERR_WIN32A(DNS_STATUS_SINGLE_PART_NAME) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_BASE) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_DOES_NOT_EXIST) + CHK_ERR_WIN32A(DNS_ERROR_NO_ZONE_INFO) + CHK_ERR_WIN32A(DNS_ERROR_INVALID_ZONE_OPERATION) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_CONFIGURATION_ERROR) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_HAS_NO_SOA_RECORD) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_HAS_NO_NS_RECORDS) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_LOCKED) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_CREATION_FAILED) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_ALREADY_EXISTS) + CHK_ERR_WIN32A(DNS_ERROR_AUTOZONE_ALREADY_EXISTS) + CHK_ERR_WIN32A(DNS_ERROR_INVALID_ZONE_TYPE) + CHK_ERR_WIN32A(DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_NOT_SECONDARY) + CHK_ERR_WIN32A(DNS_ERROR_NEED_SECONDARY_ADDRESSES) + CHK_ERR_WIN32A(DNS_ERROR_WINS_INIT_FAILED) + CHK_ERR_WIN32A(DNS_ERROR_NEED_WINS_SERVERS) + CHK_ERR_WIN32A(DNS_ERROR_NBSTAT_INIT_FAILED) + CHK_ERR_WIN32A(DNS_ERROR_SOA_DELETE_INVALID) + CHK_ERR_WIN32A(DNS_ERROR_DATAFILE_BASE) + CHK_ERR_WIN32A(DNS_ERROR_PRIMARY_REQUIRES_DATAFILE) + CHK_ERR_WIN32A(DNS_ERROR_INVALID_DATAFILE_NAME) + CHK_ERR_WIN32A(DNS_ERROR_DATAFILE_OPEN_FAILURE) + CHK_ERR_WIN32A(DNS_ERROR_FILE_WRITEBACK_FAILED) + CHK_ERR_WIN32A(DNS_ERROR_DATAFILE_PARSING) + CHK_ERR_WIN32A(DNS_ERROR_DATABASE_BASE) + CHK_ERR_WIN32A(DNS_ERROR_RECORD_DOES_NOT_EXIST) + CHK_ERR_WIN32A(DNS_ERROR_RECORD_FORMAT) + CHK_ERR_WIN32A(DNS_ERROR_NODE_CREATION_FAILED) + CHK_ERR_WIN32A(DNS_ERROR_UNKNOWN_RECORD_TYPE) + CHK_ERR_WIN32A(DNS_ERROR_RECORD_TIMED_OUT) + CHK_ERR_WIN32A(DNS_ERROR_NAME_NOT_IN_ZONE) + CHK_ERR_WIN32A(DNS_ERROR_CNAME_LOOP) + CHK_ERR_WIN32A(DNS_ERROR_NODE_IS_CNAME) + CHK_ERR_WIN32A(DNS_ERROR_CNAME_COLLISION) + CHK_ERR_WIN32A(DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT) + CHK_ERR_WIN32A(DNS_ERROR_RECORD_ALREADY_EXISTS) + CHK_ERR_WIN32A(DNS_ERROR_SECONDARY_DATA) + CHK_ERR_WIN32A(DNS_ERROR_NO_CREATE_CACHE_DATA) + CHK_ERR_WIN32A(DNS_ERROR_NAME_DOES_NOT_EXIST) + CHK_ERR_WIN32A(DNS_WARNING_PTR_CREATE_FAILED) + CHK_ERR_WIN32A(DNS_WARNING_DOMAIN_UNDELETED) + CHK_ERR_WIN32A(DNS_ERROR_DS_UNAVAILABLE) + CHK_ERR_WIN32A(DNS_ERROR_DS_ZONE_ALREADY_EXISTS) + CHK_ERR_WIN32A(DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE) + CHK_ERR_WIN32A(DNS_ERROR_OPERATION_BASE) + CHK_ERR_WIN32A(DNS_INFO_AXFR_COMPLETE) + CHK_ERR_WIN32A(DNS_ERROR_AXFR) + CHK_ERR_WIN32A(DNS_INFO_ADDED_LOCAL_WINS) + CHK_ERR_WIN32A(DNS_ERROR_SECURE_BASE) + CHK_ERR_WIN32A(DNS_STATUS_CONTINUE_NEEDED) + CHK_ERR_WIN32A(DNS_ERROR_SETUP_BASE) + CHK_ERR_WIN32A(DNS_ERROR_NO_TCPIP) + CHK_ERR_WIN32A(DNS_ERROR_NO_DNS_SERVERS) + CHK_ERR_WIN32A(WSABASEERR) + CHK_ERR_WIN32A(WSAEINTR) + CHK_ERR_WIN32A(WSAEBADF) + CHK_ERR_WIN32A(WSAEACCES) + CHK_ERR_WIN32A(WSAEFAULT) + CHK_ERR_WIN32A(WSAEINVAL) + CHK_ERR_WIN32A(WSAEMFILE) + CHK_ERR_WIN32A(WSAEWOULDBLOCK) + CHK_ERR_WIN32A(WSAEINPROGRESS) + CHK_ERR_WIN32A(WSAEALREADY) + CHK_ERR_WIN32A(WSAENOTSOCK) + CHK_ERR_WIN32A(WSAEDESTADDRREQ) + CHK_ERR_WIN32A(WSAEMSGSIZE) + CHK_ERR_WIN32A(WSAEPROTOTYPE) + CHK_ERR_WIN32A(WSAENOPROTOOPT) + CHK_ERR_WIN32A(WSAEPROTONOSUPPORT) + CHK_ERR_WIN32A(WSAESOCKTNOSUPPORT) + CHK_ERR_WIN32A(WSAEOPNOTSUPP) + CHK_ERR_WIN32A(WSAEPFNOSUPPORT) + CHK_ERR_WIN32A(WSAEAFNOSUPPORT) + CHK_ERR_WIN32A(WSAEADDRINUSE) + CHK_ERR_WIN32A(WSAEADDRNOTAVAIL) + CHK_ERR_WIN32A(WSAENETDOWN) + CHK_ERR_WIN32A(WSAENETUNREACH) + CHK_ERR_WIN32A(WSAENETRESET) + CHK_ERR_WIN32A(WSAECONNABORTED) + CHK_ERR_WIN32A(WSAECONNRESET) + CHK_ERR_WIN32A(WSAENOBUFS) + CHK_ERR_WIN32A(WSAEISCONN) + CHK_ERR_WIN32A(WSAENOTCONN) + CHK_ERR_WIN32A(WSAESHUTDOWN) + CHK_ERR_WIN32A(WSAETOOMANYREFS) + CHK_ERR_WIN32A(WSAETIMEDOUT) + CHK_ERR_WIN32A(WSAECONNREFUSED) + CHK_ERR_WIN32A(WSAELOOP) + CHK_ERR_WIN32A(WSAENAMETOOLONG) + CHK_ERR_WIN32A(WSAEHOSTDOWN) + CHK_ERR_WIN32A(WSAEHOSTUNREACH) + CHK_ERR_WIN32A(WSAENOTEMPTY) + CHK_ERR_WIN32A(WSAEPROCLIM) + CHK_ERR_WIN32A(WSAEUSERS) + CHK_ERR_WIN32A(WSAEDQUOT) + CHK_ERR_WIN32A(WSAESTALE) + CHK_ERR_WIN32A(WSAEREMOTE) + CHK_ERR_WIN32A(WSASYSNOTREADY) + CHK_ERR_WIN32A(WSAVERNOTSUPPORTED) + CHK_ERR_WIN32A(WSANOTINITIALISED) + CHK_ERR_WIN32A(WSAEDISCON) + CHK_ERR_WIN32A(WSAENOMORE) + CHK_ERR_WIN32A(WSAECANCELLED) + CHK_ERR_WIN32A(WSAEINVALIDPROCTABLE) + CHK_ERR_WIN32A(WSAEINVALIDPROVIDER) + CHK_ERR_WIN32A(WSAEPROVIDERFAILEDINIT) + CHK_ERR_WIN32A(WSASYSCALLFAILURE) + CHK_ERR_WIN32A(WSASERVICE_NOT_FOUND) + CHK_ERR_WIN32A(WSATYPE_NOT_FOUND) + CHK_ERR_WIN32A(WSA_E_NO_MORE) + CHK_ERR_WIN32A(WSA_E_CANCELLED) + CHK_ERR_WIN32A(WSAEREFUSED) + CHK_ERR_WIN32A(WSAHOST_NOT_FOUND) + CHK_ERR_WIN32A(WSATRY_AGAIN) + CHK_ERR_WIN32A(WSANO_RECOVERY) + CHK_ERR_WIN32A(WSANO_DATA) + CHK_ERR_WIN32A(WSA_QOS_RECEIVERS) + CHK_ERR_WIN32A(WSA_QOS_SENDERS) + CHK_ERR_WIN32A(WSA_QOS_NO_SENDERS) + CHK_ERR_WIN32A(WSA_QOS_NO_RECEIVERS) + CHK_ERR_WIN32A(WSA_QOS_REQUEST_CONFIRMED) + CHK_ERR_WIN32A(WSA_QOS_ADMISSION_FAILURE) + CHK_ERR_WIN32A(WSA_QOS_POLICY_FAILURE) + CHK_ERR_WIN32A(WSA_QOS_BAD_STYLE) + CHK_ERR_WIN32A(WSA_QOS_BAD_OBJECT) + CHK_ERR_WIN32A(WSA_QOS_TRAFFIC_CTRL_ERROR) + CHK_ERR_WIN32A(WSA_QOS_GENERIC_ERROR) + + CHK_ERRA(CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT) + CHK_ERRA(CO_E_SERVER_PAUSED) + CHK_ERRA(CO_E_SERVER_NOT_PAUSED) + CHK_ERRA(CO_E_CLASS_DISABLED) + CHK_ERRA(CO_E_CLRNOTAVAILABLE) + CHK_ERRA(CO_E_ASYNC_WORK_REJECTED) + CHK_ERRA(CO_E_SERVER_INIT_TIMEOUT) + CHK_ERRA(CO_E_NO_SECCTX_IN_ACTIVATE) + CHK_ERRA(CO_E_TRACKER_CONFIG) + CHK_ERRA(CO_E_THREADPOOL_CONFIG) + CHK_ERRA(CO_E_SXS_CONFIG) + CHK_ERRA(CO_E_MALFORMED_SPN) + CHK_ERRA(REGDB_E_BADTHREADINGMODEL) +// CHK_ERRA(EVENT_E_FIRST) +// CHK_ERRA(EVENT_E_LAST) +// CHK_ERRA(EVENT_S_FIRST) +// CHK_ERRA(EVENT_S_LAST) +// CHK_ERRA(EVENT_S_SOME_SUBSCRIBERS_FAILED) +// CHK_ERRA(EVENT_E_ALL_SUBSCRIBERS_FAILED) + CHK_ERRA(EVENT_S_NOSUBSCRIBERS) +// CHK_ERRA(EVENT_E_QUERYSYNTAX) +// CHK_ERRA(EVENT_E_QUERYFIELD) +// CHK_ERRA(EVENT_E_INTERNALEXCEPTION) +// CHK_ERRA(EVENT_E_INTERNALERROR) +// CHK_ERRA(EVENT_E_INVALID_PER_USER_SID) +// CHK_ERRA(EVENT_E_USER_EXCEPTION) +// CHK_ERRA(EVENT_E_TOO_MANY_METHODS) +// CHK_ERRA(EVENT_E_MISSING_EVENTCLASS) +// CHK_ERRA(EVENT_E_NOT_ALL_REMOVED) +// CHK_ERRA(EVENT_E_COMPLUS_NOT_INSTALLED) +// CHK_ERRA(EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT) +// CHK_ERRA(EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT) +// CHK_ERRA(EVENT_E_INVALID_EVENT_CLASS_PARTITION) +// CHK_ERRA(EVENT_E_PER_USER_SID_NOT_LOGGED_ON) + CHK_ERRA(CONTEXT_E_FIRST) + CHK_ERRA(CONTEXT_E_LAST) + CHK_ERRA(CONTEXT_S_FIRST) + CHK_ERRA(CONTEXT_S_LAST) + CHK_ERRA(CONTEXT_E_ABORTED) + CHK_ERRA(CONTEXT_E_ABORTING) + CHK_ERRA(CONTEXT_E_NOCONTEXT) +// CHK_ERRA(CONTEXT_E_WOULD_DEADLOCK) + CHK_ERRA(CONTEXT_E_SYNCH_TIMEOUT) + CHK_ERRA(CONTEXT_E_OLDREF) + CHK_ERRA(CONTEXT_E_ROLENOTFOUND) + CHK_ERRA(CONTEXT_E_TMNOTAVAILABLE) + CHK_ERRA(CO_E_ACTIVATIONFAILED) + CHK_ERRA(CO_E_ACTIVATIONFAILED_EVENTLOGGED) + CHK_ERRA(CO_E_ACTIVATIONFAILED_CATALOGERROR) + CHK_ERRA(CO_E_ACTIVATIONFAILED_TIMEOUT) + CHK_ERRA(CO_E_INITIALIZATIONFAILED) + CHK_ERRA(CONTEXT_E_NOJIT) + CHK_ERRA(CONTEXT_E_NOTRANSACTION) + CHK_ERRA(CO_E_THREADINGMODEL_CHANGED) + CHK_ERRA(CO_E_NOIISINTRINSICS) + CHK_ERRA(CO_E_NOCOOKIES) + CHK_ERRA(CO_E_DBERROR) + CHK_ERRA(CO_E_NOTPOOLED) + CHK_ERRA(CO_E_NOTCONSTRUCTED) + CHK_ERRA(CO_E_NOSYNCHRONIZATION) +// CHK_ERRA(CO_E_ISOLEVELMISMATCH) + CHK_ERRA(SCHED_S_TASK_READY) + CHK_ERRA(SCHED_S_TASK_RUNNING) + CHK_ERRA(SCHED_S_TASK_DISABLED) + CHK_ERRA(SCHED_S_TASK_HAS_NOT_RUN) + CHK_ERRA(SCHED_S_TASK_NO_MORE_RUNS) + CHK_ERRA(SCHED_S_TASK_NOT_SCHEDULED) + CHK_ERRA(SCHED_S_TASK_TERMINATED) + CHK_ERRA(SCHED_S_TASK_NO_VALID_TRIGGERS) + CHK_ERRA(SCHED_S_EVENT_TRIGGER) + CHK_ERRA(SCHED_E_TRIGGER_NOT_FOUND) + CHK_ERRA(SCHED_E_TASK_NOT_READY) + CHK_ERRA(SCHED_E_TASK_NOT_RUNNING) + CHK_ERRA(SCHED_E_SERVICE_NOT_INSTALLED) + CHK_ERRA(SCHED_E_CANNOT_OPEN_TASK) + CHK_ERRA(SCHED_E_INVALID_TASK) + CHK_ERRA(SCHED_E_ACCOUNT_INFORMATION_NOT_SET) + CHK_ERRA(SCHED_E_ACCOUNT_NAME_NOT_FOUND) + CHK_ERRA(SCHED_E_ACCOUNT_DBASE_CORRUPT) + CHK_ERRA(SCHED_E_NO_SECURITY_SERVICES) + CHK_ERRA(SCHED_E_UNKNOWN_OBJECT_VERSION) + CHK_ERRA(SCHED_E_UNSUPPORTED_ACCOUNT_OPTION) + CHK_ERRA(SCHED_E_SERVICE_NOT_RUNNING) + CHK_ERRA(CO_S_MACHINENAMENOTFOUND) + CHK_ERRA(STG_E_STATUS_COPY_PROTECTION_FAILURE) + CHK_ERRA(STG_E_CSS_AUTHENTICATION_FAILURE) + CHK_ERRA(STG_E_CSS_KEY_NOT_PRESENT) + CHK_ERRA(STG_E_CSS_KEY_NOT_ESTABLISHED) + CHK_ERRA(STG_E_CSS_SCRAMBLED_SECTOR) + CHK_ERRA(STG_E_CSS_REGION_MISMATCH) + CHK_ERRA(STG_E_RESETS_EXHAUSTED) + CHK_ERRA(CO_E_CANCEL_DISABLED) + CHK_ERRA(ERROR_AUDITING_DISABLED) + CHK_ERRA(ERROR_ALL_SIDS_FILTERED) + CHK_ERRA(NTE_TEMPORARY_PROFILE) + CHK_ERRA(NTE_FIXEDPARAMETER) + CHK_ERRA(SEC_E_INSUFFICIENT_MEMORY) + CHK_ERRA(SEC_E_INVALID_HANDLE) + CHK_ERRA(SEC_E_UNSUPPORTED_FUNCTION) + CHK_ERRA(SEC_E_TARGET_UNKNOWN) + CHK_ERRA(SEC_E_INTERNAL_ERROR) + CHK_ERRA(SEC_E_SECPKG_NOT_FOUND) + CHK_ERRA(SEC_E_NOT_OWNER) + CHK_ERRA(SEC_E_CANNOT_INSTALL) + CHK_ERRA(SEC_E_INVALID_TOKEN) + CHK_ERRA(SEC_E_CANNOT_PACK) + CHK_ERRA(SEC_E_QOP_NOT_SUPPORTED) + CHK_ERRA(SEC_E_NO_IMPERSONATION) + CHK_ERRA(SEC_E_LOGON_DENIED) + CHK_ERRA(SEC_E_UNKNOWN_CREDENTIALS) + CHK_ERRA(SEC_E_NO_CREDENTIALS) + CHK_ERRA(SEC_E_MESSAGE_ALTERED) + CHK_ERRA(SEC_E_OUT_OF_SEQUENCE) + CHK_ERRA(SEC_E_NO_AUTHENTICATING_AUTHORITY) + CHK_ERRA(SEC_I_CONTINUE_NEEDED) + CHK_ERRA(SEC_I_COMPLETE_NEEDED) + CHK_ERRA(SEC_I_COMPLETE_AND_CONTINUE) + CHK_ERRA(SEC_I_LOCAL_LOGON) + CHK_ERRA(SEC_E_BAD_PKGID) + CHK_ERRA(SEC_E_CONTEXT_EXPIRED) + CHK_ERRA(SEC_I_CONTEXT_EXPIRED) + CHK_ERRA(SEC_E_INCOMPLETE_MESSAGE) + CHK_ERRA(SEC_E_INCOMPLETE_CREDENTIALS) + CHK_ERRA(SEC_E_BUFFER_TOO_SMALL) + CHK_ERRA(SEC_I_INCOMPLETE_CREDENTIALS) + CHK_ERRA(SEC_I_RENEGOTIATE) + CHK_ERRA(SEC_E_WRONG_PRINCIPAL) + CHK_ERRA(SEC_I_NO_LSA_CONTEXT) + CHK_ERRA(SEC_E_TIME_SKEW) + CHK_ERRA(SEC_E_UNTRUSTED_ROOT) + CHK_ERRA(SEC_E_ILLEGAL_MESSAGE) + CHK_ERRA(SEC_E_CERT_UNKNOWN) + CHK_ERRA(SEC_E_CERT_EXPIRED) + CHK_ERRA(SEC_E_ENCRYPT_FAILURE) + CHK_ERRA(SEC_E_DECRYPT_FAILURE) + CHK_ERRA(SEC_E_ALGORITHM_MISMATCH) + CHK_ERRA(SEC_E_SECURITY_QOS_FAILED) + CHK_ERRA(SEC_E_UNFINISHED_CONTEXT_DELETED) + CHK_ERRA(SEC_E_NO_TGT_REPLY) + CHK_ERRA(SEC_E_NO_IP_ADDRESSES) + CHK_ERRA(SEC_E_WRONG_CREDENTIAL_HANDLE) + CHK_ERRA(SEC_E_CRYPTO_SYSTEM_INVALID) + CHK_ERRA(SEC_E_MAX_REFERRALS_EXCEEDED) + CHK_ERRA(SEC_E_MUST_BE_KDC) + CHK_ERRA(SEC_E_STRONG_CRYPTO_NOT_SUPPORTED) + CHK_ERRA(SEC_E_TOO_MANY_PRINCIPALS) + CHK_ERRA(SEC_E_NO_PA_DATA) + CHK_ERRA(SEC_E_PKINIT_NAME_MISMATCH) + CHK_ERRA(SEC_E_SMARTCARD_LOGON_REQUIRED) + CHK_ERRA(SEC_E_SHUTDOWN_IN_PROGRESS) + CHK_ERRA(SEC_E_KDC_INVALID_REQUEST) + CHK_ERRA(SEC_E_KDC_UNABLE_TO_REFER) + CHK_ERRA(SEC_E_KDC_UNKNOWN_ETYPE) + CHK_ERRA(SEC_E_UNSUPPORTED_PREAUTH) + CHK_ERRA(SEC_E_DELEGATION_REQUIRED) + CHK_ERRA(SEC_E_BAD_BINDINGS) + CHK_ERRA(SEC_E_MULTIPLE_ACCOUNTS) + CHK_ERRA(SEC_E_NO_KERB_KEY) +// CHK_ERRA(SEC_E_CERT_WRONG_USAGE) +// CHK_ERRA(SEC_E_DOWNGRADE_DETECTED) + CHK_ERRA(SEC_E_SMARTCARD_CERT_REVOKED) + CHK_ERRA(SEC_E_ISSUING_CA_UNTRUSTED) + CHK_ERRA(SEC_E_REVOCATION_OFFLINE_C) + CHK_ERRA(SEC_E_PKINIT_CLIENT_FAILURE) + CHK_ERRA(SEC_E_SMARTCARD_CERT_EXPIRED) +// CHK_ERRA(SEC_E_NO_SPM) +// CHK_ERRA(SEC_E_NOT_SUPPORTED) + CHK_ERRA(CRYPT_I_NEW_PROTECTION_REQUIRED) + CHK_ERRA(CRYPT_E_MISSING_PUBKEY_PARA) + CHK_ERRA(CRYPT_E_ASN1_ERROR) + CHK_ERRA(CRYPT_E_ASN1_INTERNAL) + CHK_ERRA(CRYPT_E_ASN1_EOD) + CHK_ERRA(CRYPT_E_ASN1_CORRUPT) + CHK_ERRA(CRYPT_E_ASN1_LARGE) + CHK_ERRA(CRYPT_E_ASN1_CONSTRAINT) + CHK_ERRA(CRYPT_E_ASN1_MEMORY) + CHK_ERRA(CRYPT_E_ASN1_OVERFLOW) + CHK_ERRA(CRYPT_E_ASN1_BADPDU) + CHK_ERRA(CRYPT_E_ASN1_BADARGS) + CHK_ERRA(CRYPT_E_ASN1_BADREAL) + CHK_ERRA(CRYPT_E_ASN1_BADTAG) + CHK_ERRA(CRYPT_E_ASN1_CHOICE) + CHK_ERRA(CRYPT_E_ASN1_RULE) + CHK_ERRA(CRYPT_E_ASN1_UTF8) + CHK_ERRA(CRYPT_E_ASN1_PDU_TYPE) + CHK_ERRA(CRYPT_E_ASN1_NYI) + CHK_ERRA(CRYPT_E_ASN1_EXTENDED) + CHK_ERRA(CRYPT_E_ASN1_NOEOD) + CHK_ERRA(CERTSRV_E_SERVER_SUSPENDED) + CHK_ERRA(CERTSRV_E_ENCODING_LENGTH) + CHK_ERRA(CERTSRV_E_ROLECONFLICT) + CHK_ERRA(CERTSRV_E_RESTRICTEDOFFICER) + CHK_ERRA(CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED) + CHK_ERRA(CERTSRV_E_NO_VALID_KRA) + CHK_ERRA(CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL) + CHK_ERRA(CERTSRV_E_NO_CAADMIN_DEFINED) + CHK_ERRA(CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE) + CHK_ERRA(CERTSRV_E_NO_DB_SESSIONS) + CHK_ERRA(CERTSRV_E_ALIGNMENT_FAULT) + CHK_ERRA(CERTSRV_E_ENROLL_DENIED) + CHK_ERRA(CERTSRV_E_TEMPLATE_DENIED) +// CHK_ERRA(CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE) + CHK_ERRA(CERTSRV_E_TEMPLATE_CONFLICT) + CHK_ERRA(CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED) + CHK_ERRA(CERTSRV_E_ARCHIVED_KEY_REQUIRED) + CHK_ERRA(CERTSRV_E_SMIME_REQUIRED) + CHK_ERRA(CERTSRV_E_BAD_RENEWAL_SUBJECT) + CHK_ERRA(CERTSRV_E_BAD_TEMPLATE_VERSION) + CHK_ERRA(CERTSRV_E_TEMPLATE_POLICY_REQUIRED) + CHK_ERRA(CERTSRV_E_SIGNATURE_POLICY_REQUIRED) + CHK_ERRA(CERTSRV_E_SIGNATURE_COUNT) + CHK_ERRA(CERTSRV_E_SIGNATURE_REJECTED) + CHK_ERRA(CERTSRV_E_ISSUANCE_POLICY_REQUIRED) + CHK_ERRA(CERTSRV_E_SUBJECT_UPN_REQUIRED) + CHK_ERRA(CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED) + CHK_ERRA(CERTSRV_E_SUBJECT_DNS_REQUIRED) + CHK_ERRA(CERTSRV_E_ARCHIVED_KEY_UNEXPECTED) + CHK_ERRA(CERTSRV_E_KEY_LENGTH) +// CHK_ERRA(CERTSRV_E_SUBJECT_EMAIL_REQUIRED) +// CHK_ERRA(CERTSRV_E_UNKNOWN_CERT_TYPE) +// CHK_ERRA(CERTSRV_E_CERT_TYPE_OVERLAP) + CHK_ERRA(XENROLL_E_KEY_NOT_EXPORTABLE) + CHK_ERRA(XENROLL_E_CANNOT_ADD_ROOT_CERT) + CHK_ERRA(XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND) + CHK_ERRA(XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH) + CHK_ERRA(XENROLL_E_RESPONSE_KA_HASH_MISMATCH) + CHK_ERRA(XENROLL_E_KEYSPEC_SMIME_MISMATCH) + CHK_ERRA(MSSIPOTF_E_OUTOFMEMRANGE) + CHK_ERRA(MSSIPOTF_E_CANTGETOBJECT) + CHK_ERRA(MSSIPOTF_E_NOHEADTABLE) + CHK_ERRA(MSSIPOTF_E_BAD_MAGICNUMBER) + CHK_ERRA(MSSIPOTF_E_BAD_OFFSET_TABLE) + CHK_ERRA(MSSIPOTF_E_TABLE_TAGORDER) + CHK_ERRA(MSSIPOTF_E_TABLE_LONGWORD) + CHK_ERRA(MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT) + CHK_ERRA(MSSIPOTF_E_TABLES_OVERLAP) + CHK_ERRA(MSSIPOTF_E_TABLE_PADBYTES) + CHK_ERRA(MSSIPOTF_E_FILETOOSMALL) + CHK_ERRA(MSSIPOTF_E_TABLE_CHECKSUM) + CHK_ERRA(MSSIPOTF_E_FILE_CHECKSUM) + CHK_ERRA(MSSIPOTF_E_FAILED_POLICY) + CHK_ERRA(MSSIPOTF_E_FAILED_HINTS_CHECK) + CHK_ERRA(MSSIPOTF_E_NOT_OPENTYPE) + CHK_ERRA(MSSIPOTF_E_FILE) + CHK_ERRA(MSSIPOTF_E_CRYPT) + CHK_ERRA(MSSIPOTF_E_BADVERSION) + CHK_ERRA(MSSIPOTF_E_DSIG_STRUCTURE) + CHK_ERRA(MSSIPOTF_E_PCONST_CHECK) + CHK_ERRA(MSSIPOTF_E_STRUCTURE) + CHK_ERRA(TRUST_E_EXPLICIT_DISTRUST) + CHK_ERRA(CERT_E_UNTRUSTEDCA) + CHK_ERRA(CERT_E_INVALID_POLICY) + CHK_ERRA(CERT_E_INVALID_NAME) + CHK_ERRA(SPAPI_E_NOT_DISABLEABLE) + CHK_ERRA(SPAPI_E_CANT_REMOVE_DEVINST) + CHK_ERRA(SPAPI_E_INVALID_TARGET) + CHK_ERRA(SPAPI_E_DRIVER_NONNATIVE) + CHK_ERRA(SPAPI_E_IN_WOW64) + CHK_ERRA(SPAPI_E_SET_SYSTEM_RESTORE_POINT) + CHK_ERRA(SPAPI_E_INCORRECTLY_COPIED_INF) + CHK_ERRA(SPAPI_E_SCE_DISABLED) + CHK_ERRA(SCARD_E_NO_KEY_CONTAINER) + CHK_ERRA(SCARD_W_CARD_NOT_AUTHENTICATED) + CHK_ERRA(COMADMIN_E_OBJECTERRORS) + CHK_ERRA(COMADMIN_E_OBJECTINVALID) + CHK_ERRA(COMADMIN_E_KEYMISSING) + CHK_ERRA(COMADMIN_E_ALREADYINSTALLED) + CHK_ERRA(COMADMIN_E_APP_FILE_WRITEFAIL) + CHK_ERRA(COMADMIN_E_APP_FILE_READFAIL) + CHK_ERRA(COMADMIN_E_APP_FILE_VERSION) + CHK_ERRA(COMADMIN_E_BADPATH) + CHK_ERRA(COMADMIN_E_APPLICATIONEXISTS) + CHK_ERRA(COMADMIN_E_ROLEEXISTS) + CHK_ERRA(COMADMIN_E_CANTCOPYFILE) + CHK_ERRA(COMADMIN_E_NOUSER) + CHK_ERRA(COMADMIN_E_INVALIDUSERIDS) + CHK_ERRA(COMADMIN_E_NOREGISTRYCLSID) + CHK_ERRA(COMADMIN_E_BADREGISTRYPROGID) + CHK_ERRA(COMADMIN_E_AUTHENTICATIONLEVEL) + CHK_ERRA(COMADMIN_E_USERPASSWDNOTVALID) + CHK_ERRA(COMADMIN_E_CLSIDORIIDMISMATCH) + CHK_ERRA(COMADMIN_E_REMOTEINTERFACE) + CHK_ERRA(COMADMIN_E_DLLREGISTERSERVER) + CHK_ERRA(COMADMIN_E_NOSERVERSHARE) + CHK_ERRA(COMADMIN_E_DLLLOADFAILED) + CHK_ERRA(COMADMIN_E_BADREGISTRYLIBID) + CHK_ERRA(COMADMIN_E_APPDIRNOTFOUND) + CHK_ERRA(COMADMIN_E_REGISTRARFAILED) + CHK_ERRA(COMADMIN_E_COMPFILE_DOESNOTEXIST) + CHK_ERRA(COMADMIN_E_COMPFILE_LOADDLLFAIL) + CHK_ERRA(COMADMIN_E_COMPFILE_GETCLASSOBJ) + CHK_ERRA(COMADMIN_E_COMPFILE_CLASSNOTAVAIL) + CHK_ERRA(COMADMIN_E_COMPFILE_BADTLB) + CHK_ERRA(COMADMIN_E_COMPFILE_NOTINSTALLABLE) + CHK_ERRA(COMADMIN_E_NOTCHANGEABLE) + CHK_ERRA(COMADMIN_E_NOTDELETEABLE) + CHK_ERRA(COMADMIN_E_SESSION) + CHK_ERRA(COMADMIN_E_COMP_MOVE_LOCKED) + CHK_ERRA(COMADMIN_E_COMP_MOVE_BAD_DEST) + CHK_ERRA(COMADMIN_E_REGISTERTLB) + CHK_ERRA(COMADMIN_E_SYSTEMAPP) + CHK_ERRA(COMADMIN_E_COMPFILE_NOREGISTRAR) + CHK_ERRA(COMADMIN_E_COREQCOMPINSTALLED) + CHK_ERRA(COMADMIN_E_SERVICENOTINSTALLED) + CHK_ERRA(COMADMIN_E_PROPERTYSAVEFAILED) + CHK_ERRA(COMADMIN_E_OBJECTEXISTS) + CHK_ERRA(COMADMIN_E_COMPONENTEXISTS) + CHK_ERRA(COMADMIN_E_REGFILE_CORRUPT) + CHK_ERRA(COMADMIN_E_PROPERTY_OVERFLOW) + CHK_ERRA(COMADMIN_E_NOTINREGISTRY) + CHK_ERRA(COMADMIN_E_OBJECTNOTPOOLABLE) + CHK_ERRA(COMADMIN_E_APPLID_MATCHES_CLSID) + CHK_ERRA(COMADMIN_E_ROLE_DOES_NOT_EXIST) + CHK_ERRA(COMADMIN_E_START_APP_NEEDS_COMPONENTS) + CHK_ERRA(COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM) + CHK_ERRA(COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY) + CHK_ERRA(COMADMIN_E_CAN_NOT_START_APP) + CHK_ERRA(COMADMIN_E_CAN_NOT_EXPORT_SYS_APP) + CHK_ERRA(COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT) + CHK_ERRA(COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER) + CHK_ERRA(COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE) + CHK_ERRA(COMADMIN_E_BASE_PARTITION_ONLY) + CHK_ERRA(COMADMIN_E_START_APP_DISABLED) + CHK_ERRA(COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME) + CHK_ERRA(COMADMIN_E_CAT_INVALID_PARTITION_NAME) + CHK_ERRA(COMADMIN_E_CAT_PARTITION_IN_USE) + CHK_ERRA(COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES) + CHK_ERRA(COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED) + CHK_ERRA(COMADMIN_E_AMBIGUOUS_APPLICATION_NAME) + CHK_ERRA(COMADMIN_E_AMBIGUOUS_PARTITION_NAME) + CHK_ERRA(COMADMIN_E_REGDB_NOTINITIALIZED) + CHK_ERRA(COMADMIN_E_REGDB_NOTOPEN) + CHK_ERRA(COMADMIN_E_REGDB_SYSTEMERR) + CHK_ERRA(COMADMIN_E_REGDB_ALREADYRUNNING) + CHK_ERRA(COMADMIN_E_MIG_VERSIONNOTSUPPORTED) + CHK_ERRA(COMADMIN_E_MIG_SCHEMANOTFOUND) + CHK_ERRA(COMADMIN_E_CAT_BITNESSMISMATCH) + CHK_ERRA(COMADMIN_E_CAT_UNACCEPTABLEBITNESS) + CHK_ERRA(COMADMIN_E_CAT_WRONGAPPBITNESS) + CHK_ERRA(COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED) + CHK_ERRA(COMADMIN_E_CAT_SERVERFAULT) + CHK_ERRA(COMQC_E_APPLICATION_NOT_QUEUED) + CHK_ERRA(COMQC_E_NO_QUEUEABLE_INTERFACES) + CHK_ERRA(COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE) + CHK_ERRA(COMQC_E_NO_IPERSISTSTREAM) + CHK_ERRA(COMQC_E_BAD_MESSAGE) + CHK_ERRA(COMQC_E_UNAUTHENTICATED) + CHK_ERRA(COMQC_E_UNTRUSTED_ENQUEUER) + CHK_ERRA(MSDTC_E_DUPLICATE_RESOURCE) + CHK_ERRA(COMADMIN_E_OBJECT_PARENT_MISSING) + CHK_ERRA(COMADMIN_E_OBJECT_DOES_NOT_EXIST) + CHK_ERRA(COMADMIN_E_APP_NOT_RUNNING) + CHK_ERRA(COMADMIN_E_INVALID_PARTITION) + CHK_ERRA(COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE) + CHK_ERRA(COMADMIN_E_USER_IN_SET) + CHK_ERRA(COMADMIN_E_CANTRECYCLELIBRARYAPPS) + CHK_ERRA(COMADMIN_E_CANTRECYCLESERVICEAPPS) + CHK_ERRA(COMADMIN_E_PROCESSALREADYRECYCLED) + CHK_ERRA(COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED) + CHK_ERRA(COMADMIN_E_CANTMAKEINPROCSERVICE) + CHK_ERRA(COMADMIN_E_PROGIDINUSEBYCLSID) + CHK_ERRA(COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET) + CHK_ERRA(COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED) + CHK_ERRA(COMADMIN_E_PARTITION_ACCESSDENIED) + CHK_ERRA(COMADMIN_E_PARTITION_MSI_ONLY) + CHK_ERRA(COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT) + CHK_ERRA(COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS) + CHK_ERRA(COMADMIN_E_COMP_MOVE_SOURCE) + CHK_ERRA(COMADMIN_E_COMP_MOVE_DEST) + CHK_ERRA(COMADMIN_E_COMP_MOVE_PRIVATE) + CHK_ERRA(COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET) + CHK_ERRA(COMADMIN_E_CANNOT_ALIAS_EVENTCLASS) + CHK_ERRA(COMADMIN_E_PRIVATE_ACCESSDENIED) + CHK_ERRA(COMADMIN_E_SAFERINVALID) + CHK_ERRA(COMADMIN_E_REGISTRY_ACCESSDENIED) +// CHK_ERRA(COMADMIN_E_PARTITIONS_DISABLED) +// CHK_ERR_WIN32A(ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY) +// CHK_ERR_WIN32A(ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY) + CHK_ERR_WIN32A(ERROR_DISK_TOO_FRAGMENTED) + CHK_ERR_WIN32A(ERROR_DELETE_PENDING) +// CHK_ERR_WIN32A(ERROR_SCOPE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_NOT_SAFEBOOT_SERVICE) + CHK_ERR_WIN32A(ERROR_JOURNAL_ENTRY_DELETED) + CHK_ERR_WIN32A(ERROR_ONLY_IF_CONNECTED) + CHK_ERR_WIN32A(ERROR_OVERRIDE_NOCHANGES) + CHK_ERR_WIN32A(ERROR_BAD_USER_PROFILE) + CHK_ERR_WIN32A(ERROR_NOT_SUPPORTED_ON_SBS) + CHK_ERR_WIN32A(ERROR_SERVER_SHUTDOWN_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_HOST_DOWN) + CHK_ERR_WIN32A(ERROR_NON_ACCOUNT_SID) + CHK_ERR_WIN32A(ERROR_NON_DOMAIN_SID) + CHK_ERR_WIN32A(ERROR_APPHELP_BLOCK) + CHK_ERR_WIN32A(ERROR_ACCESS_DISABLED_BY_POLICY) + CHK_ERR_WIN32A(ERROR_REG_NAT_CONSUMPTION) + CHK_ERR_WIN32A(ERROR_CSCSHARE_OFFLINE) + CHK_ERR_WIN32A(ERROR_PKINIT_FAILURE) + CHK_ERR_WIN32A(ERROR_SMARTCARD_SUBSYSTEM_FAILURE) + CHK_ERR_WIN32A(ERROR_DOWNGRADE_DETECTED) + CHK_ERR_WIN32A(ERROR_MACHINE_LOCKED) + CHK_ERR_WIN32A(ERROR_CALLBACK_SUPPLIED_INVALID_DATA) + CHK_ERR_WIN32A(ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED) + CHK_ERR_WIN32A(ERROR_DRIVER_BLOCKED) + CHK_ERR_WIN32A(ERROR_INVALID_IMPORT_OF_NON_DLL) +// CHK_ERR_WIN32A(ERROR_ACCESS_DISABLED_WEBBLADE) +// CHK_ERR_WIN32A(ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER) +// CHK_ERR_WIN32A(ERROR_RECOVERY_FAILURE) +// CHK_ERR_WIN32A(ERROR_ALREADY_FIBER) +// CHK_ERR_WIN32A(ERROR_ALREADY_THREAD) +// CHK_ERR_WIN32A(ERROR_STACK_BUFFER_OVERRUN) +// CHK_ERR_WIN32A(ERROR_PARAMETER_QUOTA_EXCEEDED) +// CHK_ERR_WIN32A(ERROR_DEBUGGER_INACTIVE) +// CHK_ERR_WIN32A(ERROR_DELAY_LOAD_FAILED) + CHK_ERR_WIN32A(ERROR_CURRENT_DOMAIN_NOT_ALLOWED) + CHK_ERR_WIN32A(ERROR_INSTALL_SERVICE_FAILURE) + CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_VERSION) + CHK_ERR_WIN32A(ERROR_INSTALL_ALREADY_RUNNING) + CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_OPEN_FAILED) + CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_INVALID) + CHK_ERR_WIN32A(ERROR_INSTALL_UI_FAILURE) + CHK_ERR_WIN32A(ERROR_INSTALL_LOG_FAILURE) + CHK_ERR_WIN32A(ERROR_INSTALL_LANGUAGE_UNSUPPORTED) + CHK_ERR_WIN32A(ERROR_INSTALL_TRANSFORM_FAILURE) + CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_REJECTED) + CHK_ERR_WIN32A(ERROR_FUNCTION_NOT_CALLED) + CHK_ERR_WIN32A(ERROR_FUNCTION_FAILED) + CHK_ERR_WIN32A(ERROR_INVALID_TABLE) + CHK_ERR_WIN32A(ERROR_DATATYPE_MISMATCH) + CHK_ERR_WIN32A(ERROR_UNSUPPORTED_TYPE) + CHK_ERR_WIN32A(ERROR_CREATE_FAILED) + CHK_ERR_WIN32A(ERROR_INSTALL_TEMP_UNWRITABLE) + CHK_ERR_WIN32A(ERROR_INSTALL_PLATFORM_UNSUPPORTED) + CHK_ERR_WIN32A(ERROR_INSTALL_NOTUSED) + CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_OPEN_FAILED) + CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_INVALID) + CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_UNSUPPORTED) + CHK_ERR_WIN32A(ERROR_PRODUCT_VERSION) + CHK_ERR_WIN32A(ERROR_INVALID_COMMAND_LINE) + CHK_ERR_WIN32A(ERROR_INSTALL_REMOTE_DISALLOWED) + CHK_ERR_WIN32A(ERROR_SUCCESS_REBOOT_INITIATED) + CHK_ERR_WIN32A(ERROR_PATCH_TARGET_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_REJECTED) + CHK_ERR_WIN32A(ERROR_INSTALL_TRANSFORM_REJECTED) +// CHK_ERR_WIN32A(ERROR_INSTALL_REMOTE_PROHIBITED) + CHK_ERR_WIN32A(RPC_S_ENTRY_TYPE_MISMATCH) + CHK_ERR_WIN32A(RPC_S_NOT_ALL_OBJS_EXPORTED) + CHK_ERR_WIN32A(RPC_S_INTERFACE_NOT_EXPORTED) + CHK_ERR_WIN32A(RPC_S_PROFILE_NOT_ADDED) + CHK_ERR_WIN32A(RPC_S_PRF_ELT_NOT_ADDED) + CHK_ERR_WIN32A(RPC_S_PRF_ELT_NOT_REMOVED) + CHK_ERR_WIN32A(RPC_S_GRP_ELT_NOT_ADDED) + CHK_ERR_WIN32A(RPC_S_GRP_ELT_NOT_REMOVED) + CHK_ERR_WIN32A(ERROR_KM_DRIVER_BLOCKED) + CHK_ERR_WIN32A(ERROR_CONTEXT_EXPIRED) +// CHK_ERR_WIN32A(ERROR_PER_USER_TRUST_QUOTA_EXCEEDED) +// CHK_ERR_WIN32A(ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED) +// CHK_ERR_WIN32A(ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED) + CHK_ERR_WIN32A(ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT) + CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_WARNED) + CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_BLOCKED) + CHK_ERR_WIN32A(ERROR_VOLUME_CONTAINS_SYS_FILES) + CHK_ERR_WIN32A(ERROR_INDIGENOUS_TYPE) + CHK_ERR_WIN32A(ERROR_NO_SUPPORTING_DRIVES) + CHK_ERR_WIN32A(ERROR_CLEANER_CARTRIDGE_INSTALLED) + CHK_ERR_WIN32A(ERROR_REPARSE_TAG_INVALID) + CHK_ERR_WIN32A(ERROR_REPARSE_TAG_MISMATCH) + CHK_ERR_WIN32A(ERROR_VOLUME_NOT_SIS_ENABLED) + CHK_ERR_WIN32A(ERROR_QUORUM_OWNER_ALIVE) + CHK_ERR_WIN32A(ERROR_NETWORK_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_NODE_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_ALL_NODES_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_RESOURCE_FAILED) + CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_NODE) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_EXISTS) + CHK_ERR_WIN32A(ERROR_CLUSTER_JOIN_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_EXISTS) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETINTERFACE_EXISTS) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETINTERFACE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_REQUEST) + CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_NETWORK_PROVIDER) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_DOWN) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_UNREACHABLE) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_MEMBER) + CHK_ERR_WIN32A(ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_NETWORK) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_UP) + CHK_ERR_WIN32A(ERROR_CLUSTER_IPADDR_IN_USE) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_PAUSED) + CHK_ERR_WIN32A(ERROR_CLUSTER_NO_SECURITY_CONTEXT) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_NOT_INTERNAL) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_UP) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_DOWN) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_ALREADY_ONLINE) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_MEMBER) + CHK_ERR_WIN32A(ERROR_CLUSTER_LAST_INTERNAL_NETWORK) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS) + CHK_ERR_WIN32A(ERROR_INVALID_OPERATION_ON_QUORUM) + CHK_ERR_WIN32A(ERROR_DEPENDENCY_NOT_ALLOWED) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_PAUSED) + CHK_ERR_WIN32A(ERROR_NODE_CANT_HOST_RESOURCE) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_READY) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_SHUTTING_DOWN) + CHK_ERR_WIN32A(ERROR_CLUSTER_JOIN_ABORTED) + CHK_ERR_WIN32A(ERROR_CLUSTER_INCOMPATIBLE_VERSIONS) + CHK_ERR_WIN32A(ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED) + CHK_ERR_WIN32A(ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED) + CHK_ERR_WIN32A(ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED) + CHK_ERR_WIN32A(ERROR_CLUSTER_RESNAME_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED) + CHK_ERR_WIN32A(ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST) + CHK_ERR_WIN32A(ERROR_CLUSTER_DATABASE_SEQMISMATCH) + CHK_ERR_WIN32A(ERROR_RESMON_INVALID_STATE) + CHK_ERR_WIN32A(ERROR_CLUSTER_GUM_NOT_LOCKER) + CHK_ERR_WIN32A(ERROR_QUORUM_DISK_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_DATABASE_BACKUP_CORRUPT) + CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT) + CHK_ERR_WIN32A(ERROR_RESOURCE_PROPERTY_UNCHANGEABLE) + CHK_ERR_WIN32A(ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE) + CHK_ERR_WIN32A(ERROR_CLUSTER_QUORUMLOG_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_CLUSTER_MEMBERSHIP_HALT) + CHK_ERR_WIN32A(ERROR_CLUSTER_INSTANCE_ID_MISMATCH) + CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP) + CHK_ERR_WIN32A(ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH) + CHK_ERR_WIN32A(ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP) + CHK_ERR_WIN32A(ERROR_CLUSTER_PARAMETER_MISMATCH) + CHK_ERR_WIN32A(ERROR_NODE_CANNOT_BE_CLUSTERED) + CHK_ERR_WIN32A(ERROR_CLUSTER_WRONG_OS_VERSION) + CHK_ERR_WIN32A(ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME) +// CHK_ERR_WIN32A(ERROR_CLUSCFG_ALREADY_COMMITTED) +// CHK_ERR_WIN32A(ERROR_CLUSCFG_ROLLBACK_FAILED) +// CHK_ERR_WIN32A(ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT) +// CHK_ERR_WIN32A(ERROR_CLUSTER_OLD_VERSION) +// CHK_ERR_WIN32A(ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME) + CHK_ERR_WIN32A(ERROR_FILE_READ_ONLY) + CHK_ERR_WIN32A(ERROR_DIR_EFS_DISALLOWED) + CHK_ERR_WIN32A(ERROR_EFS_SERVER_NOT_TRUSTED) + CHK_ERR_WIN32A(ERROR_BAD_RECOVERY_POLICY) + CHK_ERR_WIN32A(ERROR_EFS_ALG_BLOB_TOO_BIG) + CHK_ERR_WIN32A(ERROR_VOLUME_NOT_SUPPORT_EFS) + CHK_ERR_WIN32A(ERROR_EFS_DISABLED) + CHK_ERR_WIN32A(ERROR_EFS_VERSION_NOT_SUPPORT) + CHK_ERR_WIN32A(SCHED_E_SERVICE_NOT_LOCALSYSTEM) + CHK_ERR_WIN32A(ERROR_CTX_CLIENT_LICENSE_IN_USE) + CHK_ERR_WIN32A(ERROR_CTX_CLIENT_LICENSE_NOT_SET) + CHK_ERR_WIN32A(ERROR_CTX_LICENSE_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_CTX_LICENSE_CLIENT_INVALID) + CHK_ERR_WIN32A(ERROR_CTX_LICENSE_EXPIRED) + CHK_ERR_WIN32A(ERROR_CTX_SHADOW_NOT_RUNNING) + CHK_ERR_WIN32A(ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE) +// CHK_ERR_WIN32A(ERROR_ACTIVATION_COUNT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_SORT_CONTROL_MISSING) + CHK_ERR_WIN32A(ERROR_DS_OFFSET_RANGE_ERROR) + CHK_ERR_WIN32A(ERROR_DS_OBJECT_BEING_REMOVED) + CHK_ERR_WIN32A(ERROR_DS_DS_REQUIRED) + CHK_ERR_WIN32A(ERROR_DS_INVALID_LDAP_DISPLAY_NAME) + CHK_ERR_WIN32A(ERROR_DS_NON_BASE_SEARCH) + CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_ATTS) + CHK_ERR_WIN32A(ERROR_DS_BACKLINK_WITHOUT_LINK) + CHK_ERR_WIN32A(ERROR_DS_EPOCH_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_SRC_NAME_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_SRC_AND_DST_NC_IDENTICAL) + CHK_ERR_WIN32A(ERROR_DS_DST_NC_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC) + CHK_ERR_WIN32A(ERROR_DS_SRC_GUID_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_DELETED_OBJECT) + CHK_ERR_WIN32A(ERROR_DS_PDC_OPERATION_IN_PROGRESS) + CHK_ERR_WIN32A(ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD) + CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION) + CHK_ERR_WIN32A(ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS) + CHK_ERR_WIN32A(ERROR_DS_NC_MUST_HAVE_NC_PARENT) + CHK_ERR_WIN32A(ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE) + CHK_ERR_WIN32A(ERROR_DS_DST_DOMAIN_NOT_NATIVE) + CHK_ERR_WIN32A(ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER) + CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_ACCOUNT_GROUP) + CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_RESOURCE_GROUP) + CHK_ERR_WIN32A(ERROR_DS_INVALID_SEARCH_FLAG) + CHK_ERR_WIN32A(ERROR_DS_NO_TREE_DELETE_ABOVE_NC) + CHK_ERR_WIN32A(ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE) + CHK_ERR_WIN32A(ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE) + CHK_ERR_WIN32A(ERROR_DS_SAM_INIT_FAILURE) + CHK_ERR_WIN32A(ERROR_DS_SENSITIVE_GROUP_VIOLATION) + CHK_ERR_WIN32A(ERROR_DS_CANT_MOD_PRIMARYGROUPID) + CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD) + CHK_ERR_WIN32A(ERROR_DS_NONSAFE_SCHEMA_CHANGE) + CHK_ERR_WIN32A(ERROR_DS_SCHEMA_UPDATE_DISALLOWED) + CHK_ERR_WIN32A(ERROR_DS_CANT_CREATE_UNDER_SCHEMA) + CHK_ERR_WIN32A(ERROR_DS_INSTALL_NO_SRC_SCH_VERSION) + CHK_ERR_WIN32A(ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE) + CHK_ERR_WIN32A(ERROR_DS_INVALID_GROUP_TYPE) + CHK_ERR_WIN32A(ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN) + CHK_ERR_WIN32A(ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN) + CHK_ERR_WIN32A(ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER) + CHK_ERR_WIN32A(ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER) + CHK_ERR_WIN32A(ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER) + CHK_ERR_WIN32A(ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER) + CHK_ERR_WIN32A(ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER) + CHK_ERR_WIN32A(ERROR_DS_HAVE_PRIMARY_MEMBERS) + CHK_ERR_WIN32A(ERROR_DS_STRING_SD_CONVERSION_FAILED) + CHK_ERR_WIN32A(ERROR_DS_NAMING_MASTER_GC) + CHK_ERR_WIN32A(ERROR_DS_DNS_LOOKUP_FAILURE) + CHK_ERR_WIN32A(ERROR_DS_COULDNT_UPDATE_SPNS) + CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_SD) + CHK_ERR_WIN32A(ERROR_DS_KEY_NOT_UNIQUE) + CHK_ERR_WIN32A(ERROR_DS_WRONG_LINKED_ATT_SYNTAX) + CHK_ERR_WIN32A(ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD) + CHK_ERR_WIN32A(ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY) + CHK_ERR_WIN32A(ERROR_DS_CANT_START) + CHK_ERR_WIN32A(ERROR_DS_INIT_FAILURE) + CHK_ERR_WIN32A(ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION) + CHK_ERR_WIN32A(ERROR_DS_SOURCE_DOMAIN_IN_FOREST) + CHK_ERR_WIN32A(ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST) + CHK_ERR_WIN32A(ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED) + CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN) + CHK_ERR_WIN32A(ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER) + CHK_ERR_WIN32A(ERROR_DS_SRC_SID_EXISTS_IN_FOREST) + CHK_ERR_WIN32A(ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH) + CHK_ERR_WIN32A(ERROR_SAM_INIT_FAILURE) + CHK_ERR_WIN32A(ERROR_DS_DRA_SCHEMA_INFO_SHIP) + CHK_ERR_WIN32A(ERROR_DS_DRA_SCHEMA_CONFLICT) + CHK_ERR_WIN32A(ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT) + CHK_ERR_WIN32A(ERROR_DS_DRA_OBJ_NC_MISMATCH) + CHK_ERR_WIN32A(ERROR_DS_NC_STILL_HAS_DSAS) + CHK_ERR_WIN32A(ERROR_DS_GC_REQUIRED) + CHK_ERR_WIN32A(ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY) + CHK_ERR_WIN32A(ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS) + CHK_ERR_WIN32A(ERROR_DS_CANT_ADD_TO_GC) + CHK_ERR_WIN32A(ERROR_DS_NO_CHECKPOINT_WITH_PDC) + CHK_ERR_WIN32A(ERROR_DS_SOURCE_AUDITING_NOT_ENABLED) + CHK_ERR_WIN32A(ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC) + CHK_ERR_WIN32A(ERROR_DS_INVALID_NAME_FOR_SPN) + CHK_ERR_WIN32A(ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS) + CHK_ERR_WIN32A(ERROR_DS_UNICODEPWD_NOT_IN_QUOTES) + CHK_ERR_WIN32A(ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_MUST_BE_RUN_ON_DST_DC) + CHK_ERR_WIN32A(ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER) + CHK_ERR_WIN32A(ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ) + CHK_ERR_WIN32A(ERROR_DS_INIT_FAILURE_CONSOLE) + CHK_ERR_WIN32A(ERROR_DS_SAM_INIT_FAILURE_CONSOLE) + CHK_ERR_WIN32A(ERROR_DS_FOREST_VERSION_TOO_HIGH) + CHK_ERR_WIN32A(ERROR_DS_DOMAIN_VERSION_TOO_HIGH) + CHK_ERR_WIN32A(ERROR_DS_FOREST_VERSION_TOO_LOW) + CHK_ERR_WIN32A(ERROR_DS_DOMAIN_VERSION_TOO_LOW) + CHK_ERR_WIN32A(ERROR_DS_INCOMPATIBLE_VERSION) + CHK_ERR_WIN32A(ERROR_DS_LOW_DSA_VERSION) + CHK_ERR_WIN32A(ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN) + CHK_ERR_WIN32A(ERROR_DS_NOT_SUPPORTED_SORT_ORDER) + CHK_ERR_WIN32A(ERROR_DS_NAME_NOT_UNIQUE) + CHK_ERR_WIN32A(ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4) + CHK_ERR_WIN32A(ERROR_DS_OUT_OF_VERSION_STORE) + CHK_ERR_WIN32A(ERROR_DS_INCOMPATIBLE_CONTROLS_USED) + CHK_ERR_WIN32A(ERROR_DS_NO_REF_DOMAIN) + CHK_ERR_WIN32A(ERROR_DS_RESERVED_LINK_ID) + CHK_ERR_WIN32A(ERROR_DS_LINK_ID_NOT_AVAILABLE) + CHK_ERR_WIN32A(ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER) + CHK_ERR_WIN32A(ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE) + CHK_ERR_WIN32A(ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC) + CHK_ERR_WIN32A(ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG) + CHK_ERR_WIN32A(ERROR_DS_MODIFYDN_WRONG_GRANDPARENT) + CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_TRUST_REFERRAL) + CHK_ERR_WIN32A(ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER) + CHK_ERR_WIN32A(ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD) + CHK_ERR_WIN32A(ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2) + CHK_ERR_WIN32A(ERROR_DS_THREAD_LIMIT_EXCEEDED) + CHK_ERR_WIN32A(ERROR_DS_NOT_CLOSEST) + CHK_ERR_WIN32A(ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF) + CHK_ERR_WIN32A(ERROR_DS_SINGLE_USER_MODE_FAILED) + CHK_ERR_WIN32A(ERROR_DS_NTDSCRIPT_SYNTAX_ERROR) + CHK_ERR_WIN32A(ERROR_DS_NTDSCRIPT_PROCESS_ERROR) + CHK_ERR_WIN32A(ERROR_DS_DIFFERENT_REPL_EPOCHS) + CHK_ERR_WIN32A(ERROR_DS_DRS_EXTENSIONS_CHANGED) + CHK_ERR_WIN32A(ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR) + CHK_ERR_WIN32A(ERROR_DS_NO_MSDS_INTID) + CHK_ERR_WIN32A(ERROR_DS_DUP_MSDS_INTID) + CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_RDNATTID) + CHK_ERR_WIN32A(ERROR_DS_AUTHORIZATION_FAILED) + CHK_ERR_WIN32A(ERROR_DS_INVALID_SCRIPT) + CHK_ERR_WIN32A(ERROR_DS_REMOTE_CROSSREF_OP_FAILED) +// CHK_ERR_WIN32A(ERROR_DS_CROSS_REF_BUSY) +// CHK_ERR_WIN32A(ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN) +// CHK_ERR_WIN32A(ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC) +// CHK_ERR_WIN32A(ERROR_DS_DUPLICATE_ID_FOUND) +// CHK_ERR_WIN32A(ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT) +// CHK_ERR_WIN32A(ERROR_DS_GROUP_CONVERSION_ERROR) +// CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_APP_BASIC_GROUP) +// CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_APP_QUERY_GROUP) +// CHK_ERR_WIN32A(ERROR_DS_ROLE_NOT_VERIFIED) +// CHK_ERR_WIN32A(ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL) +// CHK_ERR_WIN32A(ERROR_DS_DOMAIN_RENAME_IN_PROGRESS) +// CHK_ERR_WIN32A(ERROR_DS_EXISTING_AD_CHILD_NC) +// CHK_ERR_WIN32A(DNS_ERROR_INVALID_NAME_CHAR) +// CHK_ERR_WIN32A(DNS_ERROR_NUMERIC_NAME) +// CHK_ERR_WIN32A(DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER) +// CHK_ERR_WIN32A(DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION) +// CHK_ERR_WIN32A(DNS_ERROR_CANNOT_FIND_ROOT_HINTS) +// CHK_ERR_WIN32A(DNS_ERROR_INCONSISTENT_ROOT_HINTS) + CHK_ERR_WIN32A(DNS_ERROR_FORWARDER_ALREADY_EXISTS) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_REQUIRES_MASTER_IP) + CHK_ERR_WIN32A(DNS_ERROR_ZONE_IS_SHUTDOWN) + CHK_ERR_WIN32A(DNS_ERROR_DP_BASE) + CHK_ERR_WIN32A(DNS_ERROR_DP_DOES_NOT_EXIST) + CHK_ERR_WIN32A(DNS_ERROR_DP_ALREADY_EXISTS) + CHK_ERR_WIN32A(DNS_ERROR_DP_NOT_ENLISTED) + CHK_ERR_WIN32A(DNS_ERROR_DP_ALREADY_ENLISTED) +// CHK_ERR_WIN32A(DNS_ERROR_DP_NOT_AVAILABLE) + CHK_ERR_WIN32A(WSA_QOS_ESERVICETYPE) + CHK_ERR_WIN32A(WSA_QOS_EFLOWSPEC) + CHK_ERR_WIN32A(WSA_QOS_EPROVSPECBUF) + CHK_ERR_WIN32A(WSA_QOS_EFILTERSTYLE) + CHK_ERR_WIN32A(WSA_QOS_EFILTERTYPE) + CHK_ERR_WIN32A(WSA_QOS_EFILTERCOUNT) + CHK_ERR_WIN32A(WSA_QOS_EOBJLENGTH) + CHK_ERR_WIN32A(WSA_QOS_EFLOWCOUNT) + CHK_ERR_WIN32A(WSA_QOS_EUNKOWNPSOBJ) + CHK_ERR_WIN32A(WSA_QOS_EPOLICYOBJ) + CHK_ERR_WIN32A(WSA_QOS_EFLOWDESC) + CHK_ERR_WIN32A(WSA_QOS_EPSFLOWSPEC) + CHK_ERR_WIN32A(WSA_QOS_EPSFILTERSPEC) + CHK_ERR_WIN32A(WSA_QOS_ESDMODEOBJ) + CHK_ERR_WIN32A(WSA_QOS_ESHAPERATEOBJ) + CHK_ERR_WIN32A(WSA_QOS_RESERVED_PETYPE) + CHK_ERR_WIN32A(ERROR_SXS_SECTION_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_SXS_CANT_GEN_ACTCTX) + CHK_ERR_WIN32A(ERROR_SXS_INVALID_ACTCTXDATA_FORMAT) + CHK_ERR_WIN32A(ERROR_SXS_ASSEMBLY_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_FORMAT_ERROR) + CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_PARSE_ERROR) + CHK_ERR_WIN32A(ERROR_SXS_ACTIVATION_CONTEXT_DISABLED) + CHK_ERR_WIN32A(ERROR_SXS_KEY_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_SXS_VERSION_CONFLICT) + CHK_ERR_WIN32A(ERROR_SXS_WRONG_SECTION_TYPE) + CHK_ERR_WIN32A(ERROR_SXS_THREAD_QUERIES_DISABLED) + CHK_ERR_WIN32A(ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET) + CHK_ERR_WIN32A(ERROR_SXS_UNKNOWN_ENCODING_GROUP) + CHK_ERR_WIN32A(ERROR_SXS_UNKNOWN_ENCODING) + CHK_ERR_WIN32A(ERROR_SXS_INVALID_XML_NAMESPACE_URI) + CHK_ERR_WIN32A(ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED) + CHK_ERR_WIN32A(ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED) + CHK_ERR_WIN32A(ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE) + CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE) + CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE) + CHK_ERR_WIN32A(ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT) + CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_DLL_NAME) + CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME) + CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_CLSID) + CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_IID) + CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_TLBID) + CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_PROGID) + CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_ASSEMBLY_NAME) + CHK_ERR_WIN32A(ERROR_SXS_FILE_HASH_MISMATCH) + CHK_ERR_WIN32A(ERROR_SXS_POLICY_PARSE_ERROR) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGQUOTE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_COMMENTSYNTAX) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADSTARTNAMECHAR) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADNAMECHAR) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADCHARINSTRING) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_XMLDECLSYNTAX) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADCHARDATA) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGWHITESPACE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_EXPECTINGTAGEND) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGSEMICOLON) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNBALANCEDPAREN) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INTERNALERROR) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INCOMPLETE_ENCODING) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSING_PAREN) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MULTIPLE_COLONS) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_DECIMAL) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_HEXIDECIMAL) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_UNICODE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTEDENDTAG) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDTAG) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_DUPLICATEATTRIBUTE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MULTIPLEROOTS) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALIDATROOTLEVEL) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADXMLDECL) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGROOT) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTEDEOF) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADPEREFINSUBSET) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDSTARTTAG) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDENDTAG) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDSTRING) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDCOMMENT) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDDECL) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDCDATA) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_RESERVEDNAMESPACE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALIDENCODING) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALIDSWITCH) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADXMLCASE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_STANDALONE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTED_STANDALONE) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_VERSION) + CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGEQUALS) + CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_RECOVERY_FAILED) + CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT) + CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_CATALOG_NOT_VALID) + CHK_ERR_WIN32A(ERROR_SXS_UNTRANSLATABLE_HRESULT) + CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING) + CHK_ERR_WIN32A(ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE) + CHK_ERR_WIN32A(ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME) + CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_EXISTS) + CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_IN_USE) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_EXISTS) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_IN_USE) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_FILTER_EXISTS) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_FILTER_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_TRANSPORT_FILTER_EXISTS) + CHK_ERR_WIN32A(ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_EXISTS) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_IN_USE) + CHK_ERR_WIN32A(ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_TUNNEL_FILTER_EXISTS) + CHK_ERR_WIN32A(ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_FILTER_PENDING_DELETION) + CHK_ERR_WIN32A(ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION) + CHK_ERR_WIN32A(ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_PENDING_DELETION) + CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_PENDING_DELETION) + CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_PENDING_DELETION) +// CHK_ERR_WIN32A(WARNING_IPSEC_MM_POLICY_PRUNED) +// CHK_ERR_WIN32A(WARNING_IPSEC_QM_POLICY_PRUNED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEG_STATUS_BEGIN) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_AUTH_FAIL) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ATTRIB_FAIL) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEGOTIATION_PENDING) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_TIMED_OUT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_CERT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SA_DELETED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SA_REAPED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_MM_ACQUIRE_DROP) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QM_ACQUIRE_DROP) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QUEUE_DROP_MM) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DROP_NO_RESPONSE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_MM_DELAY_DROP) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QM_DELAY_DROP) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ERROR) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_CRL_FAILED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_KEY_USAGE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_CERT_TYPE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_PRIVATE_KEY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DH_FAIL) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HEADER) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_POLICY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_SIGNATURE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_KERBEROS_ERROR) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_PUBLIC_KEY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_SA) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_PROP) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_TRANS) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_KE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_ID) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_CERT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_HASH) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_SIG) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_NONCE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_DELETE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_PAYLOAD) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_LOAD_SOFT_SA) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_COOKIE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_PEER_CERT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PEER_CRL_FAILED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_POLICY_CHANGE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_MM_POLICY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NOTCBPRIV) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SECLOADFAIL) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_FAILSSPINIT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_FAILQUERYSSP) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SRVACQFAIL) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SRVQUERYCRED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_GETSPIFAIL) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_FILTER) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_OUT_OF_MEMORY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_POLICY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_UNKNOWN_DOI) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_SITUATION) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DH_FAILURE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_GROUP) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ENCRYPT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DECRYPT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_POLICY_MATCH) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_UNSUPPORTED_ID) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HASH) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HASH_ALG) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HASH_SIZE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_AUTH_ALG) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_SIG) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_LOAD_FAILED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_RPC_DELETE) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_BENIGN_REINIT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_MM_LIMIT) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEGOTIATION_DISABLED) + CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEG_STATUS_END) + +// ------------------------------------------------------------- +// ddraw.h error codes +// ------------------------------------------------------------- + CHK_ERRA(DDERR_ALREADYINITIALIZED) + CHK_ERRA(DDERR_CANNOTATTACHSURFACE) + CHK_ERRA(DDERR_CANNOTDETACHSURFACE) + CHK_ERRA(DDERR_CURRENTLYNOTAVAIL) + CHK_ERRA(DDERR_EXCEPTION) +// CHK_ERRA(DDERR_GENERIC) + CHK_ERRA(DDERR_HEIGHTALIGN) + CHK_ERRA(DDERR_INCOMPATIBLEPRIMARY) + CHK_ERRA(DDERR_INVALIDCAPS) + CHK_ERRA(DDERR_INVALIDCLIPLIST) + CHK_ERRA(DDERR_INVALIDMODE) + CHK_ERRA(DDERR_INVALIDOBJECT) +// CHK_ERRA(DDERR_INVALIDPARAMS) + CHK_ERRA(DDERR_INVALIDPIXELFORMAT) + CHK_ERRA(DDERR_INVALIDRECT) + CHK_ERRA(DDERR_LOCKEDSURFACES) + CHK_ERRA(DDERR_NO3D) + CHK_ERRA(DDERR_NOALPHAHW) + CHK_ERRA(DDERR_NOSTEREOHARDWARE) + CHK_ERRA(DDERR_NOSURFACELEFT) + CHK_ERRA(DDERR_NOCLIPLIST) + CHK_ERRA(DDERR_NOCOLORCONVHW) + CHK_ERRA(DDERR_NOCOOPERATIVELEVELSET) + CHK_ERRA(DDERR_NOCOLORKEY) + CHK_ERRA(DDERR_NOCOLORKEYHW) + CHK_ERRA(DDERR_NODIRECTDRAWSUPPORT) + CHK_ERRA(DDERR_NOEXCLUSIVEMODE) + CHK_ERRA(DDERR_NOFLIPHW) + CHK_ERRA(DDERR_NOGDI) + CHK_ERRA(DDERR_NOMIRRORHW) + CHK_ERRA(DDERR_NOTFOUND) + CHK_ERRA(DDERR_NOOVERLAYHW) + CHK_ERRA(DDERR_OVERLAPPINGRECTS) + CHK_ERRA(DDERR_NORASTEROPHW) + CHK_ERRA(DDERR_NOROTATIONHW) + CHK_ERRA(DDERR_NOSTRETCHHW) + CHK_ERRA(DDERR_NOT4BITCOLOR) + CHK_ERRA(DDERR_NOT4BITCOLORINDEX) + CHK_ERRA(DDERR_NOT8BITCOLOR) + CHK_ERRA(DDERR_NOTEXTUREHW) + CHK_ERRA(DDERR_NOVSYNCHW) + CHK_ERRA(DDERR_NOZBUFFERHW) + CHK_ERRA(DDERR_NOZOVERLAYHW) + CHK_ERRA(DDERR_OUTOFCAPS) +// CHK_ERRA(DDERR_OUTOFMEMORY) +// CHK_ERRA(DDERR_OUTOFVIDEOMEMORY) + CHK_ERRA(DDERR_OVERLAYCANTCLIP) + CHK_ERRA(DDERR_OVERLAYCOLORKEYONLYONEACTIVE) + CHK_ERRA(DDERR_PALETTEBUSY) + CHK_ERRA(DDERR_COLORKEYNOTSET) + CHK_ERRA(DDERR_SURFACEALREADYATTACHED) + CHK_ERRA(DDERR_SURFACEALREADYDEPENDENT) + CHK_ERRA(DDERR_SURFACEBUSY) + CHK_ERRA(DDERR_CANTLOCKSURFACE) + CHK_ERRA(DDERR_SURFACEISOBSCURED) + CHK_ERRA(DDERR_SURFACELOST) + CHK_ERRA(DDERR_SURFACENOTATTACHED) + CHK_ERRA(DDERR_TOOBIGHEIGHT) + CHK_ERRA(DDERR_TOOBIGSIZE) + CHK_ERRA(DDERR_TOOBIGWIDTH) +// CHK_ERRA(DDERR_UNSUPPORTED) + CHK_ERRA(DDERR_UNSUPPORTEDFORMAT) + CHK_ERRA(DDERR_UNSUPPORTEDMASK) + CHK_ERRA(DDERR_INVALIDSTREAM) + CHK_ERRA(DDERR_VERTICALBLANKINPROGRESS) + CHK_ERRA(DDERR_WASSTILLDRAWING) + CHK_ERRA(DDERR_DDSCAPSCOMPLEXREQUIRED) + CHK_ERRA(DDERR_XALIGN) + CHK_ERRA(DDERR_INVALIDDIRECTDRAWGUID) + CHK_ERRA(DDERR_DIRECTDRAWALREADYCREATED) + CHK_ERRA(DDERR_NODIRECTDRAWHW) + CHK_ERRA(DDERR_PRIMARYSURFACEALREADYEXISTS) + CHK_ERRA(DDERR_NOEMULATION) + CHK_ERRA(DDERR_REGIONTOOSMALL) + CHK_ERRA(DDERR_CLIPPERISUSINGHWND) + CHK_ERRA(DDERR_NOCLIPPERATTACHED) + CHK_ERRA(DDERR_NOHWND) + CHK_ERRA(DDERR_HWNDSUBCLASSED) + CHK_ERRA(DDERR_HWNDALREADYSET) + CHK_ERRA(DDERR_NOPALETTEATTACHED) + CHK_ERRA(DDERR_NOPALETTEHW) + CHK_ERRA(DDERR_BLTFASTCANTCLIP) + CHK_ERRA(DDERR_NOBLTHW) + CHK_ERRA(DDERR_NODDROPSHW) + CHK_ERRA(DDERR_OVERLAYNOTVISIBLE) + CHK_ERRA(DDERR_NOOVERLAYDEST) + CHK_ERRA(DDERR_INVALIDPOSITION) + CHK_ERRA(DDERR_NOTAOVERLAYSURFACE) + CHK_ERRA(DDERR_EXCLUSIVEMODEALREADYSET) + CHK_ERRA(DDERR_NOTFLIPPABLE) + CHK_ERRA(DDERR_CANTDUPLICATE) + CHK_ERRA(DDERR_NOTLOCKED) + CHK_ERRA(DDERR_CANTCREATEDC) + CHK_ERRA(DDERR_NODC) + CHK_ERRA(DDERR_WRONGMODE) + CHK_ERRA(DDERR_IMPLICITLYCREATED) + CHK_ERRA(DDERR_NOTPALETTIZED) + CHK_ERRA(DDERR_UNSUPPORTEDMODE) + CHK_ERRA(DDERR_NOMIPMAPHW) + CHK_ERRA(DDERR_INVALIDSURFACETYPE) + CHK_ERRA(DDERR_NOOPTIMIZEHW) + CHK_ERRA(DDERR_NOTLOADED) + CHK_ERRA(DDERR_NOFOCUSWINDOW) + CHK_ERRA(DDERR_NOTONMIPMAPSUBLEVEL) + CHK_ERRA(DDERR_DCALREADYCREATED) + CHK_ERRA(DDERR_NONONLOCALVIDMEM) + CHK_ERRA(DDERR_CANTPAGELOCK) + CHK_ERRA(DDERR_CANTPAGEUNLOCK) + CHK_ERRA(DDERR_NOTPAGELOCKED) + CHK_ERRA(DDERR_MOREDATA) + CHK_ERRA(DDERR_EXPIRED) + CHK_ERRA(DDERR_TESTFINISHED) + CHK_ERRA(DDERR_NEWMODE) + CHK_ERRA(DDERR_D3DNOTINITIALIZED) + CHK_ERRA(DDERR_VIDEONOTACTIVE) + CHK_ERRA(DDERR_NOMONITORINFORMATION) + CHK_ERRA(DDERR_NODRIVERSUPPORT) + CHK_ERRA(DDERR_DEVICEDOESNTOWNSURFACE) + +// ------------------------------------------------------------- +// d3d10.h error codes +// ------------------------------------------------------------- + CHK_ERRA(D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS) + CHK_ERRA(D3D10_ERROR_FILE_NOT_FOUND) + +// ------------------------------------------------------------- +// dxgi.h error codes +// ------------------------------------------------------------- + CHK_ERRA(DXGI_STATUS_OCCLUDED) + CHK_ERRA(DXGI_STATUS_CLIPPED) + CHK_ERRA(DXGI_STATUS_NO_REDIRECTION) + CHK_ERRA(DXGI_STATUS_NO_DESKTOP_ACCESS) + CHK_ERRA(DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE) + CHK_ERRA(DXGI_STATUS_MODE_CHANGED) + CHK_ERRA(DXGI_STATUS_MODE_CHANGE_IN_PROGRESS) + CHK_ERRA(DXGI_ERROR_INVALID_CALL) + CHK_ERRA(DXGI_ERROR_NOT_FOUND) + CHK_ERRA(DXGI_ERROR_MORE_DATA) + CHK_ERRA(DXGI_ERROR_UNSUPPORTED) + CHK_ERRA(DXGI_ERROR_DEVICE_REMOVED) + CHK_ERRA(DXGI_ERROR_DEVICE_HUNG) + CHK_ERRA(DXGI_ERROR_DEVICE_RESET) + CHK_ERRA(DXGI_ERROR_WAS_STILL_DRAWING) + CHK_ERRA(DXGI_ERROR_FRAME_STATISTICS_DISJOINT) + CHK_ERRA(DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE) + CHK_ERRA(DXGI_ERROR_DRIVER_INTERNAL_ERROR) + CHK_ERRA(DXGI_ERROR_NONEXCLUSIVE) + CHK_ERRA(DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) + CHK_ERRA(DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED) + CHK_ERRA(DXGI_ERROR_REMOTE_OUTOFMEMORY) + +// ------------------------------------------------------------- +// d3d11.h error codes +// ------------------------------------------------------------- + CHK_ERRA(D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS) + CHK_ERRA(D3D11_ERROR_FILE_NOT_FOUND) + CHK_ERRA(D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS) + CHK_ERRA(D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD) + +// ------------------------------------------------------------- +// Direct2D error codes +// ------------------------------------------------------------- + CHK_ERRA(D2DERR_UNSUPPORTED_PIXEL_FORMAT) +// CHK_ERRA(D2DERR_INSUFFICIENT_BUFFER) + CHK_ERRA(D2DERR_WRONG_STATE) + CHK_ERRA(D2DERR_NOT_INITIALIZED) + CHK_ERRA(D2DERR_UNSUPPORTED_OPERATION) + CHK_ERRA(D2DERR_SCANNER_FAILED) + CHK_ERRA(D2DERR_SCREEN_ACCESS_DENIED) + CHK_ERRA(D2DERR_DISPLAY_STATE_INVALID) + CHK_ERRA(D2DERR_ZERO_VECTOR) + CHK_ERRA(D2DERR_INTERNAL_ERROR) + CHK_ERRA(D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED) + CHK_ERRA(D2DERR_INVALID_CALL) + CHK_ERRA(D2DERR_NO_HARDWARE_DEVICE) + CHK_ERRA(D2DERR_RECREATE_TARGET) + CHK_ERRA(D2DERR_TOO_MANY_SHADER_ELEMENTS) + CHK_ERRA(D2DERR_SHADER_COMPILE_FAILED) + CHK_ERRA(D2DERR_MAX_TEXTURE_SIZE_EXCEEDED) + CHK_ERRA(D2DERR_UNSUPPORTED_VERSION) + CHK_ERRA(D2DERR_BAD_NUMBER) + CHK_ERRA(D2DERR_WRONG_FACTORY) + CHK_ERRA(D2DERR_LAYER_ALREADY_IN_USE) + CHK_ERRA(D2DERR_POP_CALL_DID_NOT_MATCH_PUSH) +// CHK_ERRA(D2DERR_WRONG_RESOURCE_DOMAIN) + CHK_ERRA(D2DERR_PUSH_POP_UNBALANCED) + CHK_ERRA(D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT) + CHK_ERRA(D2DERR_INCOMPATIBLE_BRUSH_TYPES) + CHK_ERRA(D2DERR_WIN32_ERROR) + CHK_ERRA(D2DERR_TARGET_NOT_GDI_COMPATIBLE) + CHK_ERRA(D2DERR_TEXT_EFFECT_IS_WRONG_TYPE) + CHK_ERRA(D2DERR_TEXT_RENDERER_NOT_RELEASED) +// CHK_ERRA(D2DERR_EXCEEDS_MAX_BITMAP_SIZE) + +// ------------------------------------------------------------- +// DirectWrite error codes +// ------------------------------------------------------------- + CHK_ERRA(DWRITE_E_FILEFORMAT) + CHK_ERRA(DWRITE_E_UNEXPECTED) + CHK_ERRA(DWRITE_E_NOFONT) + CHK_ERRA(DWRITE_E_FILENOTFOUND) + CHK_ERRA(DWRITE_E_FILEACCESS) + CHK_ERRA(DWRITE_E_FONTCOLLECTIONOBSOLETE) + CHK_ERRA(DWRITE_E_ALREADYREGISTERED) + +// ------------------------------------------------------------- +// WIC error codes +// ------------------------------------------------------------- + CHK_ERRA(WINCODEC_ERR_WRONGSTATE) + CHK_ERRA(WINCODEC_ERR_VALUEOUTOFRANGE) + CHK_ERRA(WINCODEC_ERR_UNKNOWNIMAGEFORMAT) + CHK_ERRA(WINCODEC_ERR_UNSUPPORTEDVERSION) + CHK_ERRA(WINCODEC_ERR_NOTINITIALIZED) + CHK_ERRA(WINCODEC_ERR_ALREADYLOCKED) + CHK_ERRA(WINCODEC_ERR_PROPERTYNOTFOUND) + CHK_ERRA(WINCODEC_ERR_PROPERTYNOTSUPPORTED) + CHK_ERRA(WINCODEC_ERR_PROPERTYSIZE) + CHK_ERRA(WINCODEC_ERR_CODECPRESENT) + CHK_ERRA(WINCODEC_ERR_CODECNOTHUMBNAIL) + CHK_ERRA(WINCODEC_ERR_PALETTEUNAVAILABLE) + CHK_ERRA(WINCODEC_ERR_CODECTOOMANYSCANLINES) + CHK_ERRA(WINCODEC_ERR_INTERNALERROR) + CHK_ERRA(WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS) + CHK_ERRA(WINCODEC_ERR_COMPONENTNOTFOUND) + CHK_ERRA(WINCODEC_ERR_IMAGESIZEOUTOFRANGE) + CHK_ERRA(WINCODEC_ERR_TOOMUCHMETADATA) + CHK_ERRA(WINCODEC_ERR_BADIMAGE) + CHK_ERRA(WINCODEC_ERR_BADHEADER) + CHK_ERRA(WINCODEC_ERR_FRAMEMISSING) + CHK_ERRA(WINCODEC_ERR_BADMETADATAHEADER) + CHK_ERRA(WINCODEC_ERR_BADSTREAMDATA) + CHK_ERRA(WINCODEC_ERR_STREAMWRITE) + CHK_ERRA(WINCODEC_ERR_STREAMREAD) + CHK_ERRA(WINCODEC_ERR_STREAMNOTAVAILABLE) +// CHK_ERRA(WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT) + CHK_ERRA(WINCODEC_ERR_UNSUPPORTEDOPERATION) + CHK_ERRA(WINCODEC_ERR_INVALIDREGISTRATION) + CHK_ERRA(WINCODEC_ERR_COMPONENTINITIALIZEFAILURE) + CHK_ERRA(WINCODEC_ERR_INSUFFICIENTBUFFER) + CHK_ERRA(WINCODEC_ERR_DUPLICATEMETADATAPRESENT) + CHK_ERRA(WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE) + CHK_ERRA(WINCODEC_ERR_UNEXPECTEDSIZE) + CHK_ERRA(WINCODEC_ERR_INVALIDQUERYREQUEST) + CHK_ERRA(WINCODEC_ERR_UNEXPECTEDMETADATATYPE) + CHK_ERRA(WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT) + CHK_ERRA(WINCODEC_ERR_INVALIDQUERYCHARACTER) + CHK_ERRA(WINCODEC_ERR_WIN32ERROR) + CHK_ERRA(WINCODEC_ERR_INVALIDPROGRESSIVELEVEL) + +// ------------------------------------------------------------- +// DXUT error codes +// ------------------------------------------------------------- + CHK_ERRA(DXUTERR_NODIRECT3D) + CHK_ERRA(DXUTERR_NOCOMPATIBLEDEVICES) + CHK_ERRA(DXUTERR_MEDIANOTFOUND) + CHK_ERRA(DXUTERR_NONZEROREFCOUNT) + CHK_ERRA(DXUTERR_CREATINGDEVICE) + CHK_ERRA(DXUTERR_RESETTINGDEVICE) + CHK_ERRA(DXUTERR_CREATINGDEVICEOBJECTS) + CHK_ERRA(DXUTERR_RESETTINGDEVICEOBJECTS) + CHK_ERRA(DXUTERR_INCORRECTVERSION) + CHK_ERRA(DXUTERR_DEVICEREMOVED) + +// ------------------------------------------------------------- +// xaudio2.h error codes +// ------------------------------------------------------------- + CHK_ERRA(XAUDIO2_E_INVALID_CALL) + CHK_ERRA(XAUDIO2_E_XMA_DECODER_ERROR) + CHK_ERRA(XAUDIO2_E_XAPO_CREATION_FAILED) + CHK_ERRA(XAUDIO2_E_DEVICE_INVALIDATED) + +// ------------------------------------------------------------- +// xapo.h error codes +// ------------------------------------------------------------- + CHK_ERRA(XAPO_E_FORMAT_UNSUPPORTED) + + default: return L"Unknown error."; + } +} + +//-------------------------------------------------------------------------------------- +#undef CHK_ERR +#undef CHK_ERRA +#undef HRESULT_FROM_WIN32b +#undef CHK_ERR_WIN32A +#undef CHK_ERR_WIN32_ONLY + +#define CHK_ERRA(hrchk) \ + case hrchk: \ + wcscpy_s( desc, count, L#hrchk ); break; + +#define CHK_ERR(hrchk, strOut) \ + case hrchk: \ + wcscpy_s( desc, count, L##strOut ); break; + + +//-------------------------------------------------------------------------------------- +void WINAPI DXGetErrorDescriptionW( _In_ HRESULT hr, _Out_cap_(count) WCHAR* desc, _In_ size_t count ) +{ + if ( !count ) + return; + + *desc = 0; + + // First try to see if FormatMessage knows this hr + LPWSTR errorText = nullptr; + + DWORD result = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ALLOCATE_BUFFER, nullptr, hr, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&errorText, 0, nullptr ); + + if (result > 0 && errorText) + { + wcscpy_s( desc, count, errorText ); + + if ( errorText ) + LocalFree( errorText ); + + return; + } + + switch (hr) + { +// Commmented out codes are actually alises for other codes + +// ------------------------------------------------------------- +// ddraw.h error codes +// ------------------------------------------------------------- + CHK_ERR(DDERR_ALREADYINITIALIZED, "This object is already initialized") + CHK_ERR(DDERR_CANNOTATTACHSURFACE, "This surface can not be attached to the requested surface.") + CHK_ERR(DDERR_CANNOTDETACHSURFACE, "This surface can not be detached from the requested surface.") + CHK_ERR(DDERR_CURRENTLYNOTAVAIL, "Support is currently not available.") + CHK_ERR(DDERR_EXCEPTION, "An exception was encountered while performing the requested operation") +// CHK_ERR(DDERR_GENERIC, "DDERR_GENERIC") + CHK_ERR(DDERR_HEIGHTALIGN, "Height of rectangle provided is not a multiple of reqd alignment") + CHK_ERR(DDERR_INCOMPATIBLEPRIMARY, "Unable to match primary surface creation request with existing primary surface.") + CHK_ERR(DDERR_INVALIDCAPS, "One or more of the caps bits passed to the callback are incorrect.") + CHK_ERR(DDERR_INVALIDCLIPLIST, "DirectDraw does not support provided Cliplist.") + CHK_ERR(DDERR_INVALIDMODE, "DirectDraw does not support the requested mode") + CHK_ERR(DDERR_INVALIDOBJECT, "DirectDraw received a pointer that was an invalid DIRECTDRAW object.") +// CHK_ERR(DDERR_INVALIDPARAMS, "DDERR_INVALIDPARAMS") + CHK_ERR(DDERR_INVALIDPIXELFORMAT, "pixel format was invalid as specified") + CHK_ERR(DDERR_INVALIDRECT, "Rectangle provided was invalid.") + CHK_ERR(DDERR_LOCKEDSURFACES, "Operation could not be carried out because one or more surfaces are locked") + CHK_ERR(DDERR_NO3D, "There is no 3D present.") + CHK_ERR(DDERR_NOALPHAHW, "Operation could not be carried out because there is no alpha accleration hardware present or available.") + CHK_ERR(DDERR_NOSTEREOHARDWARE, "Operation could not be carried out because there is no stereo hardware present or available.") + CHK_ERR(DDERR_NOSURFACELEFT, "Operation could not be carried out because there is no hardware present which supports stereo surfaces") + CHK_ERR(DDERR_NOCLIPLIST, "no clip list available") + CHK_ERR(DDERR_NOCOLORCONVHW, "Operation could not be carried out because there is no color conversion hardware present or available.") + CHK_ERR(DDERR_NOCOOPERATIVELEVELSET, "Create function called without DirectDraw object method SetCooperativeLevel being called.") + CHK_ERR(DDERR_NOCOLORKEY, "Surface doesn't currently have a color key") + CHK_ERR(DDERR_NOCOLORKEYHW, "Operation could not be carried out because there is no hardware support of the dest color key.") + CHK_ERR(DDERR_NODIRECTDRAWSUPPORT, "No DirectDraw support possible with current display driver") + CHK_ERR(DDERR_NOEXCLUSIVEMODE, "Operation requires the application to have exclusive mode but the application does not have exclusive mode.") + CHK_ERR(DDERR_NOFLIPHW, "Flipping visible surfaces is not supported.") + CHK_ERR(DDERR_NOGDI, "There is no GDI present.") + CHK_ERR(DDERR_NOMIRRORHW, "Operation could not be carried out because there is no hardware present or available.") + CHK_ERR(DDERR_NOTFOUND, "Requested item was not found") + CHK_ERR(DDERR_NOOVERLAYHW, "Operation could not be carried out because there is no overlay hardware present or available.") + CHK_ERR(DDERR_OVERLAPPINGRECTS, "Operation could not be carried out because the source and destination rectangles are on the same surface and overlap each other.") + CHK_ERR(DDERR_NORASTEROPHW, "Operation could not be carried out because there is no appropriate raster op hardware present or available.") + CHK_ERR(DDERR_NOROTATIONHW, "Operation could not be carried out because there is no rotation hardware present or available.") + CHK_ERR(DDERR_NOSTRETCHHW, "Operation could not be carried out because there is no hardware support for stretching") + CHK_ERR(DDERR_NOT4BITCOLOR, "DirectDrawSurface is not in 4 bit color palette and the requested operation requires 4 bit color palette.") + CHK_ERR(DDERR_NOT4BITCOLORINDEX, "DirectDrawSurface is not in 4 bit color index palette and the requested operation requires 4 bit color index palette.") + CHK_ERR(DDERR_NOT8BITCOLOR, "DirectDraw Surface is not in 8 bit color mode and the requested operation requires 8 bit color.") + CHK_ERR(DDERR_NOTEXTUREHW, "Operation could not be carried out because there is no texture mapping hardware present or available.") + CHK_ERR(DDERR_NOVSYNCHW, "Operation could not be carried out because there is no hardware support for vertical blank synchronized operations.") + CHK_ERR(DDERR_NOZBUFFERHW, "Operation could not be carried out because there is no hardware support for zbuffer blting.") + CHK_ERR(DDERR_NOZOVERLAYHW, "Overlay surfaces could not be z layered based on their BltOrder because the hardware does not support z layering of overlays.") + CHK_ERR(DDERR_OUTOFCAPS, "The hardware needed for the requested operation has already been allocated.") +// CHK_ERR(DDERR_OUTOFMEMORY, "DDERR_OUTOFMEMORY") +// CHK_ERR(DDERR_OUTOFVIDEOMEMORY, "DDERR_OUTOFVIDEOMEMORY") + CHK_ERR(DDERR_OVERLAYCANTCLIP, "hardware does not support clipped overlays") + CHK_ERR(DDERR_OVERLAYCOLORKEYONLYONEACTIVE, "Can only have ony color key active at one time for overlays") + CHK_ERR(DDERR_PALETTEBUSY, "Access to this palette is being refused because the palette is already locked by another thread.") + CHK_ERR(DDERR_COLORKEYNOTSET, "No src color key specified for this operation.") + CHK_ERR(DDERR_SURFACEALREADYATTACHED, "This surface is already attached to the surface it is being attached to.") + CHK_ERR(DDERR_SURFACEALREADYDEPENDENT, "This surface is already a dependency of the surface it is being made a dependency of.") + CHK_ERR(DDERR_SURFACEBUSY, "Access to this surface is being refused because the surface is already locked by another thread.") + CHK_ERR(DDERR_CANTLOCKSURFACE, "Access to this surface is being refused because no driver exists which can supply a pointer to the surface. This is most likely to happen when attempting to lock the primary surface when no DCI provider is present. Will also happen on attempts to lock an optimized surface.") + CHK_ERR(DDERR_SURFACEISOBSCURED, "Access to Surface refused because Surface is obscured.") + CHK_ERR(DDERR_SURFACELOST, "Access to this surface is being refused because the surface is gone. The DIRECTDRAWSURFACE object representing this surface should have Restore called on it.") + CHK_ERR(DDERR_SURFACENOTATTACHED, "The requested surface is not attached.") + CHK_ERR(DDERR_TOOBIGHEIGHT, "Height requested by DirectDraw is too large.") + CHK_ERR(DDERR_TOOBIGSIZE, "Size requested by DirectDraw is too large -- The individual height and width are OK.") + CHK_ERR(DDERR_TOOBIGWIDTH, "Width requested by DirectDraw is too large.") +// CHK_ERR(DDERR_UNSUPPORTED, "DDERR_UNSUPPORTED") + CHK_ERR(DDERR_UNSUPPORTEDFORMAT, "Pixel format requested is unsupported by DirectDraw") + CHK_ERR(DDERR_UNSUPPORTEDMASK, "Bitmask in the pixel format requested is unsupported by DirectDraw") + CHK_ERR(DDERR_INVALIDSTREAM, "The specified stream contains invalid data") + CHK_ERR(DDERR_VERTICALBLANKINPROGRESS, "vertical blank is in progress") + CHK_ERR(DDERR_WASSTILLDRAWING, "Was still drawing") + CHK_ERR(DDERR_DDSCAPSCOMPLEXREQUIRED, "The specified surface type requires specification of the COMPLEX flag") + CHK_ERR(DDERR_XALIGN, "Rectangle provided was not horizontally aligned on reqd. boundary") + CHK_ERR(DDERR_INVALIDDIRECTDRAWGUID, "The GUID passed to DirectDrawCreate is not a valid DirectDraw driver identifier.") + CHK_ERR(DDERR_DIRECTDRAWALREADYCREATED, "A DirectDraw object representing this driver has already been created for this process.") + CHK_ERR(DDERR_NODIRECTDRAWHW, "A hardware only DirectDraw object creation was attempted but the driver did not support any hardware.") + CHK_ERR(DDERR_PRIMARYSURFACEALREADYEXISTS, "this process already has created a primary surface") + CHK_ERR(DDERR_NOEMULATION, "software emulation not available.") + CHK_ERR(DDERR_REGIONTOOSMALL, "region passed to Clipper::GetClipList is too small.") + CHK_ERR(DDERR_CLIPPERISUSINGHWND, "an attempt was made to set a clip list for a clipper objec that is already monitoring an hwnd.") + CHK_ERR(DDERR_NOCLIPPERATTACHED, "No clipper object attached to surface object") + CHK_ERR(DDERR_NOHWND, "Clipper notification requires an HWND or no HWND has previously been set as the CooperativeLevel HWND.") + CHK_ERR(DDERR_HWNDSUBCLASSED, "HWND used by DirectDraw CooperativeLevel has been subclassed, this prevents DirectDraw from restoring state.") + CHK_ERR(DDERR_HWNDALREADYSET, "The CooperativeLevel HWND has already been set. It can not be reset while the process has surfaces or palettes created.") + CHK_ERR(DDERR_NOPALETTEATTACHED, "No palette object attached to this surface.") + CHK_ERR(DDERR_NOPALETTEHW, "No hardware support for 16 or 256 color palettes.") + CHK_ERR(DDERR_BLTFASTCANTCLIP, "If a clipper object is attached to the source surface passed into a BltFast call.") + CHK_ERR(DDERR_NOBLTHW, "No blter.") + CHK_ERR(DDERR_NODDROPSHW, "No DirectDraw ROP hardware.") + CHK_ERR(DDERR_OVERLAYNOTVISIBLE, "returned when GetOverlayPosition is called on a hidden overlay") + CHK_ERR(DDERR_NOOVERLAYDEST, "returned when GetOverlayPosition is called on a overlay that UpdateOverlay has never been called on to establish a destionation.") + CHK_ERR(DDERR_INVALIDPOSITION, "returned when the position of the overlay on the destionation is no longer legal for that destionation.") + CHK_ERR(DDERR_NOTAOVERLAYSURFACE, "returned when an overlay member is called for a non-overlay surface") + CHK_ERR(DDERR_EXCLUSIVEMODEALREADYSET, "An attempt was made to set the cooperative level when it was already set to exclusive.") + CHK_ERR(DDERR_NOTFLIPPABLE, "An attempt has been made to flip a surface that is not flippable.") + CHK_ERR(DDERR_CANTDUPLICATE, "Can't duplicate primary & 3D surfaces, or surfaces that are implicitly created.") + CHK_ERR(DDERR_NOTLOCKED, "Surface was not locked. An attempt to unlock a surface that was not locked at all, or by this process, has been attempted.") + CHK_ERR(DDERR_CANTCREATEDC, "Windows can not create any more DCs, or a DC was requested for a paltte-indexed surface when the surface had no palette AND the display mode was not palette-indexed (in this case DirectDraw cannot select a proper palette into the DC)") + CHK_ERR(DDERR_NODC, "No DC was ever created for this surface.") + CHK_ERR(DDERR_WRONGMODE, "This surface can not be restored because it was created in a different mode.") + CHK_ERR(DDERR_IMPLICITLYCREATED, "This surface can not be restored because it is an implicitly created surface.") + CHK_ERR(DDERR_NOTPALETTIZED, "The surface being used is not a palette-based surface") + CHK_ERR(DDERR_UNSUPPORTEDMODE, "The display is currently in an unsupported mode") + CHK_ERR(DDERR_NOMIPMAPHW, "Operation could not be carried out because there is no mip-map texture mapping hardware present or available.") + CHK_ERR(DDERR_INVALIDSURFACETYPE, "The requested action could not be performed because the surface was of the wrong type.") + CHK_ERR(DDERR_NOOPTIMIZEHW, "Device does not support optimized surfaces, therefore no video memory optimized surfaces") + CHK_ERR(DDERR_NOTLOADED, "Surface is an optimized surface, but has not yet been allocated any memory") + CHK_ERR(DDERR_NOFOCUSWINDOW, "Attempt was made to create or set a device window without first setting the focus window") + CHK_ERR(DDERR_NOTONMIPMAPSUBLEVEL, "Attempt was made to set a palette on a mipmap sublevel") + CHK_ERR(DDERR_DCALREADYCREATED, "A DC has already been returned for this surface. Only one DC can be retrieved per surface.") + CHK_ERR(DDERR_NONONLOCALVIDMEM, "An attempt was made to allocate non-local video memory from a device that does not support non-local video memory.") + CHK_ERR(DDERR_CANTPAGELOCK, "The attempt to page lock a surface failed.") + CHK_ERR(DDERR_CANTPAGEUNLOCK, "The attempt to page unlock a surface failed.") + CHK_ERR(DDERR_NOTPAGELOCKED, "An attempt was made to page unlock a surface with no outstanding page locks.") + CHK_ERR(DDERR_MOREDATA, "There is more data available than the specified buffer size could hold") + CHK_ERR(DDERR_EXPIRED, "The data has expired and is therefore no longer valid.") + CHK_ERR(DDERR_TESTFINISHED, "The mode test has finished executing.") + CHK_ERR(DDERR_NEWMODE, "The mode test has switched to a new mode.") + CHK_ERR(DDERR_D3DNOTINITIALIZED, "D3D has not yet been initialized.") + CHK_ERR(DDERR_VIDEONOTACTIVE, "The video port is not active") + CHK_ERR(DDERR_NOMONITORINFORMATION, "The monitor does not have EDID data.") + CHK_ERR(DDERR_NODRIVERSUPPORT, "The driver does not enumerate display mode refresh rates.") + CHK_ERR(DDERR_DEVICEDOESNTOWNSURFACE, "Surfaces created by one direct draw device cannot be used directly by another direct draw device.") + +// ------------------------------------------------------------- +// d3d10.h error codes +// ------------------------------------------------------------- + CHK_ERR(D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS, "There are too many unique state objects.") + CHK_ERR(D3D10_ERROR_FILE_NOT_FOUND, "File not found") + +// ------------------------------------------------------------- +// dxgi.h error codes +// ------------------------------------------------------------- + CHK_ERR(DXGI_STATUS_OCCLUDED, "The target window or output has been occluded. The application should suspend rendering operations if possible.") + CHK_ERR(DXGI_STATUS_CLIPPED, "Target window is clipped.") + CHK_ERR(DXGI_STATUS_NO_REDIRECTION, "") + CHK_ERR(DXGI_STATUS_NO_DESKTOP_ACCESS, "No access to desktop.") + CHK_ERR(DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE, "") + CHK_ERR(DXGI_STATUS_MODE_CHANGED, "Display mode has changed") + CHK_ERR(DXGI_STATUS_MODE_CHANGE_IN_PROGRESS, "Display mode is changing") + CHK_ERR(DXGI_ERROR_INVALID_CALL, "The application has made an erroneous API call that it had enough information to avoid. This error is intended to denote that the application should be altered to avoid the error. Use of the debug version of the DXGI.DLL will provide run-time debug output with further information.") + CHK_ERR(DXGI_ERROR_NOT_FOUND, "The item requested was not found. For GetPrivateData calls, this means that the specified GUID had not been previously associated with the object.") + CHK_ERR(DXGI_ERROR_MORE_DATA, "The specified size of the destination buffer is too small to hold the requested data.") + CHK_ERR(DXGI_ERROR_UNSUPPORTED, "Unsupported.") + CHK_ERR(DXGI_ERROR_DEVICE_REMOVED, "Hardware device removed.") + CHK_ERR(DXGI_ERROR_DEVICE_HUNG, "Device hung due to badly formed commands.") + CHK_ERR(DXGI_ERROR_DEVICE_RESET, "Device reset due to a badly formed commant.") + CHK_ERR(DXGI_ERROR_WAS_STILL_DRAWING, "Was still drawing.") + CHK_ERR(DXGI_ERROR_FRAME_STATISTICS_DISJOINT, "The requested functionality is not supported by the device or the driver.") + CHK_ERR(DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE, "The requested functionality is not supported by the device or the driver.") + CHK_ERR(DXGI_ERROR_DRIVER_INTERNAL_ERROR, "An internal driver error occurred.") + CHK_ERR(DXGI_ERROR_NONEXCLUSIVE, "The application attempted to perform an operation on an DXGI output that is only legal after the output has been claimed for exclusive owenership.") + CHK_ERR(DXGI_ERROR_NOT_CURRENTLY_AVAILABLE, "The requested functionality is not supported by the device or the driver.") + CHK_ERR(DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED, "Remote desktop client disconnected.") + CHK_ERR(DXGI_ERROR_REMOTE_OUTOFMEMORY, "Remote desktop client is out of memory.") + +// ------------------------------------------------------------- +// d3d11.h error codes +// ------------------------------------------------------------- + CHK_ERR(D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS, "There are too many unique state objects.") + CHK_ERR(D3D11_ERROR_FILE_NOT_FOUND, "File not found") + CHK_ERR(D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS, "Therea are too many unique view objects.") + CHK_ERR(D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD, "Deferred context requires Map-Discard usage pattern") + +// ------------------------------------------------------------- +// Direct2D error codes +// ------------------------------------------------------------- + CHK_ERR(D2DERR_UNSUPPORTED_PIXEL_FORMAT, "The pixel format is not supported.") +// CHK_ERR(D2DERR_INSUFFICIENT_BUFFER, "The supplied buffer was too small to accomodate the data.") + CHK_ERR(D2DERR_WRONG_STATE, "The object was not in the correct state to process the method.") + CHK_ERR(D2DERR_NOT_INITIALIZED, "The object has not yet been initialized.") + CHK_ERR(D2DERR_UNSUPPORTED_OPERATION, "The requested opertion is not supported.") + CHK_ERR(D2DERR_SCANNER_FAILED, "The geomery scanner failed to process the data.") + CHK_ERR(D2DERR_SCREEN_ACCESS_DENIED, "D2D could not access the screen.") + CHK_ERR(D2DERR_DISPLAY_STATE_INVALID, "A valid display state could not be determined.") + CHK_ERR(D2DERR_ZERO_VECTOR, "The supplied vector is zero.") + CHK_ERR(D2DERR_INTERNAL_ERROR, "An internal error (D2D bug) occurred. On checked builds, we would assert.") + CHK_ERR(D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED, "The display format we need to render is not supported by the hardware device.") + CHK_ERR(D2DERR_INVALID_CALL, "A call to this method is invalid.") + CHK_ERR(D2DERR_NO_HARDWARE_DEVICE, "No HW rendering device is available for this operation.") + CHK_ERR(D2DERR_RECREATE_TARGET, "here has been a presentation error that may be recoverable. The caller needs to recreate, rerender the entire frame, and reattempt present.") + CHK_ERR(D2DERR_TOO_MANY_SHADER_ELEMENTS, "Shader construction failed because it was too complex.") + CHK_ERR(D2DERR_SHADER_COMPILE_FAILED, "Shader compilation failed.") + CHK_ERR(D2DERR_MAX_TEXTURE_SIZE_EXCEEDED, "Requested DX surface size exceeded maximum texture size.") + CHK_ERR(D2DERR_UNSUPPORTED_VERSION, "The requested D2D version is not supported.") + CHK_ERR(D2DERR_BAD_NUMBER, "Invalid number.") + CHK_ERR(D2DERR_WRONG_FACTORY, "Objects used together must be created from the same factory instance.") + CHK_ERR(D2DERR_LAYER_ALREADY_IN_USE, "A layer resource can only be in use once at any point in time.") + CHK_ERR(D2DERR_POP_CALL_DID_NOT_MATCH_PUSH, "The pop call did not match the corresponding push call") +// CHK_ERR(D2DERR_WRONG_RESOURCE_DOMAIN, "The resource was realized on the wrong render target") + CHK_ERR(D2DERR_PUSH_POP_UNBALANCED, "The push and pop calls were unbalanced") + CHK_ERR(D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT, "Attempt to copy from a render target while a layer or clip rect is applied") + CHK_ERR(D2DERR_INCOMPATIBLE_BRUSH_TYPES, "The brush types are incompatible for the call.") + CHK_ERR(D2DERR_WIN32_ERROR, "An unknown win32 failure occurred.") + CHK_ERR(D2DERR_TARGET_NOT_GDI_COMPATIBLE, "The render target is not compatible with GDI") + CHK_ERR(D2DERR_TEXT_EFFECT_IS_WRONG_TYPE, "A text client drawing effect object is of the wrong type") + CHK_ERR(D2DERR_TEXT_RENDERER_NOT_RELEASED, "The application is holding a reference to the IDWriteTextRenderer interface after the corresponding DrawText or DrawTextLayout call has returned. The IDWriteTextRenderer instance will be zombied.") +// CHK_ERR(D2DERR_EXCEEDS_MAX_BITMAP_SIZE, "The requested size is larger than the guaranteed supported texture size.") + +// ------------------------------------------------------------- +// DirectWrite error codes +// ------------------------------------------------------------- + CHK_ERR(DWRITE_E_FILEFORMAT, "Indicates an error in an input file such as a font file.") + CHK_ERR(DWRITE_E_UNEXPECTED, "Indicates an error originating in DirectWrite code, which is not expected to occur but is safe to recover from.") + CHK_ERR(DWRITE_E_NOFONT, "Indicates the specified font does not exist.") + CHK_ERR(DWRITE_E_FILENOTFOUND, "A font file could not be opened because the file, directory, network location, drive, or other storage location does not exist or is unavailable.") + CHK_ERR(DWRITE_E_FILEACCESS, "A font file exists but could not be opened due to access denied, sharing violation, or similar error.") + CHK_ERR(DWRITE_E_FONTCOLLECTIONOBSOLETE, "A font collection is obsolete due to changes in the system.") + CHK_ERR(DWRITE_E_ALREADYREGISTERED, "The given interface is already registered.") + +// ------------------------------------------------------------- +// WIC error codes +// ------------------------------------------------------------- + CHK_ERR(WINCODEC_ERR_WRONGSTATE, "WIC object in incorrect state.") + CHK_ERR(WINCODEC_ERR_VALUEOUTOFRANGE, "WIC Value out of range.") + CHK_ERR(WINCODEC_ERR_UNKNOWNIMAGEFORMAT, "Encountered unexpected value or setting in WIC image format.") + CHK_ERR(WINCODEC_ERR_UNSUPPORTEDVERSION, "Unsupported WINCODEC_SD_VERSION passed to WIC factory.") + CHK_ERR(WINCODEC_ERR_NOTINITIALIZED, "WIC component not initialized.") + CHK_ERR(WINCODEC_ERR_ALREADYLOCKED, "WIC bitmap object already locked.") + CHK_ERR(WINCODEC_ERR_PROPERTYNOTFOUND, "WIC property not found.") + CHK_ERR(WINCODEC_ERR_PROPERTYNOTSUPPORTED, "WIC property not supported.") + CHK_ERR(WINCODEC_ERR_PROPERTYSIZE, "Invalid property size") + CHK_ERRA(WINCODEC_ERR_CODECPRESENT) // not currently used by WIC + CHK_ERRA(WINCODEC_ERR_CODECNOTHUMBNAIL) // not currently used by WIC + CHK_ERR(WINCODEC_ERR_PALETTEUNAVAILABLE, "Required palette data not available.") + CHK_ERR(WINCODEC_ERR_CODECTOOMANYSCANLINES, "More scanlines requested than are available in WIC bitmap.") + CHK_ERR(WINCODEC_ERR_INTERNALERROR, "Unexpected internal error in WIC.") + CHK_ERR(WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS, "Source WIC rectangle does not match bitmap dimensions.") + CHK_ERR(WINCODEC_ERR_COMPONENTNOTFOUND, "WIC component not found.") + CHK_ERR(WINCODEC_ERR_IMAGESIZEOUTOFRANGE, "Image size beyond expected boundaries for WIC codec." ) + CHK_ERR(WINCODEC_ERR_TOOMUCHMETADATA, "Image metadata size beyond expected boundaries for WIC codec.") + CHK_ERR(WINCODEC_ERR_BADIMAGE, "WIC image is corrupted.") + CHK_ERR(WINCODEC_ERR_BADHEADER, "Invalid header found in WIC image.") + CHK_ERR(WINCODEC_ERR_FRAMEMISSING, "Expected bitmap frame data not found in WIC image." ) + CHK_ERR(WINCODEC_ERR_BADMETADATAHEADER, "Invalid metadata header found in WIC image.") + CHK_ERR(WINCODEC_ERR_BADSTREAMDATA, "Invalid stream data found in WIC image.") + CHK_ERR(WINCODEC_ERR_STREAMWRITE, "WIC operation on write stream failed.") + CHK_ERR(WINCODEC_ERR_STREAMREAD, "WIC operation on read stream failed.") + CHK_ERR(WINCODEC_ERR_STREAMNOTAVAILABLE, "Required stream is not available." ) +// CHK_ERRA(WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT) + CHK_ERR(WINCODEC_ERR_UNSUPPORTEDOPERATION, "This operation is not supported by WIC." ) + CHK_ERR(WINCODEC_ERR_INVALIDREGISTRATION, "Error occurred reading WIC codec registry keys.") + CHK_ERR(WINCODEC_ERR_COMPONENTINITIALIZEFAILURE, "Failed initializing WIC codec.") + CHK_ERR(WINCODEC_ERR_INSUFFICIENTBUFFER, "Not enough buffer space available for WIC operation.") + CHK_ERR(WINCODEC_ERR_DUPLICATEMETADATAPRESENT, "Duplicate metadata detected in WIC image.") + CHK_ERR(WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE, "Unexpected property type in WIC image.") + CHK_ERR(WINCODEC_ERR_UNEXPECTEDSIZE, "Unexpected value size in WIC metadata.") + CHK_ERR(WINCODEC_ERR_INVALIDQUERYREQUEST, "Invalid metadata query.") + CHK_ERR(WINCODEC_ERR_UNEXPECTEDMETADATATYPE, "Unexpected metadata type encountered in WIC image.") + CHK_ERR(WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT, "Operation only valid on meatadata root.") + CHK_ERR(WINCODEC_ERR_INVALIDQUERYCHARACTER, "Invalid character in WIC metadata query.") + CHK_ERR(WINCODEC_ERR_WIN32ERROR, "General Win32 error encountered during WIC operation.") + CHK_ERR(WINCODEC_ERR_INVALIDPROGRESSIVELEVEL, "Invalid level for progressive WIC image decode.") + +// ------------------------------------------------------------- +// DXUT error codes +// ------------------------------------------------------------- + CHK_ERR(DXUTERR_NODIRECT3D, "Could not initialize Direct3D.") + CHK_ERR(DXUTERR_NOCOMPATIBLEDEVICES, "No device could be found with the specified device settings.") + CHK_ERR(DXUTERR_MEDIANOTFOUND, "A media file could not be found.") + CHK_ERR(DXUTERR_NONZEROREFCOUNT, "The device interface has a non-zero reference count, meaning that some objects were not released.") + CHK_ERR(DXUTERR_CREATINGDEVICE, "An error occurred when attempting to create a device.") + CHK_ERR(DXUTERR_RESETTINGDEVICE, "An error occurred when attempting to reset a device.") + CHK_ERR(DXUTERR_CREATINGDEVICEOBJECTS, "An error occurred in the device create callback function.") + CHK_ERR(DXUTERR_RESETTINGDEVICEOBJECTS, "An error occurred in the device reset callback function.") + CHK_ERR(DXUTERR_INCORRECTVERSION, "Incorrect version of Direct3D or D3DX.") + CHK_ERR(DXUTERR_DEVICEREMOVED, "The device was removed.") + +// ------------------------------------------------------------- +// xaudio2.h error codes +// ------------------------------------------------------------- + CHK_ERR(XAUDIO2_E_INVALID_CALL, "Invalid XAudio2 API call or arguments") + CHK_ERR(XAUDIO2_E_XMA_DECODER_ERROR, "Hardware XMA decoder error") + CHK_ERR(XAUDIO2_E_XAPO_CREATION_FAILED, "Failed to create an audio effect") + CHK_ERR(XAUDIO2_E_DEVICE_INVALIDATED, "Device invalidated (unplugged, disabled, etc)") + +// ------------------------------------------------------------- +// xapo.h error codes +// ------------------------------------------------------------- + CHK_ERR(XAPO_E_FORMAT_UNSUPPORTED, "Requested audio format unsupported.") + + default: wcscpy_s( desc, count, L"Unknown error." ); break; + } +} + +//----------------------------------------------------------------------------- +HRESULT WINAPI DXTraceW( _In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, + _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox ) +{ + WCHAR strBufferFile[MAX_PATH]; + WCHAR strBufferLine[128]; + WCHAR strBufferError[256]; + WCHAR strBufferMsg[1024]; + WCHAR strBuffer[BUFFER_SIZE]; + + swprintf_s( strBufferLine, 128, L"%lu", dwLine ); + if( strFile ) + { + swprintf_s( strBuffer, BUFFER_SIZE, L"%ls(%ls): ", strFile, strBufferLine ); + OutputDebugStringW( strBuffer ); + } + + size_t nMsgLen = (strMsg) ? wcsnlen_s( strMsg, 1024 ) : 0; + if( nMsgLen > 0 ) + { + OutputDebugStringW( strMsg ); + OutputDebugStringW( L" " ); + } + + swprintf_s( strBufferError, 256, L"%ls (0x%0.8x)", DXGetErrorStringW(hr), hr ); + swprintf_s( strBuffer, BUFFER_SIZE, L"hr=%ls", strBufferError ); + OutputDebugStringW( strBuffer ); + + OutputDebugStringW( L"\n" ); + + if( bPopMsgBox ) + { + wcscpy_s( strBufferFile, MAX_PATH, L"" ); + if( strFile ) + wcscpy_s( strBufferFile, MAX_PATH, strFile ); + + wcscpy_s( strBufferMsg, 1024, L"" ); + if( nMsgLen > 0 ) + swprintf_s( strBufferMsg, 1024, L"Calling: %ls\n", strMsg ); + + swprintf_s( strBuffer, BUFFER_SIZE, L"File: %ls\nLine: %ls\nError Code: %ls\n%lsDo you want to debug the application?", + strBufferFile, strBufferLine, strBufferError, strBufferMsg ); + + int nResult = MessageBoxW( GetForegroundWindow(), strBuffer, L"Unexpected error encountered", MB_YESNO | MB_ICONERROR ); + if( nResult == IDYES ) + DebugBreak(); + } + + return hr; +} \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Core/dxerr.h b/FriedLiver/Source/DXUT/Core/dxerr.h new file mode 100644 index 00000000..d1c55cd3 --- /dev/null +++ b/FriedLiver/Source/DXUT/Core/dxerr.h @@ -0,0 +1,72 @@ +//-------------------------------------------------------------------------------------- +// File: DXErr.h +// +// DirectX Error Library +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +//-------------------------------------------------------------------------------------- + +// This version only supports UNICODE. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//-------------------------------------------------------------------------------------- +// DXGetErrorString +//-------------------------------------------------------------------------------------- +const WCHAR* WINAPI DXGetErrorStringW( _In_ HRESULT hr ); + +#define DXGetErrorString DXGetErrorStringW + +//-------------------------------------------------------------------------------------- +// DXGetErrorDescription has to be modified to return a copy in a buffer rather than +// the original static string. +//-------------------------------------------------------------------------------------- +void WINAPI DXGetErrorDescriptionW( _In_ HRESULT hr, _Out_cap_(count) WCHAR* desc, _In_ size_t count ); + +#define DXGetErrorDescription DXGetErrorDescriptionW + +//-------------------------------------------------------------------------------------- +// DXTrace +// +// Desc: Outputs a formatted error message to the debug stream +// +// Args: WCHAR* strFile The current file, typically passed in using the +// __FILEW__ macro. +// DWORD dwLine The current line number, typically passed in using the +// __LINE__ macro. +// HRESULT hr An HRESULT that will be traced to the debug stream. +// CHAR* strMsg A string that will be traced to the debug stream (may be NULL) +// BOOL bPopMsgBox If TRUE, then a message box will popup also containing the passed info. +// +// Return: The hr that was passed in. +//-------------------------------------------------------------------------------------- +HRESULT WINAPI DXTraceW( _In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox ); + +#define DXTrace DXTraceW + +//-------------------------------------------------------------------------------------- +// +// Helper macros +// +//-------------------------------------------------------------------------------------- +#if defined(DEBUG) || defined(_DEBUG) +#define DXTRACE_MSG(str) DXTrace( __FILEW__, (DWORD)__LINE__, 0, str, false ) +#define DXTRACE_ERR(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, false ) +#define DXTRACE_ERR_MSGBOX(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, true ) +#else +#define DXTRACE_MSG(str) (0L) +#define DXTRACE_ERR(str,hr) (hr) +#define DXTRACE_ERR_MSGBOX(str,hr) (hr) +#endif + +#ifdef __cplusplus +} +#endif //__cplusplus diff --git a/FriedLiver/Source/DXUT/Media/UI/Font.dds b/FriedLiver/Source/DXUT/Media/UI/Font.dds new file mode 100644 index 00000000..37514f5b Binary files /dev/null and b/FriedLiver/Source/DXUT/Media/UI/Font.dds differ diff --git a/FriedLiver/Source/DXUT/Media/UI/dxutcontrols.dds b/FriedLiver/Source/DXUT/Media/UI/dxutcontrols.dds new file mode 100644 index 00000000..b5f52e10 Binary files /dev/null and b/FriedLiver/Source/DXUT/Media/UI/dxutcontrols.dds differ diff --git a/FriedLiver/Source/DXUT/Optional/DXUTLockFreePipe.h b/FriedLiver/Source/DXUT/Optional/DXUTLockFreePipe.h index ed107478..20ee90c5 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTLockFreePipe.h +++ b/FriedLiver/Source/DXUT/Optional/DXUTLockFreePipe.h @@ -2,40 +2,35 @@ // DXUTLockFreePipe.h // // See the "Lockless Programming Considerations for Xbox 360 and Microsoft Windows" -// article in the DirectX SDK for more details. +// article for more details. // -// http://msdn2.microsoft.com/en-us/library/bb310595.aspx +// http://msdn.microsoft.com/en-us/library/ee418650.aspx // -// XNA Developer Connection -// Copyright (C) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once #include +#include + +#pragma pack(push) +#pragma pack(8) +#include +#pragma pack (pop) + +extern "C" + void _ReadWriteBarrier(); +#pragma intrinsic(_ReadWriteBarrier) -#ifdef _XBOX_VER - // Prevent the CPU from rearranging loads - // and stores, sufficiently for read-acquire - // and write-release. - #define DXUTImportBarrier __lwsync - #define DXUTExportBarrier __lwsync -#else - #pragma pack(push) - #pragma pack(8) - #include - #pragma pack (pop) - - extern "C" - void _ReadWriteBarrier(); - #pragma intrinsic(_ReadWriteBarrier) - - // Prevent the compiler from rearranging loads - // and stores, sufficiently for read-acquire - // and write-release. This is sufficient on - // x86 and x64. - #define DXUTImportBarrier _ReadWriteBarrier - #define DXUTExportBarrier _ReadWriteBarrier -#endif +// Prevent the compiler from rearranging loads +// and stores, sufficiently for read-acquire +// and write-release. This is sufficient on +// x86 and x64. +#define DXUTImportBarrier _ReadWriteBarrier +#define DXUTExportBarrier _ReadWriteBarrier // // Pipe class designed for use by at most two threads: one reader, one writer. @@ -63,7 +58,7 @@ template class DXUTLockFreePipe return m_writeOffset - m_readOffset; } - bool __forceinline Read( void* pvDest, unsigned long cbDest ) + bool __forceinline Read( _Out_writes_(cbDest) void* pvDest, _In_ unsigned long cbDest ) { // Store the read and write offsets into local variables--this is // essentially a snapshot of their values so that they stay constant @@ -118,7 +113,7 @@ template class DXUTLockFreePipe // then the previous comparison would have failed since that would imply // that there were less than cbDest bytes available to read. // - unsigned long cbTailBytes = min( bytesLeft, c_cbBufferSize - actualReadOffset ); + unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualReadOffset ); memcpy( pbDest, m_pbBuffer + actualReadOffset, cbTailBytes ); bytesLeft -= cbTailBytes; @@ -148,7 +143,7 @@ template class DXUTLockFreePipe return true; } - bool __forceinline Write( const void* pvSrc, unsigned long cbSrc ) + bool __forceinline Write( _In_reads_(cbSrc) const void* pvSrc, _In_ unsigned long cbSrc ) { // Reading the read offset here has the same caveats as reading // the write offset had in the Read() function above. @@ -179,7 +174,7 @@ template class DXUTLockFreePipe // See the explanation in the Read() function as to why we don't // explicitly check against the read offset here. - unsigned long cbTailBytes = min( bytesLeft, c_cbBufferSize - actualWriteOffset ); + unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualWriteOffset ); memcpy( m_pbBuffer + actualWriteOffset, pbSrc, cbTailBytes ); bytesLeft -= cbTailBytes; @@ -208,9 +203,9 @@ template class DXUTLockFreePipe private: // Values derived from the buffer size template parameter // - const static BYTE c_cbBufferSizeLog2 = min( cbBufferSizeLog2, 31 ); - const static DWORD c_cbBufferSize = ( 1 << c_cbBufferSizeLog2 ); - const static DWORD c_sizeMask = c_cbBufferSize - 1; + static const BYTE c_cbBufferSizeLog2 = __min( cbBufferSizeLog2, 31 ); + static const DWORD c_cbBufferSize = ( 1 << c_cbBufferSizeLog2 ); + static const DWORD c_sizeMask = c_cbBufferSize - 1; // Leave these private and undefined to prevent their use DXUTLockFreePipe( const DXUTLockFreePipe& ); diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015.vcxproj new file mode 100644 index 00000000..b14c76cf --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015.vcxproj @@ -0,0 +1,339 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + Bin\Desktop_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015.vcxproj.filters new file mode 100644 index 00000000..1bdbaf91 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015.vcxproj.filters @@ -0,0 +1,32 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015_Win10.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015_Win10.vcxproj new file mode 100644 index 00000000..79dff5a9 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015_Win10.vcxproj @@ -0,0 +1,340 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + 10.0.14393.0 + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015_Win10.vcxproj.filters new file mode 100644 index 00000000..1bdbaf91 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2015_Win10.vcxproj.filters @@ -0,0 +1,32 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2017_Win10.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2017_Win10.vcxproj new file mode 100644 index 00000000..99ca92bf --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2017_Win10.vcxproj @@ -0,0 +1,352 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + 10.0.17763.0 + + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2017_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2017_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2017_Win10.vcxproj.filters new file mode 100644 index 00000000..1bdbaf91 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2017_Win10.vcxproj.filters @@ -0,0 +1,32 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2019_Win10.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2019_Win10.vcxproj new file mode 100644 index 00000000..6c295b42 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2019_Win10.vcxproj @@ -0,0 +1,352 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + 10.0 + + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + Bin\Desktop_2019_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;_WIN32_WINNT=0x0600;_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_2019_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2019_Win10.vcxproj.filters new file mode 100644 index 00000000..1bdbaf91 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_2019_Win10.vcxproj.filters @@ -0,0 +1,32 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015.vcxproj new file mode 100644 index 00000000..0560c96f --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015.vcxproj @@ -0,0 +1,337 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015.vcxproj.filters new file mode 100644 index 00000000..b959c9a4 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015.vcxproj.filters @@ -0,0 +1,30 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015_Win10.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015_Win10.vcxproj new file mode 100644 index 00000000..71ff1066 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015_Win10.vcxproj @@ -0,0 +1,338 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + 10.0.14393.0 + + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2015_Win10\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_3;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015_Win10.vcxproj.filters new file mode 100644 index 00000000..b959c9a4 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2015_Win10.vcxproj.filters @@ -0,0 +1,30 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2017_Win10.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2017_Win10.vcxproj new file mode 100644 index 00000000..3948895f --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2017_Win10.vcxproj @@ -0,0 +1,350 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + 10.0.17763.0 + + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + StaticLibrary + true + Unicode + v141 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2017\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2017_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2017_Win10.vcxproj.filters new file mode 100644 index 00000000..b959c9a4 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2017_Win10.vcxproj.filters @@ -0,0 +1,30 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2019_Win10.vcxproj b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2019_Win10.vcxproj new file mode 100644 index 00000000..db49a77b --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2019_Win10.vcxproj @@ -0,0 +1,350 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Profile + Win32 + + + Profile + x64 + + + Release + Win32 + + + Release + x64 + + + + DXUTOpt + {61B333C2-C4F7-4cc1-A9BF-83F6D95588EB} + DXUTOpt + Win32Proj + 10.0 + + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + StaticLibrary + true + Unicode + v142 + + + + + + + + + + + + + + + + + + + + + + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUTOpt + + + true + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + Bin\DirectXTK_2019\$(Platform)\$(Configuration)\ + DXUTOpt + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + Disabled + MultiThreadedDebugDLL + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;_DEBUG;DEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + Windows + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + StreamingSIMDExtensions2 + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + Level4 + MaxSpeed + Fast + ..\..\DirectXTK\Inc;..\Core\;%(AdditionalIncludeDirectories) + /Zc:__cplusplus %(AdditionalOptions) + WIN32;NDEBUG;PROFILE;_WINDOWS;_LIB;USE_DIRECT3D11_4;USE_DIRECTXTK;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + Use + DXUT.h + true + + + true + Windows + true + true + + + false + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2019_Win10.vcxproj.filters b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2019_Win10.vcxproj.filters new file mode 100644 index 00000000..b959c9a4 --- /dev/null +++ b/FriedLiver/Source/DXUT/Optional/DXUTOpt_DirectXTK_2019_Win10.vcxproj.filters @@ -0,0 +1,30 @@ + + + + +{8e114980-c1a3-4ada-ad7c-83caadf5daeb} +rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FriedLiver/Source/DXUT/Optional/DXUTcamera.cpp b/FriedLiver/Source/DXUT/Optional/DXUTcamera.cpp index 691d5283..fe2f2ec0 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTcamera.cpp +++ b/FriedLiver/Source/DXUT/Optional/DXUTcamera.cpp @@ -1,21 +1,40 @@ //-------------------------------------------------------------------------------------- // File: DXUTcamera.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTres.h" -#undef min // use __min instead -#undef max // use __max instead + +using namespace DirectX; + +//====================================================================================== +// CD3DArcBall +//====================================================================================== //-------------------------------------------------------------------------------------- -CD3DArcBall::CD3DArcBall() +CD3DArcBall::CD3DArcBall() noexcept : + m_mRotation{}, + m_mTranslation{}, + m_mTranslationDelta{}, + m_Offset{ 0, 0 }, + m_nWidth(0), + m_nHeight(0), + m_vCenter{}, + m_fRadius(0), + m_fRadiusTranslation(0), + m_qDown{}, + m_qNow{}, + m_bDrag(false), + m_ptLastMouse{}, + m_vDownPt( 0, 0, 0 ), + m_vCurrentPt( 0, 0, 0 ) { Reset(); - m_vDownPt = D3DXVECTOR3( 0, 0, 0 ); - m_vCurrentPt = D3DXVECTOR3( 0, 0, 0 ); - m_Offset.x = m_Offset.y = 0; RECT rc; GetClientRect( GetForegroundWindow(), &rc ); @@ -23,66 +42,26 @@ CD3DArcBall::CD3DArcBall() } - - - //-------------------------------------------------------------------------------------- void CD3DArcBall::Reset() { - D3DXQuaternionIdentity( &m_qDown ); - D3DXQuaternionIdentity( &m_qNow ); - D3DXMatrixIdentity( &m_mRotation ); - D3DXMatrixIdentity( &m_mTranslation ); - D3DXMatrixIdentity( &m_mTranslationDelta ); - m_bDrag = FALSE; - m_fRadiusTranslation = 1.0f; - m_fRadius = 1.0f; -} - - - - -//-------------------------------------------------------------------------------------- -D3DXVECTOR3 CD3DArcBall::ScreenToVector( float fScreenPtX, float fScreenPtY ) -{ - // Scale to screen - FLOAT x = -( fScreenPtX - m_Offset.x - m_nWidth / 2 ) / ( m_fRadius * m_nWidth / 2 ); - FLOAT y = ( fScreenPtY - m_Offset.y - m_nHeight / 2 ) / ( m_fRadius * m_nHeight / 2 ); - - FLOAT z = 0.0f; - FLOAT mag = x * x + y * y; - - if( mag > 1.0f ) - { - FLOAT scale = 1.0f / sqrtf( mag ); - x *= scale; - y *= scale; - } - else - z = sqrtf( 1.0f - mag ); - - // Return vector - return D3DXVECTOR3( x, y, z ); -} + XMVECTOR qid = XMQuaternionIdentity(); + XMStoreFloat4( &m_qDown, qid ); + XMStoreFloat4( &m_qNow, qid ); + XMMATRIX id = XMMatrixIdentity(); + XMStoreFloat4x4( &m_mRotation, id ); + XMStoreFloat4x4( &m_mTranslation, id ); + XMStoreFloat4x4( &m_mTranslationDelta, id ); - - -//-------------------------------------------------------------------------------------- -D3DXQUATERNION CD3DArcBall::QuatFromBallPoints( const D3DXVECTOR3& vFrom, const D3DXVECTOR3& vTo ) -{ - D3DXVECTOR3 vPart; - float fDot = D3DXVec3Dot( &vFrom, &vTo ); - D3DXVec3Cross( &vPart, &vFrom, &vTo ); - - return D3DXQUATERNION( vPart.x, vPart.y, vPart.z, fDot ); + m_bDrag = false; + m_fRadiusTranslation = 1.0f; + m_fRadius = 1.0f; } - - //-------------------------------------------------------------------------------------- -void CD3DArcBall::OnBegin( int nX, int nY ) +void CD3DArcBall::OnBegin( _In_ int nX, _In_ int nY ) { // Only enter the drag state if the click falls // inside the click rectangle. @@ -93,24 +72,27 @@ void CD3DArcBall::OnBegin( int nX, int nY ) { m_bDrag = true; m_qDown = m_qNow; - m_vDownPt = ScreenToVector( ( float )nX, ( float )nY ); + XMVECTOR v = ScreenToVector( float(nX), float(nY) ); + XMStoreFloat3( &m_vDownPt, v ); } } - - //-------------------------------------------------------------------------------------- -void CD3DArcBall::OnMove( int nX, int nY ) +void CD3DArcBall::OnMove( _In_ int nX, _In_ int nY ) { if( m_bDrag ) { - m_vCurrentPt = ScreenToVector( ( float )nX, ( float )nY ); - m_qNow = m_qDown * QuatFromBallPoints( m_vDownPt, m_vCurrentPt ); - } -} + XMVECTOR curr = ScreenToVector( ( float )nX, ( float )nY ); + XMStoreFloat3( &m_vCurrentPt, curr ); + XMVECTOR down = XMLoadFloat3( &m_vDownPt ); + XMVECTOR qdown = XMLoadFloat4( &m_qDown ); + XMVECTOR result = XMQuaternionMultiply( qdown, QuatFromBallPoints( down, curr ) ); + XMStoreFloat4( &m_qNow, result ); + } +} //-------------------------------------------------------------------------------------- @@ -120,11 +102,8 @@ void CD3DArcBall::OnEnd() } - - -//-------------------------------------------------------------------------------------- -// Desc: //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CD3DArcBall::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { // Current mouse position @@ -174,20 +153,25 @@ LRESULT CD3DArcBall::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM else if( ( MK_RBUTTON & wParam ) || ( MK_MBUTTON & wParam ) ) { // Normalize based on size of window and bounding sphere radius - FLOAT fDeltaX = ( m_ptLastMouse.x - iMouseX ) * m_fRadiusTranslation / m_nWidth; - FLOAT fDeltaY = ( m_ptLastMouse.y - iMouseY ) * m_fRadiusTranslation / m_nHeight; + float fDeltaX = ( m_ptLastMouse.x - iMouseX ) * m_fRadiusTranslation / m_nWidth; + float fDeltaY = ( m_ptLastMouse.y - iMouseY ) * m_fRadiusTranslation / m_nHeight; + XMMATRIX mTranslationDelta; + XMMATRIX mTranslation = XMLoadFloat4x4( &m_mTranslation ); if( wParam & MK_RBUTTON ) { - D3DXMatrixTranslation( &m_mTranslationDelta, -2 * fDeltaX, 2 * fDeltaY, 0.0f ); - D3DXMatrixMultiply( &m_mTranslation, &m_mTranslation, &m_mTranslationDelta ); + mTranslationDelta = XMMatrixTranslation( -2 * fDeltaX, 2 * fDeltaY, 0.0f ); + mTranslation = XMMatrixMultiply( mTranslation, mTranslationDelta ); } else // wParam & MK_MBUTTON { - D3DXMatrixTranslation( &m_mTranslationDelta, 0.0f, 0.0f, 5 * fDeltaY ); - D3DXMatrixMultiply( &m_mTranslation, &m_mTranslation, &m_mTranslationDelta ); + mTranslationDelta = XMMatrixTranslation( 0.0f, 0.0f, 5 * fDeltaY ); + mTranslation = XMMatrixMultiply( mTranslation, mTranslationDelta ); } + XMStoreFloat4x4( &m_mTranslationDelta, mTranslationDelta ); + XMStoreFloat4x4( &m_mTranslation, mTranslation ); + // Store mouse coordinate m_ptLastMouse.x = iMouseX; m_ptLastMouse.y = iMouseY; @@ -199,106 +183,105 @@ LRESULT CD3DArcBall::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM } - +//====================================================================================== +// CBaseCamera +//====================================================================================== //-------------------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------------------- -CBaseCamera::CBaseCamera() +CBaseCamera::CBaseCamera() noexcept : + m_mView{}, + m_mProj{}, + m_GamePad{}, + m_vGamePadLeftThumb(0,0,0), + m_vGamePadRightThumb(0,0,0), + m_GamePadLastActive{}, + m_cKeysDown(0), + m_aKeys{}, + m_vKeyboardDirection(0,0,0), + m_ptLastMousePosition{ 0, 0 }, + m_nCurrentButtonMask(0), + m_nMouseWheelDelta(0), + m_vMouseDelta(0, 0), + m_fFramesToSmoothMouseData(2.0f), + m_vDefaultEye(0, 0, 0), + m_vDefaultLookAt(0, 0, 0), + m_vEye(0, 0, 0), + m_vLookAt(0, 0, 0), + m_fCameraYawAngle(0.0f), + m_fCameraPitchAngle(0.0f), + m_rcDrag{}, + m_vVelocity(0, 0, 0), + m_vVelocityDrag(0, 0, 0), + m_fDragTimer(0.0f), + m_fTotalDragTimeToZero(0.25), + m_vRotVelocity(0, 0), + m_fFOV(0), + m_fAspect(0), + m_fNearPlane(0), + m_fFarPlane(1), + m_fRotationScaler(0.01f), + m_fMoveScaler(5.0f), + m_bMouseLButtonDown(false), + m_bMouseMButtonDown(false), + m_bMouseRButtonDown(false), + m_bMovementDrag(false), + m_bInvertPitch(false), + m_bEnablePositionMovement(true), + m_bEnableYAxisMovement(true), + m_bClipToBoundary(false), + m_bResetCursorAfterMove(false), + m_vMinBoundary(-1, -1, -1), + m_vMaxBoundary(1, 1, 1) { - m_cKeysDown = 0; - ZeroMemory( m_aKeys, sizeof( BYTE ) * CAM_MAX_KEYS ); - ZeroMemory( m_GamePad, sizeof( DXUT_GAMEPAD ) * DXUT_MAX_CONTROLLERS ); - - // Set attributes for the view matrix - D3DXVECTOR3 vEyePt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); - D3DXVECTOR3 vLookatPt = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); - // Setup the view matrix - SetViewParams( &vEyePt, &vLookatPt ); + SetViewParams( g_XMZero, g_XMIdentityR2 ); // Setup the projection matrix - SetProjParams( D3DX_PI / 4, 1.0f, 1.0f, 1000.0f ); + SetProjParams( XM_PI / 4, 1.0f, 1.0f, 1000.0f ); GetCursorPos( &m_ptLastMousePosition ); - m_bMouseLButtonDown = false; - m_bMouseMButtonDown = false; - m_bMouseRButtonDown = false; - m_nCurrentButtonMask = 0; - m_nMouseWheelDelta = 0; - - m_fCameraYawAngle = 0.0f; - m_fCameraPitchAngle = 0.0f; - + SetRect( &m_rcDrag, LONG_MIN, LONG_MIN, LONG_MAX, LONG_MAX ); - m_vVelocity = D3DXVECTOR3( 0, 0, 0 ); - m_bMovementDrag = false; - m_vVelocityDrag = D3DXVECTOR3( 0, 0, 0 ); - m_fDragTimer = 0.0f; - m_fTotalDragTimeToZero = 0.25; - m_vRotVelocity = D3DXVECTOR2( 0, 0 ); - - m_fRotationScaler = 0.01f; - m_fMoveScaler = 5.0f; - - m_bInvertPitch = false; - m_bEnableYAxisMovement = true; - m_bEnablePositionMovement = true; - - m_vMouseDelta = D3DXVECTOR2( 0, 0 ); - m_fFramesToSmoothMouseData = 2.0f; - - m_bClipToBoundary = false; - m_vMinBoundary = D3DXVECTOR3( -1, -1, -1 ); - m_vMaxBoundary = D3DXVECTOR3( 1, 1, 1 ); - - m_bResetCursorAfterMove = false; - - m_vMyKeyboardDirection.x = m_vMyKeyboardDirection.y = m_vMyKeyboardDirection.z = 0.0f; - D3DXMatrixIdentity(&m_mShift); } //-------------------------------------------------------------------------------------- // Client can call this to change the position and direction of camera //-------------------------------------------------------------------------------------- -VOID CBaseCamera::SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ) +_Use_decl_annotations_ +void CBaseCamera::SetViewParams( FXMVECTOR vEyePt, FXMVECTOR vLookatPt ) { - if( NULL == pvEyePt || NULL == pvLookatPt ) - return; + XMStoreFloat3( &m_vEye, vEyePt ); + XMStoreFloat3( &m_vDefaultEye, vEyePt ); - m_vDefaultEye = m_vEye = *pvEyePt; - m_vDefaultLookAt = m_vLookAt = *pvLookatPt; + XMStoreFloat3( &m_vLookAt, vLookatPt ); + XMStoreFloat3( &m_vDefaultLookAt , vLookatPt ); // Calc the view matrix - D3DXVECTOR3 vUp( 0,1,0 ); - D3DXMatrixLookAtLH( &m_mView, pvEyePt, pvLookatPt, &vUp ); + XMMATRIX mView = XMMatrixLookAtLH( vEyePt, vLookatPt, g_XMIdentityR1 ); + XMStoreFloat4x4( &m_mView, mView ); - D3DXMATRIX mInvView; - D3DXMatrixInverse( &mInvView, NULL, &m_mView ); + XMMATRIX mInvView = XMMatrixInverse( nullptr, mView ); // The axis basis vectors and camera position are stored inside the // position matrix in the 4 rows of the camera's world matrix. // To figure out the yaw/pitch of the camera, we just need the Z basis vector - D3DXVECTOR3* pZBasis = ( D3DXVECTOR3* )&mInvView._31; - - m_fCameraYawAngle = atan2f( pZBasis->x, pZBasis->z ); - float fLen = sqrtf( pZBasis->z * pZBasis->z + pZBasis->x * pZBasis->x ); - m_fCameraPitchAngle = -atan2f( pZBasis->y, fLen ); + DirectX::XMFLOAT3 zBasis; + XMStoreFloat3( &zBasis, mInvView.r[2] ); - //by simanies initializes the translation parameters - m_vMyKeyboardDirection.x = m_vMyKeyboardDirection.y = m_vMyKeyboardDirection.z = 0.0f; - D3DXMatrixIdentity(&m_mShift); + m_fCameraYawAngle = atan2f( zBasis.x, zBasis.z ); + float fLen = sqrtf( zBasis.z * zBasis.z + zBasis.x * zBasis.x ); + m_fCameraPitchAngle = -atan2f( zBasis.y, fLen ); } - - //-------------------------------------------------------------------------------------- // Calculates the projection matrix based on input params //-------------------------------------------------------------------------------------- -VOID CBaseCamera::SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, - FLOAT fFarPlane ) +_Use_decl_annotations_ +void CBaseCamera::SetProjParams( float fFOV, float fAspect, float fNearPlane, float fFarPlane ) { // Set attributes for the projection matrix m_fFOV = fFOV; @@ -306,15 +289,15 @@ VOID CBaseCamera::SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, m_fNearPlane = fNearPlane; m_fFarPlane = fFarPlane; - D3DXMatrixPerspectiveFovLH( &m_mProj, fFOV, fAspect, fNearPlane, fFarPlane ); + XMMATRIX mProj = XMMatrixPerspectiveFovLH( fFOV, fAspect, fNearPlane, fFarPlane ); + XMStoreFloat4x4( &m_mProj, mProj ); } - - //-------------------------------------------------------------------------------------- // Call this from your message proc so this class can handle window messages //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CBaseCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { UNREFERENCED_PARAMETER( hWnd ); @@ -330,6 +313,7 @@ LRESULT CBaseCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM D3DUtil_CameraKeys mappedKey = MapKey( ( UINT )wParam ); if( mappedKey != CAM_UNKNOWN ) { + _Analysis_assume_( mappedKey < CAM_MAX_KEYS ); if( FALSE == IsKeyDown( m_aKeys[mappedKey] ) ) { m_aKeys[ mappedKey ] = KEY_WAS_DOWN_MASK | KEY_IS_DOWN_MASK; @@ -443,13 +427,14 @@ LRESULT CBaseCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM return FALSE; } + //-------------------------------------------------------------------------------------- // Figure out the velocity based on keyboard input & drag if any //-------------------------------------------------------------------------------------- -void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bGetGamepadInput, - bool bResetCursorAfterMove ) +_Use_decl_annotations_ +void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bGetGamepadInput ) { - m_vKeyboardDirection = D3DXVECTOR3( 0, 0, 0 ); + m_vKeyboardDirection = DirectX::XMFLOAT3( 0, 0, 0 ); if( bGetKeyboardInput ) { // Update acceleration vector based on keyboard state @@ -470,17 +455,6 @@ void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bG m_vKeyboardDirection.x -= 1.0f; } - - if( IsKeyDown( m_aKeys[CAM_MOVE_FORWARD] ) ) - m_vMyKeyboardDirection.y -= 0.1f; - if( IsKeyDown( m_aKeys[CAM_MOVE_BACKWARD] ) ) - m_vMyKeyboardDirection.y += 0.1f; - - if( IsKeyDown( m_aKeys[CAM_STRAFE_RIGHT] ) ) - m_vMyKeyboardDirection.x -= 0.1f; - if( IsKeyDown( m_aKeys[CAM_STRAFE_LEFT] ) ) - m_vMyKeyboardDirection.x += 0.1f; - if( bGetMouseInput ) { UpdateMouseDelta(); @@ -488,8 +462,8 @@ void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bG if( bGetGamepadInput ) { - m_vGamePadLeftThumb = D3DXVECTOR3( 0, 0, 0 ); - m_vGamePadRightThumb = D3DXVECTOR3( 0, 0, 0 ); + m_vGamePadLeftThumb = DirectX::XMFLOAT3( 0, 0, 0 ); + m_vGamePadRightThumb = DirectX::XMFLOAT3( 0, 0, 0 ); // Get controller state for( DWORD iUserIndex = 0; iUserIndex < DXUT_MAX_CONTROLLERS; iUserIndex++ ) @@ -498,7 +472,7 @@ void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bG // Mark time if the controller is in a non-zero state if( m_GamePad[iUserIndex].wButtons || - m_GamePad[iUserIndex].sThumbLX || m_GamePad[iUserIndex].sThumbLX || + m_GamePad[iUserIndex].sThumbLX || m_GamePad[iUserIndex].sThumbLY || m_GamePad[iUserIndex].sThumbRX || m_GamePad[iUserIndex].sThumbRY || m_GamePad[iUserIndex].bLeftTrigger || m_GamePad[iUserIndex].bRightTrigger ) { @@ -538,13 +512,12 @@ void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bG //-------------------------------------------------------------------------------------- void CBaseCamera::UpdateMouseDelta() { - POINT ptCurMouseDelta; - POINT ptCurMousePos; - // Get current position of mouse + POINT ptCurMousePos; GetCursorPos( &ptCurMousePos ); // Calc how far it's moved since last frame + POINT ptCurMouseDelta; ptCurMouseDelta.x = ptCurMousePos.x - m_ptLastMousePosition.x; ptCurMouseDelta.y = ptCurMousePos.y - m_ptLastMousePosition.y; @@ -577,26 +550,30 @@ void CBaseCamera::UpdateMouseDelta() m_vMouseDelta.x = m_vMouseDelta.x * fPercentOfOld + ptCurMouseDelta.x * fPercentOfNew; m_vMouseDelta.y = m_vMouseDelta.y * fPercentOfOld + ptCurMouseDelta.y * fPercentOfNew; - m_vRotVelocity = m_vMouseDelta * m_fRotationScaler; + m_vRotVelocity.x = m_vMouseDelta.x * m_fRotationScaler; + m_vRotVelocity.y = m_vMouseDelta.y * m_fRotationScaler; } - - //-------------------------------------------------------------------------------------- // Figure out the velocity based on keyboard input & drag if any //-------------------------------------------------------------------------------------- -void CBaseCamera::UpdateVelocity( float fElapsedTime ) +void CBaseCamera::UpdateVelocity( _In_ float fElapsedTime ) { - D3DXMATRIX mRotDelta; - D3DXVECTOR2 vGamePadRightThumb = D3DXVECTOR2( m_vGamePadRightThumb.x, -m_vGamePadRightThumb.z ); - m_vRotVelocity = m_vMouseDelta * m_fRotationScaler + vGamePadRightThumb * 0.02f; + XMVECTOR vGamePadRightThumb = XMVectorSet( m_vGamePadRightThumb.x, -m_vGamePadRightThumb.z, 0, 0 ); + + XMVECTOR vMouseDelta = XMLoadFloat2( &m_vMouseDelta ); + XMVECTOR vRotVelocity = vMouseDelta * m_fRotationScaler + vGamePadRightThumb * 0.02f; - D3DXVECTOR3 vAccel = m_vKeyboardDirection + m_vGamePadLeftThumb; + XMStoreFloat2( &m_vRotVelocity, vRotVelocity ); + + XMVECTOR vKeyboardDirection = XMLoadFloat3( &m_vKeyboardDirection ); + XMVECTOR vGamePadLeftThumb = XMLoadFloat3( &m_vGamePadLeftThumb ); + XMVECTOR vAccel = vKeyboardDirection + vGamePadLeftThumb; // Normalize vector so if moving 2 dirs (left & forward), // the camera doesn't move faster than if moving in 1 dir - D3DXVec3Normalize( &vAccel, &vAccel ); + vAccel = XMVector3Normalize( vAccel ); // Scale the acceleration vector vAccel *= m_fMoveScaler; @@ -604,15 +581,17 @@ void CBaseCamera::UpdateVelocity( float fElapsedTime ) if( m_bMovementDrag ) { // Is there any acceleration this frame? - if( D3DXVec3LengthSq( &vAccel ) > 0 ) + if( XMVectorGetX( XMVector3LengthSq( vAccel ) ) > 0 ) { - // If so, then this means the user has pressed a movement key\ + // If so, then this means the user has pressed a movement key // so change the velocity immediately to acceleration // upon keyboard input. This isn't normal physics // but it will give a quick response to keyboard input - m_vVelocity = vAccel; + XMStoreFloat3( &m_vVelocity, vAccel ); + m_fDragTimer = m_fTotalDragTimeToZero; - m_vVelocityDrag = vAccel / m_fDragTimer; + + XMStoreFloat3( &m_vVelocityDrag, vAccel / m_fDragTimer ); } else { @@ -620,48 +599,34 @@ void CBaseCamera::UpdateVelocity( float fElapsedTime ) if( m_fDragTimer > 0 ) { // Drag until timer is <= 0 - m_vVelocity -= m_vVelocityDrag * fElapsedTime; + XMVECTOR vVelocity = XMLoadFloat3( &m_vVelocity ); + XMVECTOR vVelocityDrag = XMLoadFloat3( &m_vVelocityDrag ); + + vVelocity -= vVelocityDrag * fElapsedTime; + + XMStoreFloat3( &m_vVelocity, vVelocity ); + m_fDragTimer -= fElapsedTime; } else { // Zero velocity - m_vVelocity = D3DXVECTOR3( 0, 0, 0 ); + m_vVelocity = DirectX::XMFLOAT3( 0, 0, 0 ); } } } else { // No drag, so immediately change the velocity - m_vVelocity = vAccel; + XMStoreFloat3( &m_vVelocity, vAccel ); } } - - -//-------------------------------------------------------------------------------------- -// Clamps pV to lie inside m_vMinBoundary & m_vMaxBoundary -//-------------------------------------------------------------------------------------- -void CBaseCamera::ConstrainToBoundary( D3DXVECTOR3* pV ) -{ - // Constrain vector to a bounding box - pV->x = __max( pV->x, m_vMinBoundary.x ); - pV->y = __max( pV->y, m_vMinBoundary.y ); - pV->z = __max( pV->z, m_vMinBoundary.z ); - - pV->x = __min( pV->x, m_vMaxBoundary.x ); - pV->y = __min( pV->y, m_vMaxBoundary.y ); - pV->z = __min( pV->z, m_vMaxBoundary.z ); -} - - - - //-------------------------------------------------------------------------------------- // Maps a windows virtual key to an enum //-------------------------------------------------------------------------------------- -D3DUtil_CameraKeys CBaseCamera::MapKey( UINT nKey ) +D3DUtil_CameraKeys CBaseCamera::MapKey( _In_ UINT nKey ) { // This could be upgraded to a method that's user-definable but for // simplicity, we'll use a hardcoded mapping. @@ -688,7 +653,7 @@ D3DUtil_CameraKeys CBaseCamera::MapKey( UINT nKey ) return CAM_STRAFE_RIGHT; case 'W': return CAM_MOVE_FORWARD; - case 'X': // Change back to S + case 'S': return CAM_MOVE_BACKWARD; case 'Q': return CAM_MOVE_DOWN; @@ -716,46 +681,50 @@ D3DUtil_CameraKeys CBaseCamera::MapKey( UINT nKey ) } - - //-------------------------------------------------------------------------------------- // Reset the camera's position back to the default //-------------------------------------------------------------------------------------- -VOID CBaseCamera::Reset() +void CBaseCamera::Reset() { - SetViewParams( &m_vDefaultEye, &m_vDefaultLookAt ); -} + XMVECTOR vDefaultEye = XMLoadFloat3( &m_vDefaultEye ); + XMVECTOR vDefaultLookAt = XMLoadFloat3( &m_vDefaultLookAt ); + SetViewParams( vDefaultEye, vDefaultLookAt ); +} +//====================================================================================== +// CFirstPersonCamera +//====================================================================================== -//-------------------------------------------------------------------------------------- -// Constructor -//-------------------------------------------------------------------------------------- -CFirstPersonCamera::CFirstPersonCamera() : m_nActiveButtonMask( 0x07 ) +CFirstPersonCamera::CFirstPersonCamera() noexcept : + m_mCameraWorld{}, + m_nActiveButtonMask( 0x07 ), + m_bRotateWithoutButtonDown(false) { - m_bRotateWithoutButtonDown = false; } - - //-------------------------------------------------------------------------------------- // Update the view matrix based on user input & elapsed time //-------------------------------------------------------------------------------------- -VOID CFirstPersonCamera::FrameMove( FLOAT fElapsedTime ) +void CFirstPersonCamera::FrameMove( _In_ float fElapsedTime ) { - if( DXUTGetGlobalTimer()->IsStopped() ) { - if (DXUTGetFPS() == 0.0f) fElapsedTime = 0; - else fElapsedTime = 1.0f / DXUTGetFPS(); + if( DXUTGetGlobalTimer()->IsStopped() ) + { + if (DXUTGetFPS() == 0.0f) + fElapsedTime = 0; + else + fElapsedTime = 1.0f / DXUTGetFPS(); } if( IsKeyDown( m_aKeys[CAM_RESET] ) ) + { Reset(); + } // Get keyboard/mouse/gamepad input - GetInput( m_bEnablePositionMovement, ( m_nActiveButtonMask & m_nCurrentButtonMask ) || m_bRotateWithoutButtonDown, - true, m_bResetCursorAfterMove ); + GetInput( m_bEnablePositionMovement, ( m_nActiveButtonMask & m_nCurrentButtonMask ) || m_bRotateWithoutButtonDown, true ); //// Get the mouse movement (if any) if the mouse button are down //if( (m_nActiveButtonMask & m_nCurrentButtonMask) || m_bRotateWithoutButtonDown ) @@ -765,13 +734,14 @@ VOID CFirstPersonCamera::FrameMove( FLOAT fElapsedTime ) UpdateVelocity( fElapsedTime ); // Simple euler method to calculate position delta - D3DXVECTOR3 vPosDelta = m_vVelocity * fElapsedTime; + XMVECTOR vVelocity = XMLoadFloat3( &m_vVelocity ); + XMVECTOR vPosDelta = vVelocity * fElapsedTime; // If rotating the camera - if( ( m_nActiveButtonMask & m_nCurrentButtonMask ) || - m_bRotateWithoutButtonDown || - m_vGamePadRightThumb.x != 0 || - m_vGamePadRightThumb.z != 0 ) + if( ( m_nActiveButtonMask & m_nCurrentButtonMask ) + || m_bRotateWithoutButtonDown + || m_vGamePadRightThumb.x != 0 + || m_vGamePadRightThumb.z != 0 ) { // Update the pitch & yaw angle based on mouse movement float fYawDelta = m_vRotVelocity.x; @@ -785,50 +755,50 @@ VOID CFirstPersonCamera::FrameMove( FLOAT fElapsedTime ) m_fCameraYawAngle += fYawDelta; // Limit pitch to straight up or straight down - m_fCameraPitchAngle = __max( -D3DX_PI / 2.0f, m_fCameraPitchAngle ); - m_fCameraPitchAngle = __min( +D3DX_PI / 2.0f, m_fCameraPitchAngle ); + m_fCameraPitchAngle = std::max( -XM_PI / 2.0f, m_fCameraPitchAngle ); + m_fCameraPitchAngle = std::min( +XM_PI / 2.0f, m_fCameraPitchAngle ); } // Make a rotation matrix based on the camera's yaw & pitch - D3DXMATRIX mCameraRot; - D3DXMatrixRotationYawPitchRoll( &mCameraRot, m_fCameraYawAngle, m_fCameraPitchAngle, 0 ); + XMMATRIX mCameraRot = XMMatrixRotationRollPitchYaw( m_fCameraPitchAngle, m_fCameraYawAngle, 0 ); // Transform vectors based on camera's rotation matrix - D3DXVECTOR3 vWorldUp, vWorldAhead; - D3DXVECTOR3 vLocalUp = D3DXVECTOR3( 0, 1, 0 ); - D3DXVECTOR3 vLocalAhead = D3DXVECTOR3( 0, 0, 1 ); - D3DXVec3TransformCoord( &vWorldUp, &vLocalUp, &mCameraRot ); - D3DXVec3TransformCoord( &vWorldAhead, &vLocalAhead, &mCameraRot ); + XMVECTOR vWorldUp = XMVector3TransformCoord( g_XMIdentityR1, mCameraRot ); + XMVECTOR vWorldAhead = XMVector3TransformCoord( g_XMIdentityR2, mCameraRot ); // Transform the position delta by the camera's rotation - D3DXVECTOR3 vPosDeltaWorld; if( !m_bEnableYAxisMovement ) { // If restricting Y movement, do not include pitch // when transforming position delta vector. - D3DXMatrixRotationYawPitchRoll( &mCameraRot, m_fCameraYawAngle, 0.0f, 0.0f ); + mCameraRot = XMMatrixRotationRollPitchYaw( 0.0f, m_fCameraYawAngle, 0.0f ); } - D3DXVec3TransformCoord( &vPosDeltaWorld, &vPosDelta, &mCameraRot ); + XMVECTOR vPosDeltaWorld = XMVector3TransformCoord( vPosDelta, mCameraRot ); // Move the eye position - m_vEye += vPosDeltaWorld; + XMVECTOR vEye = XMLoadFloat3( &m_vEye ); + vEye += vPosDeltaWorld; if( m_bClipToBoundary ) - ConstrainToBoundary( &m_vEye ); + vEye = ConstrainToBoundary( vEye ); + XMStoreFloat3( &m_vEye, vEye ); - // Update the lookAt position based on the eye position - m_vLookAt = m_vEye + vWorldAhead; + // Update the lookAt position based on the eye position + XMVECTOR vLookAt = vEye + vWorldAhead; + XMStoreFloat3( &m_vLookAt, vLookAt ); // Update the view matrix - D3DXMatrixLookAtLH( &m_mView, &m_vEye, &m_vLookAt, &vWorldUp ); - + XMMATRIX mView = XMMatrixLookAtLH( vEye, vLookAt, vWorldUp ); + XMStoreFloat4x4( &m_mView, mView ); - D3DXMatrixInverse( &m_mCameraWorld, NULL, &m_mView ); + XMMATRIX mCameraWorld = XMMatrixInverse( nullptr, mView ); + XMStoreFloat4x4( &m_mCameraWorld, mCameraWorld ); } //-------------------------------------------------------------------------------------- // Enable or disable each of the mouse buttons for rotation drag. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CFirstPersonCamera::SetRotateButtons( bool bLeft, bool bMiddle, bool bRight, bool bRotateWithoutButtonDown ) { m_nActiveButtonMask = ( bLeft ? MOUSE_LEFT_BUTTON : 0 ) | @@ -838,38 +808,40 @@ void CFirstPersonCamera::SetRotateButtons( bool bLeft, bool bMiddle, bool bRight } -//-------------------------------------------------------------------------------------- -// Constructor -//-------------------------------------------------------------------------------------- -CModelViewerCamera::CModelViewerCamera() -{ - D3DXMatrixIdentity( &m_mWorld ); - D3DXMatrixIdentity( &m_mModelRot ); - D3DXMatrixIdentity( &m_mModelLastRot ); - D3DXMatrixIdentity( &m_mCameraRotLast ); - m_vModelCenter = D3DXVECTOR3( 0, 0, 0 ); - m_fRadius = 5.0f; - m_fDefaultRadius = 5.0f; - m_fMinRadius = 0.1f; - m_fMaxRadius = FLT_MAX; - m_bLimitPitch = false; - m_bEnablePositionMovement = false; - m_bAttachCameraToModel = false; - m_nRotateModelButtonMask = MOUSE_LEFT_BUTTON; - m_nZoomButtonMask = MOUSE_WHEEL; - m_nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON; - m_bDragSinceLastUpdate = true; -} +//====================================================================================== +// CModelViewerCamera +//====================================================================================== +CModelViewerCamera::CModelViewerCamera() noexcept : + m_nRotateModelButtonMask(MOUSE_LEFT_BUTTON), + m_nZoomButtonMask(MOUSE_WHEEL), + m_nRotateCameraButtonMask(MOUSE_RIGHT_BUTTON), + m_bAttachCameraToModel(false), + m_bLimitPitch(false), + m_bDragSinceLastUpdate(true), + m_fRadius(5.0f), + m_fDefaultRadius(5.0f), + m_fMinRadius(1.0f), + m_fMaxRadius(FLT_MAX) +{ + XMMATRIX id = XMMatrixIdentity(); + + XMStoreFloat4x4( &m_mWorld, id ); + XMStoreFloat4x4( &m_mModelRot, id ); + XMStoreFloat4x4( &m_mModelLastRot, id ); + XMStoreFloat4x4( &m_mCameraRotLast, id ); + m_vModelCenter = DirectX::XMFLOAT3( 0, 0, 0 ); + m_bEnablePositionMovement = false; +} //-------------------------------------------------------------------------------------- // Update the view matrix & the model's world matrix based // on user input & elapsed time //-------------------------------------------------------------------------------------- -VOID CModelViewerCamera::FrameMove( FLOAT fElapsedTime ) +void CModelViewerCamera::FrameMove( _In_ float fElapsedTime ) { if( IsKeyDown( m_aKeys[CAM_RESET] ) ) Reset(); @@ -878,108 +850,109 @@ VOID CModelViewerCamera::FrameMove( FLOAT fElapsedTime ) // and no camera key is held down, then no need to handle again. if( !m_bDragSinceLastUpdate && 0 == m_cKeysDown ) return; + m_bDragSinceLastUpdate = false; //// If no mouse button is held down, //// Get the mouse movement (if any) if the mouse button are down //if( m_nCurrentButtonMask != 0 ) // UpdateMouseDelta( fElapsedTime ); - //m_bEnablePositionMovement = true; - GetInput( m_bEnablePositionMovement, m_nCurrentButtonMask != 0, true, false ); + + GetInput( m_bEnablePositionMovement, m_nCurrentButtonMask != 0, true ); // Get amount of velocity based on the keyboard input and drag (if any) UpdateVelocity( fElapsedTime ); // Simple euler method to calculate position delta - D3DXVECTOR3 vPosDelta = m_vVelocity * fElapsedTime; + XMVECTOR vPosDelta = XMLoadFloat3( &m_vVelocity ) * fElapsedTime; // Change the radius from the camera to the model based on wheel scrolling - if( m_nMouseWheelDelta && m_nZoomButtonMask & MOUSE_WHEEL ) + if( m_nMouseWheelDelta && m_nZoomButtonMask == MOUSE_WHEEL ) m_fRadius -= m_nMouseWheelDelta * m_fRadius * 0.1f / 120.0f; - - m_fRadius = __min( m_fMaxRadius, m_fRadius ); - m_fRadius = __max( m_fMinRadius, m_fRadius ); + m_fRadius = std::min( m_fMaxRadius, m_fRadius ); + m_fRadius = std::max( m_fMinRadius, m_fRadius ); m_nMouseWheelDelta = 0; // Get the inverse of the arcball's rotation matrix - D3DXMATRIX mCameraRot; - D3DXMatrixInverse( &mCameraRot, NULL, m_ViewArcBall.GetRotationMatrix() ); + XMMATRIX mCameraRot = XMMatrixInverse( nullptr, m_ViewArcBall.GetRotationMatrix() ); // Transform vectors based on camera's rotation matrix - D3DXVECTOR3 vWorldUp, vWorldAhead; - D3DXVECTOR3 vLocalUp = D3DXVECTOR3( 0, 1, 0 ); - D3DXVECTOR3 vLocalAhead = D3DXVECTOR3( 0, 0, 1 ); - D3DXVec3TransformCoord( &vWorldUp, &vLocalUp, &mCameraRot ); - D3DXVec3TransformCoord( &vWorldAhead, &vLocalAhead, &mCameraRot ); + XMVECTOR vWorldUp = XMVector3TransformCoord( g_XMIdentityR1, mCameraRot ); + XMVECTOR vWorldAhead = XMVector3TransformCoord( g_XMIdentityR2, mCameraRot ); // Transform the position delta by the camera's rotation - D3DXVECTOR3 vPosDeltaWorld; - D3DXVec3TransformCoord( &vPosDeltaWorld, &vPosDelta, &mCameraRot ); + XMVECTOR vPosDeltaWorld = XMVector3TransformCoord( vPosDelta, mCameraRot ); // Move the lookAt position - m_vLookAt += vPosDeltaWorld; + XMVECTOR vLookAt = XMLoadFloat3( &m_vLookAt ); + vLookAt += vPosDeltaWorld; if( m_bClipToBoundary ) - ConstrainToBoundary( &m_vLookAt ); + vLookAt = ConstrainToBoundary( vLookAt ); + XMStoreFloat3( &m_vLookAt, vLookAt ); // Update the eye point based on a radius away from the lookAt position - m_vEye = m_vLookAt - vWorldAhead * m_fRadius; + XMVECTOR vEye = vLookAt - vWorldAhead * m_fRadius; + XMStoreFloat3( &m_vEye, vEye ); // Update the view matrix - D3DXMatrixLookAtLH( &m_mView, &m_vEye, &m_vLookAt, &vWorldUp ); + XMMATRIX mView = XMMatrixLookAtLH( vEye, vLookAt, vWorldUp ); + XMStoreFloat4x4( &m_mView, mView ); - D3DXMATRIX mInvView; - D3DXMatrixInverse( &mInvView, NULL, &m_mView ); - mInvView._41 = mInvView._42 = mInvView._43 = 0; + XMMATRIX mInvView = XMMatrixInverse( nullptr, mView ); + mInvView.r[3] = XMVectorSelect( mInvView.r[3], g_XMZero, g_XMSelect1110 ); - D3DXMATRIX mModelLastRotInv; - D3DXMatrixInverse( &mModelLastRotInv, NULL, &m_mModelLastRot ); + XMMATRIX mModelLastRot = XMLoadFloat4x4( &m_mModelLastRot ); + XMMATRIX mModelLastRotInv = XMMatrixInverse( nullptr, mModelLastRot ); // Accumulate the delta of the arcball's rotation in view space. // Note that per-frame delta rotations could be problematic over long periods of time. - D3DXMATRIX mModelRot; - mModelRot = *m_WorldArcBall.GetRotationMatrix(); - m_mModelRot *= m_mView * mModelLastRotInv * mModelRot * mInvView; + XMMATRIX mModelRot0 = m_WorldArcBall.GetRotationMatrix(); + XMMATRIX mModelRot = XMLoadFloat4x4( &m_mModelRot ); + mModelRot *= mView * mModelLastRotInv * mModelRot0 * mInvView; if( m_ViewArcBall.IsBeingDragged() && m_bAttachCameraToModel && !IsKeyDown( m_aKeys[CAM_CONTROLDOWN] ) ) { // Attach camera to model by inverse of the model rotation - D3DXMATRIX mCameraLastRotInv; - D3DXMatrixInverse( &mCameraLastRotInv, NULL, &m_mCameraRotLast ); - D3DXMATRIX mCameraRotDelta = mCameraLastRotInv * mCameraRot; // local to world matrix - m_mModelRot *= mCameraRotDelta; + XMMATRIX mCameraRotLast = XMLoadFloat4x4( &m_mCameraRotLast ); + XMMATRIX mCameraLastRotInv = XMMatrixInverse( nullptr, mCameraRotLast ); + XMMATRIX mCameraRotDelta = mCameraLastRotInv * mCameraRot; // local to world matrix + mModelRot *= mCameraRotDelta; } - m_mCameraRotLast = mCameraRot; - m_mModelLastRot = mModelRot; + XMStoreFloat4x4( &m_mModelLastRot, mModelRot0 ); + XMStoreFloat4x4( &m_mCameraRotLast, mCameraRot ); // Since we're accumulating delta rotations, we need to orthonormalize // the matrix to prevent eventual matrix skew - D3DXVECTOR3* pXBasis = ( D3DXVECTOR3* )&m_mModelRot._11; - D3DXVECTOR3* pYBasis = ( D3DXVECTOR3* )&m_mModelRot._21; - D3DXVECTOR3* pZBasis = ( D3DXVECTOR3* )&m_mModelRot._31; - D3DXVec3Normalize( pXBasis, pXBasis ); - D3DXVec3Cross( pYBasis, pZBasis, pXBasis ); - D3DXVec3Normalize( pYBasis, pYBasis ); - D3DXVec3Cross( pZBasis, pXBasis, pYBasis ); + XMVECTOR xBasis = XMVector3Normalize( mModelRot.r[0] ); + XMVECTOR yBasis = XMVector3Cross( mModelRot.r[2], xBasis ); + yBasis = XMVector3Normalize( yBasis ); + XMVECTOR zBasis = XMVector3Cross( xBasis, yBasis ); + + mModelRot.r[0] = XMVectorSelect( mModelRot.r[0], xBasis, g_XMSelect1110 ); + mModelRot.r[1] = XMVectorSelect( mModelRot.r[1], yBasis, g_XMSelect1110 ); + mModelRot.r[2] = XMVectorSelect( mModelRot.r[2], zBasis, g_XMSelect1110 ); // Translate the rotation matrix to the same position as the lookAt position - m_mModelRot._41 = m_vLookAt.x; - m_mModelRot._42 = m_vLookAt.y; - m_mModelRot._43 = m_vLookAt.z; + mModelRot.r[3] = XMVectorSelect( mModelRot.r[3], vLookAt, g_XMSelect1110 ); + + XMStoreFloat4x4( &m_mModelRot, mModelRot ); // Translate world matrix so its at the center of the model - D3DXMATRIX mTrans; - D3DXMatrixTranslation( &mTrans, -m_vModelCenter.x, -m_vModelCenter.y, -m_vModelCenter.z ); - m_mWorld = mTrans * m_mModelRot; + XMMATRIX mTrans = XMMatrixTranslation( -m_vModelCenter.x, -m_vModelCenter.y, -m_vModelCenter.z ); + XMMATRIX mWorld = mTrans * mModelRot; + XMStoreFloat4x4( &m_mWorld, mWorld ); } -void CModelViewerCamera::SetDragRect( RECT& rc ) +//-------------------------------------------------------------------------------------- +void CModelViewerCamera::SetDragRect( _In_ const RECT& rc ) { CBaseCamera::SetDragRect( rc ); m_WorldArcBall.SetOffset( rc.left, rc.top ); m_ViewArcBall.SetOffset( rc.left, rc.top ); + SetWindow( rc.right - rc.left, rc.bottom - rc.top ); } @@ -987,47 +960,49 @@ void CModelViewerCamera::SetDragRect( RECT& rc ) //-------------------------------------------------------------------------------------- // Reset the camera's position back to the default //-------------------------------------------------------------------------------------- -VOID CModelViewerCamera::Reset() +void CModelViewerCamera::Reset() { CBaseCamera::Reset(); - D3DXMatrixIdentity( &m_mWorld ); - D3DXMatrixIdentity( &m_mModelRot ); - D3DXMatrixIdentity( &m_mModelLastRot ); - D3DXMatrixIdentity( &m_mCameraRotLast ); + XMMATRIX id = XMMatrixIdentity(); + XMStoreFloat4x4( &m_mWorld, id ); + XMStoreFloat4x4( &m_mModelRot, id ); + XMStoreFloat4x4( &m_mModelLastRot, id ); + XMStoreFloat4x4( &m_mCameraRotLast, id ); m_fRadius = m_fDefaultRadius; m_WorldArcBall.Reset(); m_ViewArcBall.Reset(); } + //-------------------------------------------------------------------------------------- // Override for setting the view parameters //-------------------------------------------------------------------------------------- -void CModelViewerCamera::SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ) +_Use_decl_annotations_ +void CModelViewerCamera::SetViewParams( FXMVECTOR vEyePt, FXMVECTOR vLookatPt ) { - CBaseCamera::SetViewParams( pvEyePt, pvLookatPt ); + CBaseCamera::SetViewParams( vEyePt, vLookatPt ); // Propogate changes to the member arcball - D3DXQUATERNION quat; - D3DXMATRIXA16 mRotation; - D3DXVECTOR3 vUp( 0,1,0 ); - D3DXMatrixLookAtLH( &mRotation, pvEyePt, pvLookatPt, &vUp ); - D3DXQuaternionRotationMatrix( &quat, &mRotation ); + XMMATRIX mRotation = XMMatrixLookAtLH( vEyePt, vLookatPt, g_XMIdentityR1 ); + XMVECTOR quat = XMQuaternionRotationMatrix( mRotation ); m_ViewArcBall.SetQuatNow( quat ); // Set the radius according to the distance - D3DXVECTOR3 vEyeToPoint; - D3DXVec3Subtract( &vEyeToPoint, pvLookatPt, pvEyePt ); - SetRadius( D3DXVec3Length( &vEyeToPoint ), 0.2f ); + XMVECTOR vEyeToPoint = XMVectorSubtract( vLookatPt, vEyePt ); + float len = XMVectorGetX( XMVector3Length( vEyeToPoint ) ); + SetRadius( len ); // View information changed. FrameMove should be called. m_bDragSinceLastUpdate = true; } + //-------------------------------------------------------------------------------------- // Call this from your message proc so this class can handle window messages //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CModelViewerCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { CBaseCamera::HandleMessages( hWnd, uMsg, wParam, lParam ); @@ -1057,15 +1032,6 @@ LRESULT CModelViewerCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, int iMouseY = ( short )HIWORD( lParam ); m_WorldArcBall.OnMove( iMouseX, iMouseY ); m_ViewArcBall.OnMove( iMouseX, iMouseY ); - - - if (m_nZoomButtonMask & MOUSE_RIGHT_BUTTON && m_bMouseRButtonDown) { - FLOAT fDeltaX = (FLOAT)( m_ptLastMouseX - iMouseX ); - //FLOAT fDeltaY = (FLOAT)( m_ptLastMousePosition.y - iMouseY ); - //m_fRadius -= fDeltaX * m_fRadius * 0.1f / 120.0f; - m_fRadius -= fDeltaX * m_fRadius / 100.0f; - } - m_ptLastMouseX = iMouseX; } if( ( uMsg == WM_LBUTTONUP && m_nRotateModelButtonMask & MOUSE_LEFT_BUTTON ) || @@ -1121,152 +1087,32 @@ LRESULT CModelViewerCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, } +//====================================================================================== +// CDXUTDirectionWidget +//====================================================================================== -//-------------------------------------------------------------------------------------- -// D3D9 -IDirect3DDevice9* CDXUTDirectionWidget::s_pd3d9Device = NULL; -ID3DXEffect* CDXUTDirectionWidget::s_pD3D9Effect = NULL; -ID3DXMesh* CDXUTDirectionWidget::s_pD3D9Mesh = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hRenderWith1LightNoTexture = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hMaterialDiffuseColor = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hLightDir = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hWorldViewProjection = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hWorld = NULL; - - -//-------------------------------------------------------------------------------------- -CDXUTDirectionWidget::CDXUTDirectionWidget() +CDXUTDirectionWidget::CDXUTDirectionWidget() noexcept : + m_fRadius(1.0f), + m_nRotateMask(MOUSE_RIGHT_BUTTON) { - m_fRadius = 1.0f; - m_vDefaultDir = D3DXVECTOR3( 0, 1, 0 ); + m_vDefaultDir = DirectX::XMFLOAT3( 0, 1, 0 ); m_vCurrentDir = m_vDefaultDir; - m_nRotateMask = MOUSE_RIGHT_BUTTON; - - D3DXMatrixIdentity( &m_mView ); - D3DXMatrixIdentity( &m_mRot ); - D3DXMatrixIdentity( &m_mRotSnapshot ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::StaticOnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ) -{ - HRESULT hr; - - s_pd3d9Device = pd3dDevice; - - const char* g_strBuffer = - "float4 g_MaterialDiffuseColor; // Material's diffuse color\r\n" - "float3 g_LightDir; // Light's direction in world space\r\n" - "float4x4 g_mWorld; // World matrix for object\r\n" - "float4x4 g_mWorldViewProjection; // World * View * Projection matrix\r\n" - "\r\n" - "struct VS_OUTPUT\r\n" - "{\r\n" - " float4 Position : POSITION; // vertex position\r\n" - " float4 Diffuse : COLOR0; // vertex diffuse color\r\n" - "};\r\n" - "\r\n" - "VS_OUTPUT RenderWith1LightNoTextureVS( float4 vPos : POSITION,\r\n" - " float3 vNormal : NORMAL )\r\n" - "{\r\n" - " VS_OUTPUT Output;\r\n" - "\r\n" - " // Transform the position from object space to homogeneous projection space\r\n" - " Output.Position = mul(vPos, g_mWorldViewProjection);\r\n" - "\r\n" - " // Transform the normal from object space to world space\r\n" - " float3 vNormalWorldSpace;\r\n" - " vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space)\r\n" - "\r\n" - " // Compute simple directional lighting equation\r\n" - " Output.Diffuse.rgb = g_MaterialDiffuseColor * max(0,dot(vNormalWorldSpace, g_LightDir));\r\n" - " Output.Diffuse.a = 1.0f;\r\n" - "\r\n" - " return Output;\r\n" - "}\r\n" - "\r\n" - "float4 RenderWith1LightNoTexturePS( float4 Diffuse : COLOR0 ) : COLOR0\r\n" - "{\r\n" - " return Diffuse;\r\n" - "}\r\n" - "\r\n" - "technique RenderWith1LightNoTexture\r\n" - "{\r\n" - " pass P0\r\n" - " {\r\n" - " VertexShader = compile vs_2_0 RenderWith1LightNoTextureVS();\r\n" - " PixelShader = compile ps_2_0 RenderWith1LightNoTexturePS();\r\n" - " }\r\n" - "}\r\n" - ""; - - UINT dwBufferSize = ( UINT )strlen( g_strBuffer ) + 1; - - DWORD Flags = D3DXFX_NOT_CLONEABLE; -#ifdef D3DXFX_LARGEADDRESS_HANDLE - Flags |= D3DXFX_LARGEADDRESSAWARE; -#endif - - V_RETURN( D3DXCreateEffect( s_pd3d9Device, g_strBuffer, dwBufferSize, NULL, NULL, Flags, - NULL, &s_pD3D9Effect, NULL ) ); - - // Save technique handles for use when rendering - s_hRenderWith1LightNoTexture = s_pD3D9Effect->GetTechniqueByName( "RenderWith1LightNoTexture" ); - s_hMaterialDiffuseColor = s_pD3D9Effect->GetParameterByName( NULL, "g_MaterialDiffuseColor" ); - s_hLightDir = s_pD3D9Effect->GetParameterByName( NULL, "g_LightDir" ); - s_hWorld = s_pD3D9Effect->GetParameterByName( NULL, "g_mWorld" ); - s_hWorldViewProjection = s_pD3D9Effect->GetParameterByName( NULL, "g_mWorldViewProjection" ); - - // Load the mesh with D3DX and get back a ID3DXMesh*. For this - // sample we'll ignore the X file's embedded materials since we know - // exactly the model we're loading. See the mesh samples such as - // "OptimizedMesh" for a more generic mesh loading example. - V_RETURN( DXUTCreateArrowMeshFromInternalArray( s_pd3d9Device, &s_pD3D9Mesh ) ); - - // Optimize the mesh for this graphics card's vertex cache - // so when rendering the mesh's triangle list the vertices will - // cache hit more often so it won't have to re-execute the vertex shader - // on those vertices so it will improve perf. - DWORD* rgdwAdjacency = new DWORD[s_pD3D9Mesh->GetNumFaces() * 3]; - if( rgdwAdjacency == NULL ) - return E_OUTOFMEMORY; - V( s_pD3D9Mesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ) ); - V( s_pD3D9Mesh->OptimizeInplace( D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, NULL, NULL, NULL ) ); - delete []rgdwAdjacency; - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::OnD3D9ResetDevice( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ) -{ - m_ArcBall.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); - return S_OK; -} + XMMATRIX id = XMMatrixIdentity(); -//-------------------------------------------------------------------------------------- -void CDXUTDirectionWidget::StaticOnD3D9LostDevice() -{ - if( s_pD3D9Effect ) - s_pD3D9Effect->OnLostDevice(); -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDirectionWidget::StaticOnD3D9DestroyDevice() -{ - SAFE_RELEASE( s_pD3D9Effect ); - SAFE_RELEASE( s_pD3D9Mesh ); + XMStoreFloat4x4( &m_mView, id ); + XMStoreFloat4x4( &m_mRot, id ); + XMStoreFloat4x4( &m_mRotSnapshot, id ); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CDXUTDirectionWidget::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + switch( uMsg ) { case WM_LBUTTONDOWN: @@ -1333,222 +1179,71 @@ LRESULT CDXUTDirectionWidget::HandleMessages( HWND hWnd, UINT uMsg, } -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::OnRender9( D3DXCOLOR color, const D3DXMATRIX* pmView, - const D3DXMATRIX* pmProj, const D3DXVECTOR3* pEyePt ) -{ - m_mView = *pmView; - - // Render the light spheres so the user can visually see the light dir - UINT iPass, cPasses; - D3DXMATRIX mRotate; - D3DXMATRIX mScale; - D3DXMATRIX mTrans; - D3DXMATRIXA16 mWorldViewProj; - HRESULT hr; - - V( s_pD3D9Effect->SetTechnique( s_hRenderWith1LightNoTexture ) ); - V( s_pD3D9Effect->SetVector( s_hMaterialDiffuseColor, ( D3DXVECTOR4* )&color ) ); - - D3DXVECTOR3 vEyePt; - D3DXVec3Normalize( &vEyePt, pEyePt ); - V( s_pD3D9Effect->SetValue( s_hLightDir, &vEyePt, sizeof( D3DXVECTOR3 ) ) ); - - // Rotate arrow model to point towards origin - D3DXMATRIX mRotateA, mRotateB; - D3DXVECTOR3 vAt = D3DXVECTOR3( 0, 0, 0 ); - D3DXVECTOR3 vUp = D3DXVECTOR3( 0, 1, 0 ); - D3DXMatrixRotationX( &mRotateB, D3DX_PI ); - D3DXMatrixLookAtLH( &mRotateA, &m_vCurrentDir, &vAt, &vUp ); - D3DXMatrixInverse( &mRotateA, NULL, &mRotateA ); - mRotate = mRotateB * mRotateA; - - D3DXVECTOR3 vL = m_vCurrentDir * m_fRadius * 1.0f; - D3DXMatrixTranslation( &mTrans, vL.x, vL.y, vL.z ); - D3DXMatrixScaling( &mScale, m_fRadius * 0.2f, m_fRadius * 0.2f, m_fRadius * 0.2f ); - - D3DXMATRIX mWorld = mRotate * mScale * mTrans; - mWorldViewProj = mWorld * ( m_mView )*( *pmProj ); - - V( s_pD3D9Effect->SetMatrix( s_hWorldViewProjection, &mWorldViewProj ) ); - V( s_pD3D9Effect->SetMatrix( s_hWorld, &mWorld ) ); - - for( int iSubset = 0; iSubset < 2; iSubset++ ) - { - V( s_pD3D9Effect->Begin( &cPasses, 0 ) ); - for( iPass = 0; iPass < cPasses; iPass++ ) - { - V( s_pD3D9Effect->BeginPass( iPass ) ); - V( s_pD3D9Mesh->DrawSubset( iSubset ) ); - V( s_pD3D9Effect->EndPass() ); - } - V( s_pD3D9Effect->End() ); - } - - return S_OK; -} - //-------------------------------------------------------------------------------------- HRESULT CDXUTDirectionWidget::UpdateLightDir() { - D3DXMATRIX mInvView; - D3DXMatrixInverse( &mInvView, NULL, &m_mView ); - mInvView._41 = mInvView._42 = mInvView._43 = 0; + XMMATRIX mView = XMLoadFloat4x4( &m_mView ); + + XMMATRIX mInvView = XMMatrixInverse( nullptr, mView ); + mInvView.r[3] = XMVectorSelect( mInvView.r[3], g_XMZero, g_XMSelect1110 ); - D3DXMATRIX mLastRotInv; - D3DXMatrixInverse( &mLastRotInv, NULL, &m_mRotSnapshot ); + XMMATRIX mRotSnapshot = XMLoadFloat4x4( &m_mRotSnapshot ); + XMMATRIX mLastRotInv = XMMatrixInverse( nullptr, mRotSnapshot ); - D3DXMATRIX mRot = *m_ArcBall.GetRotationMatrix(); - m_mRotSnapshot = mRot; + XMMATRIX mRot0 = m_ArcBall.GetRotationMatrix(); + XMStoreFloat4x4( &m_mRotSnapshot, mRot0 ); // Accumulate the delta of the arcball's rotation in view space. // Note that per-frame delta rotations could be problematic over long periods of time. - m_mRot *= m_mView * mLastRotInv * mRot * mInvView; + XMMATRIX mRot = XMLoadFloat4x4( &m_mRot ); + mRot *= mView * mLastRotInv * mRot0 * mInvView; // Since we're accumulating delta rotations, we need to orthonormalize // the matrix to prevent eventual matrix skew - D3DXVECTOR3* pXBasis = ( D3DXVECTOR3* )&m_mRot._11; - D3DXVECTOR3* pYBasis = ( D3DXVECTOR3* )&m_mRot._21; - D3DXVECTOR3* pZBasis = ( D3DXVECTOR3* )&m_mRot._31; - D3DXVec3Normalize( pXBasis, pXBasis ); - D3DXVec3Cross( pYBasis, pZBasis, pXBasis ); - D3DXVec3Normalize( pYBasis, pYBasis ); - D3DXVec3Cross( pZBasis, pXBasis, pYBasis ); + XMVECTOR xBasis = XMVector3Normalize( mRot.r[0] ); + XMVECTOR yBasis = XMVector3Cross( mRot.r[2], xBasis ); + yBasis = XMVector3Normalize( yBasis ); + XMVECTOR zBasis = XMVector3Cross( xBasis, yBasis ); + mRot.r[0] = XMVectorSelect( mRot.r[0], xBasis, g_XMSelect1110 ); + mRot.r[1] = XMVectorSelect( mRot.r[1], yBasis, g_XMSelect1110 ); + mRot.r[2] = XMVectorSelect( mRot.r[2], zBasis, g_XMSelect1110 ); + XMStoreFloat4x4( &m_mRot, mRot ); // Transform the default direction vector by the light's rotation matrix - D3DXVec3TransformNormal( &m_vCurrentDir, &m_vDefaultDir, &m_mRot ); + XMVECTOR vDefaultDir = XMLoadFloat3( &m_vDefaultDir ); + XMVECTOR vCurrentDir = XMVector3TransformNormal( vDefaultDir, mRot ); + XMStoreFloat3( &m_vCurrentDir, vCurrentDir ); return S_OK; } + //-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::StaticOnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) +_Use_decl_annotations_ +HRESULT CDXUTDirectionWidget::OnRender( FXMVECTOR color, CXMMATRIX mView, CXMMATRIX mProj, FXMVECTOR vEyePt ) { - - - //s_pd3d10Device = pd3dDevice; - - //const char* g_strBuffer = - // "float4 g_MaterialDiffuseColor; // Material's diffuse color\r\n" - // "float4 g_LightDir; // Light's direction in world space\r\n" - // "float4x4 g_mWorld; // World matrix for object\r\n" - // "float4x4 g_mWorldViewProjection; // World * View * Projection matrix\r\n" - // "\r\n" - // "struct VS_OUTPUT\r\n" - // "{\r\n" - // " float4 Position : SV_POSITION; // vertex position\r\n" - // " float4 Diffuse : COLOR0; // vertex diffuse color\r\n" - // "};\r\n" - // "\r\n" - // "VS_OUTPUT RenderWith1LightNoTextureVS( float3 vPos : POSITION,\r\n" - // " float3 vNormal : NORMAL )\r\n" - // "{\r\n" - // " VS_OUTPUT Output;\r\n" - // "\r\n" - // " // Transform the position from object space to homogeneous projection space\r\n" - // " Output.Position = mul( float4(vPos,1), g_mWorldViewProjection);\r\n" - // "\r\n" - // " // Transform the normal from object space to world space\r\n" - // " float3 vNormalWorldSpace;\r\n" - // " vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space)\r\n" - // "\r\n" - // " // Compute simple directional lighting equation\r\n" - // " Output.Diffuse.rgb = g_MaterialDiffuseColor * max(0,dot(vNormalWorldSpace, g_LightDir));\r\n" - // " Output.Diffuse.a = 1.0f;\r\n" - // "\r\n" - // " return Output;\r\n" - // "}\r\n" - // "\r\n" - // "float4 RenderWith1LightNoTexturePS( VS_OUTPUT Input ) : SV_TARGET\r\n" - // "{\r\n" - // " return Input.Diffuse;\r\n" - // "}\r\n" - // "\r\n" - // "technique10 RenderWith1LightNoTexture\r\n" - // "{\r\n" - // " pass p0\r\n" - // " {\r\n" - // " SetVertexShader( CompileShader( vs_4_0, RenderWith1LightNoTextureVS() ) );\r\n" - // " SetGeometryShader( NULL );\r\n" - // " SetPixelShader( CompileShader( ps_4_0, RenderWith1LightNoTexturePS() ) );\r\n" - // " }\r\n" - // "}\r\n" - // ""; - - //UINT dwBufferSize = ( UINT )strlen( g_strBuffer ) + 1; - - //HRESULT hr = D3DX10CreateEffectFromMemory( g_strBuffer, dwBufferSize, "None", NULL, NULL, "fx_4_0", - // D3D10_SHADER_ENABLE_STRICTNESS, 0, pd3dDevice, NULL, - // NULL, &s_pD3D10Effect, NULL, NULL ); - //if( FAILED( hr ) ) - // return hr; - - //s_pRenderTech = s_pD3D10Effect->GetTechniqueByName( "RenderWith1LightNoTexture" ); - //g_pMaterialDiffuseColor = s_pD3D10Effect->GetVariableByName( "g_MaterialDiffuseColor" )->AsVector(); - //g_pLightDir = s_pD3D10Effect->GetVariableByName( "g_LightDir" )->AsVector(); - //g_pmWorld = s_pD3D10Effect->GetVariableByName( "g_mWorld" )->AsMatrix(); - //g_pmWorldViewProjection = s_pD3D10Effect->GetVariableByName( "g_mWorldViewProjection" )->AsMatrix(); - - //const D3D10_INPUT_ELEMENT_DESC layout[] = - //{ - // { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, - // { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, - //}; - //D3D10_PASS_DESC PassDesc; - //V_RETURN( s_pRenderTech->GetPassByIndex( 0 )->GetDesc( &PassDesc ) ); - //V_RETURN( pd3dDevice->CreateInputLayout( layout, 2, PassDesc.pIAInputSignature, - // PassDesc.IAInputSignatureSize, &s_pVertexLayout ) ); - + UNREFERENCED_PARAMETER(color); + UNREFERENCED_PARAMETER(mView); + UNREFERENCED_PARAMETER(mProj); + UNREFERENCED_PARAMETER(vEyePt); + // TODO - return S_OK; } + //-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::OnRender11( D3DXCOLOR color, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj, - const D3DXVECTOR3* pEyePt ) +_Use_decl_annotations_ +HRESULT CDXUTDirectionWidget::StaticOnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) { - // NO 11 version of D3DX11Mesh YET - // m_mView = *pmView; - - // // Render the light spheres so the user can visually see the light dir - // D3DXMATRIX mRotate; - // D3DXMATRIX mScale; - // D3DXMATRIX mTrans; - // D3DXMATRIXA16 mWorldViewProj; - - // g_pMaterialDiffuseColor->SetFloatVector( ( float* )&color ); - // D3DXVECTOR3 vEyePt; - // D3DXVec3Normalize( &vEyePt, pEyePt ); - // g_pLightDir->SetFloatVector( ( float* )&vEyePt ); - - // // Rotate arrow model to point towards origin - // D3DXMATRIX mRotateA, mRotateB; - // D3DXVECTOR3 vAt = D3DXVECTOR3( 0, 0, 0 ); - // D3DXVECTOR3 vUp = D3DXVECTOR3( 0, 1, 0 ); - // D3DXMatrixRotationX( &mRotateB, D3DX_PI ); - // D3DXMatrixLookAtLH( &mRotateA, &m_vCurrentDir, &vAt, &vUp ); - // D3DXMatrixInverse( &mRotateA, NULL, &mRotateA ); - // mRotate = mRotateB * mRotateA; - - // D3DXVECTOR3 vL = m_vCurrentDir * m_fRadius * 1.0f; - // D3DXMatrixTranslation( &mTrans, vL.x, vL.y, vL.z ); - // D3DXMatrixScaling( &mScale, m_fRadius * 0.2f, m_fRadius * 0.2f, m_fRadius * 0.2f ); - - // D3DXMATRIX mWorld = mRotate * mScale * mTrans; - // mWorldViewProj = mWorld * ( m_mView )*( *pmProj ); - - // g_pmWorldViewProjection->SetMatrix( ( float* )&mWorldViewProj ); - // g_pmWorld->SetMatrix( ( float* )&mWorld ); - - // s_pd3d10Device->IASetInputLayout( s_pVertexLayout ); - - // Add rendering code here - + UNREFERENCED_PARAMETER(pd3dDevice); + UNREFERENCED_PARAMETER(pd3dImmediateContext); + // TODO - return S_OK; } + //-------------------------------------------------------------------------------------- void CDXUTDirectionWidget::StaticOnD3D11DestroyDevice() { -// SAFE_RELEASE( s_pVertexLayout ); -// SAFE_RELEASE( s_pD3D11Effect ); + // TODO - } diff --git a/FriedLiver/Source/DXUT/Optional/DXUTcamera.h b/FriedLiver/Source/DXUT/Optional/DXUTcamera.h index d18da663..ad22a303 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTcamera.h +++ b/FriedLiver/Source/DXUT/Optional/DXUTcamera.h @@ -3,92 +3,105 @@ // // Helper functions for Direct3D programming. // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef CAMERA_H -#define CAMERA_H //-------------------------------------------------------------------------------------- class CD3DArcBall { public: - CD3DArcBall(); + CD3DArcBall() noexcept; // Functions to change behavior - void Reset(); - void SetTranslationRadius( FLOAT fRadiusTranslation ) + void Reset(); + void SetTranslationRadius( _In_ float fRadiusTranslation ) { m_fRadiusTranslation = fRadiusTranslation; } - void SetWindow( INT nWidth, INT nHeight, FLOAT fRadius = 0.9f ) - { - m_nWidth = nWidth; m_nHeight = nHeight; m_fRadius = fRadius; - m_vCenter = D3DXVECTOR2( m_nWidth / 2.0f, m_nHeight / 2.0f ); - } - void SetOffset( INT nX, INT nY ) + void SetWindow( _In_ INT nWidth, _In_ INT nHeight, _In_ float fRadius = 0.9f ) { - m_Offset.x = nX; m_Offset.y = nY; + m_nWidth = nWidth; + m_nHeight = nHeight; + m_fRadius = fRadius; + m_vCenter.x = float(m_nWidth) / 2.0f; + m_vCenter.y = float(m_nHeight) / 2.0f; } + void SetOffset( _In_ INT nX, _In_ INT nY ) { m_Offset.x = nX; m_Offset.y = nY; } // Call these from client and use GetRotationMatrix() to read new rotation matrix - void OnBegin( int nX, int nY ); // start the rotation (pass current mouse position) - void OnMove( int nX, int nY ); // continue the rotation (pass current mouse position) - void OnEnd(); // end the rotation + void OnBegin( _In_ int nX, _In_ int nY ); // start the rotation (pass current mouse position) + void OnMove( _In_ int nX, _In_ int nY ); // continue the rotation (pass current mouse position) + void OnEnd(); // end the rotation // Or call this to automatically handle left, middle, right buttons - LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); + LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); // Functions to get/set state - const D3DXMATRIX* GetRotationMatrix() - { - return D3DXMatrixRotationQuaternion( &m_mRotation, &m_qNow ); - }; - const D3DXMATRIX* GetTranslationMatrix() const - { - return &m_mTranslation; - } - const D3DXMATRIX* GetTranslationDeltaMatrix() const + DirectX::XMMATRIX GetRotationMatrix() const { - return &m_mTranslationDelta; + using namespace DirectX; + XMVECTOR q = XMLoadFloat4( &m_qNow ); + return DirectX::XMMatrixRotationQuaternion( q ); } - bool IsBeingDragged() const - { - return m_bDrag; - } - D3DXQUATERNION GetQuatNow() const + DirectX::XMMATRIX GetTranslationMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslation ); } + DirectX::XMMATRIX GetTranslationDeltaMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslationDelta ); } + bool IsBeingDragged() const { return m_bDrag; } + DirectX::XMVECTOR GetQuatNow() const { return DirectX::XMLoadFloat4( &m_qNow ); } + void SetQuatNow( _In_ DirectX::FXMVECTOR& q ) { DirectX::XMStoreFloat4( &m_qNow, q ); } + + static DirectX::XMVECTOR QuatFromBallPoints( _In_ DirectX::FXMVECTOR vFrom, _In_ DirectX::FXMVECTOR vTo ) { - return m_qNow; + using namespace DirectX; + + XMVECTOR dot = XMVector3Dot( vFrom, vTo ); + XMVECTOR vPart = XMVector3Cross( vFrom, vTo ); + return XMVectorSelect( dot, vPart, g_XMSelect1110 ); } - void SetQuatNow( D3DXQUATERNION q ) + +protected: + DirectX::XMFLOAT4X4 m_mRotation; // Matrix for arc ball's orientation + DirectX::XMFLOAT4X4 m_mTranslation; // Matrix for arc ball's position + DirectX::XMFLOAT4X4 m_mTranslationDelta;// Matrix for arc ball's position + + POINT m_Offset; // window offset, or upper-left corner of window + INT m_nWidth; // arc ball's window width + INT m_nHeight; // arc ball's window height + DirectX::XMFLOAT2 m_vCenter; // center of arc ball + float m_fRadius; // arc ball's radius in screen coords + float m_fRadiusTranslation; // arc ball's radius for translating the target + + DirectX::XMFLOAT4 m_qDown; // Quaternion before button down + DirectX::XMFLOAT4 m_qNow; // Composite quaternion for current drag + bool m_bDrag; // Whether user is dragging arc ball + + POINT m_ptLastMouse; // position of last mouse point + DirectX::XMFLOAT3 m_vDownPt; // starting point of rotation arc + DirectX::XMFLOAT3 m_vCurrentPt; // current point of rotation arc + + DirectX::XMVECTOR ScreenToVector( _In_ float fScreenPtX, _In_ float fScreenPtY ) { - m_qNow = q; - } + // Scale to screen + float x = -( fScreenPtX - m_Offset.x - m_nWidth / 2 ) / ( m_fRadius * m_nWidth / 2 ); + float y = ( fScreenPtY - m_Offset.y - m_nHeight / 2 ) / ( m_fRadius * m_nHeight / 2 ); - static D3DXQUATERNION WINAPI QuatFromBallPoints( const D3DXVECTOR3& vFrom, const D3DXVECTOR3& vTo ); + float z = 0.0f; + float mag = x * x + y * y; + if( mag > 1.0f ) + { + float scale = 1.0f / sqrtf( mag ); + x *= scale; + y *= scale; + } + else + z = sqrtf( 1.0f - mag ); -protected: - D3DXMATRIXA16 m_mRotation; // Matrix for arc ball's orientation - D3DXMATRIXA16 m_mTranslation; // Matrix for arc ball's position - D3DXMATRIXA16 m_mTranslationDelta; // Matrix for arc ball's position - - POINT m_Offset; // window offset, or upper-left corner of window - INT m_nWidth; // arc ball's window width - INT m_nHeight; // arc ball's window height - D3DXVECTOR2 m_vCenter; // center of arc ball - FLOAT m_fRadius; // arc ball's radius in screen coords - FLOAT m_fRadiusTranslation; // arc ball's radius for translating the target - - D3DXQUATERNION m_qDown; // Quaternion before button down - D3DXQUATERNION m_qNow; // Composite quaternion for current drag - bool m_bDrag; // Whether user is dragging arc ball - - POINT m_ptLastMouse; // position of last mouse point - D3DXVECTOR3 m_vDownPt; // starting point of rotation arc - D3DXVECTOR3 m_vCurrentPt; // current point of rotation arc - - D3DXVECTOR3 ScreenToVector( float fScreenPtX, float fScreenPtY ); + return DirectX::XMVectorSet( x, y, z, 0 ); + } }; @@ -126,195 +139,126 @@ enum D3DUtil_CameraKeys class CBaseCamera { public: - CBaseCamera(); + CBaseCamera() noexcept; // Call these from client and use Get*Matrix() to read new matrices - virtual LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual void FrameMove( FLOAT fElapsedTime ) = 0; + virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); + virtual void FrameMove( _In_ float fElapsedTime ) = 0; // Functions to change camera matrices - virtual void Reset(); - virtual void SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ); - virtual void SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, FLOAT fFarPlane ); + virtual void Reset(); + virtual void SetViewParams( _In_ DirectX::FXMVECTOR vEyePt, _In_ DirectX::FXMVECTOR vLookatPt ); + virtual void SetProjParams( _In_ float fFOV, _In_ float fAspect, _In_ float fNearPlane, _In_ float fFarPlane ); // Functions to change behavior - virtual void SetDragRect( RECT& rc ) - { - m_rcDrag = rc; - } - void SetInvertPitch( bool bInvertPitch ) - { - m_bInvertPitch = bInvertPitch; - } - void SetDrag( bool bMovementDrag, FLOAT fTotalDragTimeToZero = 0.25f ) - { - m_bMovementDrag = bMovementDrag; m_fTotalDragTimeToZero = fTotalDragTimeToZero; - } - void SetEnableYAxisMovement( bool bEnableYAxisMovement ) + virtual void SetDragRect( _In_ const RECT& rc ) { m_rcDrag = rc; } + void SetInvertPitch( _In_ bool bInvertPitch ) { m_bInvertPitch = bInvertPitch; } + void SetDrag( _In_ bool bMovementDrag, _In_ float fTotalDragTimeToZero = 0.25f ) { - m_bEnableYAxisMovement = bEnableYAxisMovement; + m_bMovementDrag = bMovementDrag; + m_fTotalDragTimeToZero = fTotalDragTimeToZero; } - void SetEnablePositionMovement( bool bEnablePositionMovement ) + void SetEnableYAxisMovement( _In_ bool bEnableYAxisMovement ) { m_bEnableYAxisMovement = bEnableYAxisMovement; } + void SetEnablePositionMovement( _In_ bool bEnablePositionMovement ) { m_bEnablePositionMovement = bEnablePositionMovement; } + void SetClipToBoundary( _In_ bool bClipToBoundary, _In_opt_ DirectX::XMFLOAT3* pvMinBoundary, _In_opt_ DirectX::XMFLOAT3* pvMaxBoundary ) { - m_bEnablePositionMovement = bEnablePositionMovement; - } - void SetClipToBoundary( bool bClipToBoundary, D3DXVECTOR3* pvMinBoundary, - D3DXVECTOR3* pvMaxBoundary ) - { - m_bClipToBoundary = bClipToBoundary; if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary; + m_bClipToBoundary = bClipToBoundary; + if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary; if( pvMaxBoundary ) m_vMaxBoundary = *pvMaxBoundary; } - void SetScalers( FLOAT fRotationScaler = 0.01f, FLOAT fMoveScaler = 5.0f ) - { - m_fRotationScaler = fRotationScaler; m_fMoveScaler = fMoveScaler; - } - void SetNumberOfFramesToSmoothMouseData( int nFrames ) + void SetScalers( _In_ float fRotationScaler = 0.01f, _In_ float fMoveScaler = 5.0f ) { - if( nFrames > 0 ) m_fFramesToSmoothMouseData = ( float )nFrames; - } - void SetResetCursorAfterMove( bool bResetCursorAfterMove ) - { - m_bResetCursorAfterMove = bResetCursorAfterMove; + m_fRotationScaler = fRotationScaler; + m_fMoveScaler = fMoveScaler; } + void SetNumberOfFramesToSmoothMouseData( _In_ int nFrames ) { if( nFrames > 0 ) m_fFramesToSmoothMouseData = ( float )nFrames; } + void SetResetCursorAfterMove( _In_ bool bResetCursorAfterMove ) { m_bResetCursorAfterMove = bResetCursorAfterMove; } // Functions to get state - D3DXMATRIX* GetViewMatrix() - { - //return &m_mView; - D3DXMatrixTranslation(&m_mShift, m_vMyKeyboardDirection.x, m_vMyKeyboardDirection.y, 0.0); - D3DXMatrixMultiply(&m_mShift, &m_mView, &m_mShift); - return &m_mShift; - } - const D3DXMATRIX* GetProjMatrix() const - { - return &m_mProj; - } - D3DXVECTOR3* GetEyePt() - { - D3DXMATRIX viewInv; - D3DXMatrixInverse(&viewInv, NULL, GetViewMatrix()); - D3DXVECTOR3 eyeview(0.0f, 0.0f, 0.0f); - D3DXVec3TransformCoord(&m_vEyeShift, &eyeview, &viewInv); - return &m_vEyeShift; - - // return &m_vEye; - } - D3DXVECTOR3* GetEyePtOrig() - { - return &m_vEye; - } - const D3DXVECTOR3* GetKeyboardVec() const { - return &m_vMyKeyboardDirection; - } - void SetKeyboardVec(D3DXVECTOR3& keyVec) { - m_vMyKeyboardDirection = keyVec; - } - const D3DXVECTOR3* GetLookAtPt() const - { - return &m_vLookAt; - } - float GetNearClip() const - { - return m_fNearPlane; - } - float GetFarClip() const - { - return m_fFarPlane; - } - float GetAspect() { - return m_fAspect; - } - - bool IsBeingDragged() const - { - return ( m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown ); - } - bool IsMouseLButtonDown() const - { - return m_bMouseLButtonDown; - } - bool IsMouseMButtonDown() const - { - return m_bMouseMButtonDown; - } - bool IsMouseRButtonDown() const - { - return m_bMouseRButtonDown; - } + DirectX::XMMATRIX GetViewMatrix() const { return DirectX::XMLoadFloat4x4( &m_mView ); } + DirectX::XMMATRIX GetProjMatrix() const { return DirectX::XMLoadFloat4x4( &m_mProj ); } + DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( &m_vEye ); } + DirectX::XMVECTOR GetLookAtPt() const { return DirectX::XMLoadFloat3( &m_vLookAt ); } + float GetNearClip() const { return m_fNearPlane; } + float GetFarClip() const { return m_fFarPlane; } + + bool IsBeingDragged() const { return ( m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown ); } + bool IsMouseLButtonDown() const { return m_bMouseLButtonDown; } + bool IsMouseMButtonDown() const { return m_bMouseMButtonDown; } + bool sMouseRButtonDown() const { return m_bMouseRButtonDown; } protected: // Functions to map a WM_KEYDOWN key to a D3DUtil_CameraKeys enum - virtual D3DUtil_CameraKeys MapKey( UINT nKey ); - bool IsKeyDown( BYTE key ) const - { - return( ( key & KEY_IS_DOWN_MASK ) == KEY_IS_DOWN_MASK ); - } - bool WasKeyDown( BYTE key ) const - { - return( ( key & KEY_WAS_DOWN_MASK ) == KEY_WAS_DOWN_MASK ); - } - - void ConstrainToBoundary( D3DXVECTOR3* pV ); - void UpdateMouseDelta(); - void UpdateVelocity( float fElapsedTime ); - void GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bGetGamepadInput, - bool bResetCursorAfterMove ); - - D3DXMATRIX m_mView; // View matrix - D3DXMATRIX m_mProj; // Projection matrix - D3DXMATRIX m_mShift; - - DXUT_GAMEPAD m_GamePad[DXUT_MAX_CONTROLLERS]; // XInput controller state - D3DXVECTOR3 m_vGamePadLeftThumb; - D3DXVECTOR3 m_vGamePadRightThumb; - double m_GamePadLastActive[DXUT_MAX_CONTROLLERS]; - - int m_cKeysDown; // Number of camera keys that are down. - BYTE m_aKeys[CAM_MAX_KEYS]; // State of input - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK - D3DXVECTOR3 m_vKeyboardDirection; // Direction vector of keyboard input - D3DXVECTOR3 m_vMyKeyboardDirection; - POINT m_ptLastMousePosition; // Last absolute position of mouse cursor - bool m_bMouseLButtonDown; // True if left button is down - bool m_bMouseMButtonDown; // True if middle button is down - bool m_bMouseRButtonDown; // True if right button is down - int m_nCurrentButtonMask; // mask of which buttons are down - int m_nMouseWheelDelta; // Amount of middle wheel scroll (+/-) - D3DXVECTOR2 m_vMouseDelta; // Mouse relative delta smoothed over a few frames - float m_fFramesToSmoothMouseData; // Number of frames to smooth mouse data over - - D3DXVECTOR3 m_vDefaultEye; // Default camera eye position - D3DXVECTOR3 m_vDefaultLookAt; // Default LookAt position - D3DXVECTOR3 m_vEye; // Camera eye position - D3DXVECTOR3 m_vEyeShift; // Camera eye after shift - D3DXVECTOR3 m_vLookAt; // LookAt position - float m_fCameraYawAngle; // Yaw angle of camera - float m_fCameraPitchAngle; // Pitch angle of camera - - RECT m_rcDrag; // Rectangle within which a drag can be initiated. - D3DXVECTOR3 m_vVelocity; // Velocity of camera - bool m_bMovementDrag; // If true, then camera movement will slow to a stop otherwise movement is instant - D3DXVECTOR3 m_vVelocityDrag; // Velocity drag force - FLOAT m_fDragTimer; // Countdown timer to apply drag - FLOAT m_fTotalDragTimeToZero; // Time it takes for velocity to go from full to 0 - D3DXVECTOR2 m_vRotVelocity; // Velocity of camera - - float m_fFOV; // Field of view - float m_fAspect; // Aspect ratio - float m_fNearPlane; // Near plane - float m_fFarPlane; // Far plane - - float m_fRotationScaler; // Scaler for rotation - float m_fMoveScaler; // Scaler for movement - - bool m_bInvertPitch; // Invert the pitch axis - bool m_bEnablePositionMovement; // If true, then the user can translate the camera/model - bool m_bEnableYAxisMovement; // If true, then camera can move in the y-axis - - bool m_bClipToBoundary; // If true, then the camera will be clipped to the boundary - D3DXVECTOR3 m_vMinBoundary; // Min point in clip boundary - D3DXVECTOR3 m_vMaxBoundary; // Max point in clip boundary - - bool m_bResetCursorAfterMove;// If true, the class will reset the cursor position so that the cursor always has space to move + virtual D3DUtil_CameraKeys MapKey( _In_ UINT nKey ); + + bool IsKeyDown( _In_ BYTE key ) const { return( ( key & KEY_IS_DOWN_MASK ) == KEY_IS_DOWN_MASK ); } + bool WasKeyDown( _In_ BYTE key ) const { return( ( key & KEY_WAS_DOWN_MASK ) == KEY_WAS_DOWN_MASK ); } + + DirectX::XMVECTOR ConstrainToBoundary( _In_ DirectX::FXMVECTOR v ) + { + using namespace DirectX; + + XMVECTOR vMin = XMLoadFloat3( &m_vMinBoundary ); + XMVECTOR vMax = XMLoadFloat3( &m_vMaxBoundary ); + + // Constrain vector to a bounding box + return XMVectorClamp( v, vMin, vMax ); + } + + void UpdateMouseDelta(); + void UpdateVelocity( _In_ float fElapsedTime ); + void GetInput( _In_ bool bGetKeyboardInput, _In_ bool bGetMouseInput, _In_ bool bGetGamepadInput ); + + DirectX::XMFLOAT4X4 m_mView; // View matrix + DirectX::XMFLOAT4X4 m_mProj; // Projection matrix + + DXUT_GAMEPAD m_GamePad[DXUT_MAX_CONTROLLERS]; // XInput controller state + DirectX::XMFLOAT3 m_vGamePadLeftThumb; + DirectX::XMFLOAT3 m_vGamePadRightThumb; + double m_GamePadLastActive[DXUT_MAX_CONTROLLERS]; + + int m_cKeysDown; // Number of camera keys that are down. + BYTE m_aKeys[CAM_MAX_KEYS]; // State of input - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK + DirectX::XMFLOAT3 m_vKeyboardDirection; // Direction vector of keyboard input + POINT m_ptLastMousePosition; // Last absolute position of mouse cursor + int m_nCurrentButtonMask; // mask of which buttons are down + int m_nMouseWheelDelta; // Amount of middle wheel scroll (+/-) + DirectX::XMFLOAT2 m_vMouseDelta; // Mouse relative delta smoothed over a few frames + float m_fFramesToSmoothMouseData; // Number of frames to smooth mouse data over + DirectX::XMFLOAT3 m_vDefaultEye; // Default camera eye position + DirectX::XMFLOAT3 m_vDefaultLookAt; // Default LookAt position + DirectX::XMFLOAT3 m_vEye; // Camera eye position + DirectX::XMFLOAT3 m_vLookAt; // LookAt position + float m_fCameraYawAngle; // Yaw angle of camera + float m_fCameraPitchAngle; // Pitch angle of camera + + RECT m_rcDrag; // Rectangle within which a drag can be initiated. + DirectX::XMFLOAT3 m_vVelocity; // Velocity of camera + DirectX::XMFLOAT3 m_vVelocityDrag; // Velocity drag force + float m_fDragTimer; // Countdown timer to apply drag + float m_fTotalDragTimeToZero; // Time it takes for velocity to go from full to 0 + DirectX::XMFLOAT2 m_vRotVelocity; // Velocity of camera + + float m_fFOV; // Field of view + float m_fAspect; // Aspect ratio + float m_fNearPlane; // Near plane + float m_fFarPlane; // Far plane + + float m_fRotationScaler; // Scaler for rotation + float m_fMoveScaler; // Scaler for movement + + bool m_bMouseLButtonDown; // True if left button is down + bool m_bMouseMButtonDown; // True if middle button is down + bool m_bMouseRButtonDown; // True if right button is down + bool m_bMovementDrag; // If true, then camera movement will slow to a stop otherwise movement is instant + bool m_bInvertPitch; // Invert the pitch axis + bool m_bEnablePositionMovement; // If true, then the user can translate the camera/model + bool m_bEnableYAxisMovement; // If true, then camera can move in the y-axis + bool m_bClipToBoundary; // If true, then the camera will be clipped to the boundary + bool m_bResetCursorAfterMove; // If true, the class will reset the cursor position so that the cursor always has space to move + + DirectX::XMFLOAT3 m_vMinBoundary; // Min point in clip boundary + DirectX::XMFLOAT3 m_vMaxBoundary; // Max point in clip boundary }; @@ -327,41 +271,26 @@ class CBaseCamera class CFirstPersonCamera : public CBaseCamera { public: - CFirstPersonCamera(); + CFirstPersonCamera() noexcept; // Call these from client and use Get*Matrix() to read new matrices - virtual void FrameMove( FLOAT fElapsedTime ); + virtual void FrameMove( _In_ float fElapsedTime ) override; // Functions to change behavior - void SetRotateButtons( bool bLeft, bool bMiddle, bool bRight, bool bRotateWithoutButtonDown = false ); + void SetRotateButtons( _In_ bool bLeft, _In_ bool bMiddle, _In_ bool bRight, _In_ bool bRotateWithoutButtonDown = false ); // Functions to get state - D3DXMATRIX* GetWorldMatrix() - { - return &m_mCameraWorld; - } + DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mCameraWorld ); } - const D3DXVECTOR3* GetWorldRight() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._11; - } - const D3DXVECTOR3* GetWorldUp() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._21; - } - const D3DXVECTOR3* GetWorldAhead() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._31; - } - const D3DXVECTOR3* GetEyePt() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._41; - } + DirectX::XMVECTOR GetWorldRight() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._11 ) ); } + DirectX::XMVECTOR GetWorldUp() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._21 ) ); } + DirectX::XMVECTOR GetWorldAhead() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._31 ) ); } + DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._41 ) ); } protected: - D3DXMATRIX m_mCameraWorld; // World matrix of the camera (inverse of the view matrix) + DirectX::XMFLOAT4X4 m_mCameraWorld; // World matrix of the camera (inverse of the view matrix) - int m_nActiveButtonMask; // Mask to determine which button to enable for rotation + int m_nActiveButtonMask; // Mask to determine which button to enable for rotation bool m_bRotateWithoutButtonDown; }; @@ -372,79 +301,61 @@ class CFirstPersonCamera : public CBaseCamera class CModelViewerCamera : public CBaseCamera { public: - CModelViewerCamera(); + CModelViewerCamera() noexcept; // Call these from client and use Get*Matrix() to read new matrices - virtual LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual void FrameMove( FLOAT fElapsedTime ); - + virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void FrameMove( _In_ float fElapsedTime ) override; // Functions to change behavior - virtual void SetDragRect( RECT& rc ); - void Reset(); - void SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ); - void SetButtonMasks( int nRotateModelButtonMask = MOUSE_LEFT_BUTTON, int nZoomButtonMask = MOUSE_WHEEL, - int nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON ) + virtual void SetDragRect( _In_ const RECT& rc ) override; + virtual void Reset() override; + virtual void SetViewParams( _In_ DirectX::FXMVECTOR pvEyePt, _In_ DirectX::FXMVECTOR pvLookatPt ) override; + void SetButtonMasks( _In_ int nRotateModelButtonMask = MOUSE_LEFT_BUTTON, _In_ int nZoomButtonMask = MOUSE_WHEEL, + _In_ int nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON ) { m_nRotateModelButtonMask = nRotateModelButtonMask, m_nZoomButtonMask = nZoomButtonMask; m_nRotateCameraButtonMask = nRotateCameraButtonMask; } - void SetAttachCameraToModel( bool bEnable = false ) - { - m_bAttachCameraToModel = bEnable; - } - void SetWindow( int nWidth, int nHeight, float fArcballRadius=0.9f ) + void SetAttachCameraToModel( _In_ bool bEnable = false ) { m_bAttachCameraToModel = bEnable; } + void SetWindow( _In_ int nWidth, _In_ int nHeight, _In_ float fArcballRadius=0.9f ) { m_WorldArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); m_ViewArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); } - void SetRadius( float fDefaultRadius=5.0f, float fMinRadius=1.0f, float fMaxRadius=FLT_MAX ) + void SetRadius( _In_ float fDefaultRadius=5.0f, _In_ float fMinRadius=1.0f, _In_ float fMaxRadius=FLT_MAX ) { m_fDefaultRadius = m_fRadius = fDefaultRadius; m_fMinRadius = fMinRadius; m_fMaxRadius = fMaxRadius; m_bDragSinceLastUpdate = true; } - void SetModelCenter( D3DXVECTOR3 vModelCenter ) - { - m_vModelCenter = vModelCenter; - } - void SetLimitPitch( bool bLimitPitch ) + void SetModelCenter( _In_ const DirectX::XMFLOAT3& vModelCenter ) { m_vModelCenter = vModelCenter; } + void SetLimitPitch( _In_ bool bLimitPitch ) { m_bLimitPitch = bLimitPitch; } + void SetViewQuat( _In_ DirectX::FXMVECTOR q ) { - m_bLimitPitch = bLimitPitch; - } - - D3DXQUATERNION GetWorldQuat() { - return m_WorldArcBall.GetQuatNow(); - } - D3DXQUATERNION GetViewQuat() { - return m_ViewArcBall.GetQuatNow(); - } - - void SetViewQuat( D3DXQUATERNION q ) - { - m_ViewArcBall.SetQuatNow( q ); m_bDragSinceLastUpdate = true; + m_ViewArcBall.SetQuatNow( q ); + m_bDragSinceLastUpdate = true; } - void SetWorldQuat( D3DXQUATERNION q ) + void SetWorldQuat( _In_ DirectX::FXMVECTOR q ) { - m_WorldArcBall.SetQuatNow( q ); m_bDragSinceLastUpdate = true; + m_WorldArcBall.SetQuatNow( q ); + m_bDragSinceLastUpdate = true; } // Functions to get state - const D3DXMATRIX* GetWorldMatrix() const + DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mWorld ); } + void SetWorldMatrix( _In_ DirectX::CXMMATRIX mWorld ) { - return &m_mWorld; - } - void SetWorldMatrix( D3DXMATRIX& mWorld ) - { - m_mWorld = mWorld; m_bDragSinceLastUpdate = true; + XMStoreFloat4x4( &m_mWorld, mWorld ); + m_bDragSinceLastUpdate = true; } protected: CD3DArcBall m_WorldArcBall; CD3DArcBall m_ViewArcBall; - D3DXVECTOR3 m_vModelCenter; - D3DXMATRIX m_mModelLastRot; // Last arcball rotation matrix for model - D3DXMATRIX m_mModelRot; // Rotation matrix of model - D3DXMATRIX m_mWorld; // World matrix of model + DirectX::XMFLOAT3 m_vModelCenter; + DirectX::XMFLOAT4X4 m_mModelLastRot; // Last arcball rotation matrix for model + DirectX::XMFLOAT4X4 m_mModelRot; // Rotation matrix of model + DirectX::XMFLOAT4X4 m_mWorld; // World matrix of model int m_nRotateModelButtonMask; int m_nZoomButtonMask; @@ -452,18 +363,16 @@ class CModelViewerCamera : public CBaseCamera bool m_bAttachCameraToModel; bool m_bLimitPitch; - float m_fRadius; // Distance from the camera to model - float m_fDefaultRadius; // Distance from the camera to model - float m_fMinRadius; // Min radius - float m_fMaxRadius; // Max radius - bool m_bDragSinceLastUpdate; // True if mouse drag has happened since last time FrameMove is called. - - D3DXMATRIX m_mCameraRotLast; - - int m_ptLastMouseX; + bool m_bDragSinceLastUpdate; // True if mouse drag has happened since last time FrameMove is called. + float m_fRadius; // Distance from the camera to model + float m_fDefaultRadius; // Distance from the camera to model + float m_fMinRadius; // Min radius + float m_fMaxRadius; // Max radius + DirectX::XMFLOAT4X4 m_mCameraRotLast; }; + //-------------------------------------------------------------------------------------- // Manages the mesh, direction, mouse events of a directional arrow that // rotates around a radius controlled by an arcball @@ -471,82 +380,43 @@ class CModelViewerCamera : public CBaseCamera class CDXUTDirectionWidget { public: - CDXUTDirectionWidget(); - - static HRESULT WINAPI StaticOnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnD3D9ResetDevice( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ); - HRESULT OnRender9( D3DXCOLOR color, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj, - const D3DXVECTOR3* pEyePt ); - LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - static void WINAPI StaticOnD3D9LostDevice(); - static void WINAPI StaticOnD3D9DestroyDevice(); - - static HRESULT WINAPI StaticOnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ); - HRESULT OnRender11( D3DXCOLOR color, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj, - const D3DXVECTOR3* pEyePt ); - static void WINAPI StaticOnD3D11DestroyDevice(); - - D3DXVECTOR3 GetLightDirection() + CDXUTDirectionWidget() noexcept; + + LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); + + HRESULT OnRender( _In_ DirectX::FXMVECTOR color, _In_ DirectX::CXMMATRIX pmView, _In_ DirectX::CXMMATRIX pmProj, _In_ DirectX::FXMVECTOR vEyePt ); + + DirectX::XMVECTOR GetLightDirection() const { return DirectX::XMLoadFloat3( &m_vCurrentDir ); } + void SetLightDirection( _In_ DirectX::FXMVECTOR vDir ) { - return m_vCurrentDir; - }; - void SetLightDirection( D3DXVECTOR3 vDir ) + DirectX::XMStoreFloat3( &m_vCurrentDir, vDir ); + m_vDefaultDir = m_vCurrentDir; + } + void SetLightDirection( _In_ DirectX::XMFLOAT3 vDir ) { m_vDefaultDir = m_vCurrentDir = vDir; - }; - void SetButtonMask( int nRotate = MOUSE_RIGHT_BUTTON ) - { - m_nRotateMask = nRotate; } + void SetButtonMask( _In_ int nRotate = MOUSE_RIGHT_BUTTON ) { m_nRotateMask = nRotate; } - float GetRadius() - { - return m_fRadius; - }; - void SetRadius( float fRadius ) - { - m_fRadius = fRadius; - }; + float GetRadius() const { return m_fRadius; } + void SetRadius( _In_ float fRadius ) { m_fRadius = fRadius; } - bool IsBeingDragged() - { - return m_ArcBall.IsBeingDragged(); - }; + bool IsBeingDragged() { return m_ArcBall.IsBeingDragged(); } + + static HRESULT WINAPI StaticOnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext ); + static void WINAPI StaticOnD3D11DestroyDevice(); protected: - HRESULT UpdateLightDir(); - - // D3D9 objects - static IDirect3DDevice9* s_pd3d9Device; - static ID3DXEffect* s_pD3D9Effect; - static ID3DXMesh* s_pD3D9Mesh; - static D3DXHANDLE s_hRenderWith1LightNoTexture; - static D3DXHANDLE s_hMaterialDiffuseColor; - static D3DXHANDLE s_hLightDir; - static D3DXHANDLE s_hWorldViewProjection; - static D3DXHANDLE s_hWorld; - - // D3D10 objects - //static ID3D10Device* s_pd3d10Device; - //static ID3D10Effect* s_pD3D10Effect; - //TODO: add some sort of d3d10 mesh object here - //static ID3D10InputLayout* s_pVertexLayout; - //static ID3D10EffectTechnique* s_pRenderTech; - //static ID3D10EffectVectorVariable* g_pMaterialDiffuseColor; - //static ID3D10EffectVectorVariable* g_pLightDir; - //static ID3D10EffectMatrixVariable* g_pmWorld; - //static ID3D10EffectMatrixVariable* g_pmWorldViewProjection; - - D3DXMATRIXA16 m_mRot; - D3DXMATRIXA16 m_mRotSnapshot; + HRESULT UpdateLightDir(); + + // TODO - need support for Direct3D 11 widget + + DirectX::XMFLOAT4X4 m_mRot; + DirectX::XMFLOAT4X4 m_mRotSnapshot; float m_fRadius; int m_nRotateMask; CD3DArcBall m_ArcBall; - D3DXVECTOR3 m_vDefaultDir; - D3DXVECTOR3 m_vCurrentDir; - D3DXMATRIX m_mView; + DirectX::XMFLOAT3 m_vDefaultDir; + DirectX::XMFLOAT3 m_vCurrentDir; + DirectX::XMFLOAT4X4 m_mView; }; - - - -#endif diff --git a/FriedLiver/Source/DXUT/Optional/DXUTgui.cpp b/FriedLiver/Source/DXUT/Optional/DXUTgui.cpp index 4faaae6c..2d223b98 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTgui.cpp +++ b/FriedLiver/Source/DXUT/Optional/DXUTgui.cpp @@ -2,6 +2,9 @@ // File: DXUTgui.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTgui.h" @@ -10,8 +13,9 @@ #include "SDKMisc.h" -#undef min // use __min instead -#undef max // use __max instead +#include "DDSTextureLoader.h" + +using namespace DirectX; #ifndef WM_XBUTTONDOWN #define WM_XBUTTONDOWN 0x020B // (not always defined) @@ -38,28 +42,14 @@ #define DXUT_MAX_GUI_SPRITES 500 -D3DCOLORVALUE D3DCOLOR_TO_D3DCOLORVALUE( D3DCOLOR c ) +inline DirectX::XMFLOAT4 D3DCOLOR_TO_D3DCOLORVALUE( DWORD c ) { - D3DCOLORVALUE cv = - { - ( ( c >> 16 ) & 0xFF ) / 255.0f, - ( ( c >> 8 ) & 0xFF ) / 255.0f, - ( c & 0xFF ) / 255.0f, - ( ( c >> 24 ) & 0xFF ) / 255.0f - }; - return cv; + return DirectX::XMFLOAT4 ( ( ( c >> 16 ) & 0xFF ) / 255.0f, + ( ( c >> 8 ) & 0xFF ) / 255.0f, + ( c & 0xFF ) / 255.0f, + ( ( c >> 24 ) & 0xFF ) / 255.0f ); } -#define UNISCRIBE_DLLNAME L"usp10.dll" - -#define GETPROCADDRESS( Module, APIName, Temp ) \ - Temp = GetProcAddress( Module, #APIName ); \ - if( Temp ) \ - *(FARPROC*)&_##APIName = Temp - -#define PLACEHOLDERPROC( APIName ) \ - _##APIName = Dummy_##APIName - #define IMM32_DLLNAME L"imm32.dll" #define VER_DLLNAME L"version.dll" @@ -164,44 +154,36 @@ const UINT g_uUIEffectFileSize = sizeof( g_strUIEffectFile ); // DXUT_MAX_EDITBOXLENGTH is the maximum string length allowed in edit boxes, -// including the NULL terminator. +// including the nul terminator. // // Uniscribe does not support strings having bigger-than-16-bits length. // This means that the string must be less than 65536 characters long, -// including the NULL terminator. +// including the nul terminator. #define DXUT_MAX_EDITBOXLENGTH 0xFFFF double CDXUTDialog::s_fTimeRefresh = 0.0f; -CDXUTControl* CDXUTDialog::s_pControlFocus = NULL; // The control which has focus -CDXUTControl* CDXUTDialog::s_pControlPressed = NULL; // The control currently pressed +CDXUTControl* CDXUTDialog::s_pControlFocus = nullptr; // The control which has focus +CDXUTControl* CDXUTDialog::s_pControlPressed = nullptr; // The control currently pressed struct DXUT_SCREEN_VERTEX { float x, y, z, h; - D3DCOLOR color; + DWORD color; float tu, tv; - - static DWORD FVF; }; -DWORD DXUT_SCREEN_VERTEX::FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1; - struct DXUT_SCREEN_VERTEX_UNTEX { float x, y, z, h; - D3DCOLOR color; - - static DWORD FVF; + DWORD color; }; -DWORD DXUT_SCREEN_VERTEX_UNTEX::FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE; - struct DXUT_SCREEN_VERTEX_10 { float x, y, z; - D3DCOLORVALUE color; + DirectX::XMFLOAT4 color; float tu, tv; }; @@ -216,72 +198,259 @@ inline int RectHeight( RECT& rc ) } -HRESULT InitFont11( ID3D11Device* pd3d11Device, ID3D11InputLayout* pInputLayout ); -void EndFont11(); +//====================================================================================== +// Font11 +//====================================================================================== + +ID3D11Buffer* g_pFontBuffer11 = nullptr; +UINT g_FontBufferBytes11 = 0; +std::vector g_FontVertices; +ID3D11ShaderResourceView* g_pFont11 = nullptr; +ID3D11InputLayout* g_pInputLayout11 = nullptr; //-------------------------------------------------------------------------------------- -// CDXUTDialog class +HRESULT InitFont11( _In_ ID3D11Device* pd3d11Device, _In_ ID3D11InputLayout* pInputLayout ) +{ + HRESULT hr = S_OK; + WCHAR str[MAX_PATH]; + V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"UI\\Font.dds" ) ); + + V_RETURN( CreateDDSTextureFromFile( pd3d11Device, str, nullptr, &g_pFont11 ) ); + + g_pInputLayout11 = pInputLayout; + return hr; +} + + +//-------------------------------------------------------------------------------------- +void EndFont11() +{ + SAFE_RELEASE( g_pFontBuffer11 ); + g_FontBufferBytes11 = 0; + SAFE_RELEASE( g_pFont11 ); +} + + //-------------------------------------------------------------------------------------- +void BeginText11() +{ + g_FontVertices.clear(); +} + //-------------------------------------------------------------------------------------- -CDXUTDialog::CDXUTDialog() +_Use_decl_annotations_ +void DrawText11DXUT( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, + LPCWSTR strText, const RECT& rcScreen, DirectX::XMFLOAT4 vFontColor, + float fBBWidth, float fBBHeight, bool bCenter ) { - m_x = 0; - m_y = 0; - m_width = 0; - m_height = 0; + float fCharTexSizeX = 0.010526315f; + //float fGlyphSizeX = 14.0f / fBBWidth; + //float fGlyphSizeY = 32.0f / fBBHeight; + float fGlyphSizeX = 15.0f / fBBWidth; + float fGlyphSizeY = 42.0f / fBBHeight; - m_pManager = NULL; - m_bVisible = true; - m_bCaption = false; - m_bMinimized = false; - m_bDrag = false; - m_wszCaption[0] = L'\0'; - m_nCaptionHeight = 18; - m_colorTopLeft = 0; - m_colorTopRight = 0; - m_colorBottomLeft = 0; - m_colorBottomRight = 0; + float fRectLeft = rcScreen.left / fBBWidth; + float fRectTop = 1.0f - rcScreen.top / fBBHeight; + + fRectLeft = fRectLeft * 2.0f - 1.0f; + fRectTop = fRectTop * 2.0f - 1.0f; + + int NumChars = (int)wcslen( strText ); + if (bCenter) { + float fRectRight = rcScreen.right / fBBWidth; + fRectRight = fRectRight * 2.0f - 1.0f; + float fRectBottom = 1.0f - rcScreen.bottom / fBBHeight; + fRectBottom = fRectBottom * 2.0f - 1.0f; + float fcenterx = ((fRectRight - fRectLeft) - (float)NumChars*fGlyphSizeX) *0.5f; + float fcentery = ((fRectTop - fRectBottom) - (float)1*fGlyphSizeY) *0.5f; + fRectLeft += fcenterx ; + fRectTop -= fcentery; + } + float fOriginalLeft = fRectLeft; + float fTexTop = 0.0f; + float fTexBottom = 1.0f; + + float fDepth = 0.5f; + for( int i=0; i 126 ) + { + continue; + } + + // Add 6 sprite vertices + DXUTSpriteVertex SpriteVertex = {}; + float fRectRight = fRectLeft + fGlyphSizeX; + float fRectBottom = fRectTop - fGlyphSizeY; + float fTexLeft = ( strText[i] - 32 ) * fCharTexSizeX; + float fTexRight = fTexLeft + fCharTexSizeX; + + // tri1 + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectLeft, fRectTop, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexLeft, fTexTop ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); + + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexRight, fTexTop ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); + + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexLeft, fTexBottom ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); + + // tri2 + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexRight, fTexTop ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); + + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectRight, fRectBottom, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexRight, fTexBottom ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); + + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexLeft, fTexBottom ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); + + fRectLeft += fGlyphSizeX; + + } + + // We have to end text after every line so that rendering order between sprites and fonts is preserved + EndText11( pd3dDevice, pd3d11DeviceContext ); +} + +_Use_decl_annotations_ +void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) +{ + if ( g_FontVertices.empty() ) + return; + + // ensure our buffer size can hold our sprites + UINT FontDataBytes = static_cast( g_FontVertices.size() * sizeof( DXUTSpriteVertex ) ); + if( g_FontBufferBytes11 < FontDataBytes ) + { + SAFE_RELEASE( g_pFontBuffer11 ); + g_FontBufferBytes11 = FontDataBytes; + + D3D11_BUFFER_DESC BufferDesc; + BufferDesc.ByteWidth = g_FontBufferBytes11; + BufferDesc.Usage = D3D11_USAGE_DYNAMIC; + BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + BufferDesc.MiscFlags = 0; + + if (FAILED(pd3dDevice->CreateBuffer(&BufferDesc, nullptr, &g_pFontBuffer11))) + { + g_pFontBuffer11 = nullptr; + g_FontBufferBytes11 = 0; + return; + } + DXUT_SetDebugName( g_pFontBuffer11, "DXUT Text11" ); + } + + // Copy the sprites over + D3D11_BOX destRegion; + destRegion.left = 0; + destRegion.right = FontDataBytes; + destRegion.top = 0; + destRegion.bottom = 1; + destRegion.front = 0; + destRegion.back = 1; + D3D11_MAPPED_SUBRESOURCE MappedResource; + if ( S_OK == pd3d11DeviceContext->Map( g_pFontBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) + { + memcpy( MappedResource.pData, (void*)&g_FontVertices[0], FontDataBytes ); + pd3d11DeviceContext->Unmap(g_pFontBuffer11, 0); + } + + ID3D11ShaderResourceView* pOldTexture = nullptr; + pd3d11DeviceContext->PSGetShaderResources( 0, 1, &pOldTexture ); + pd3d11DeviceContext->PSSetShaderResources( 0, 1, &g_pFont11 ); - m_pCallbackEvent = NULL; - m_pCallbackEventUserContext = NULL; + // Draw + UINT Stride = sizeof( DXUTSpriteVertex ); + UINT Offset = 0; + pd3d11DeviceContext->IASetVertexBuffers( 0, 1, &g_pFontBuffer11, &Stride, &Offset ); + pd3d11DeviceContext->IASetInputLayout( g_pInputLayout11 ); + pd3d11DeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); + pd3d11DeviceContext->Draw( static_cast( g_FontVertices.size() ), 0 ); - m_fTimeLastRefresh = 0; + pd3d11DeviceContext->PSSetShaderResources( 0, 1, &pOldTexture ); + SAFE_RELEASE( pOldTexture ); - m_pControlMouseOver = NULL; + g_FontVertices.clear(); +} - m_pNextDialog = this; - m_pPrevDialog = this; - m_nDefaultControlID = 0xffff; - m_bNonUserEvents = false; - m_bKeyboardInput = false; - m_bMouseInput = true; +//====================================================================================== +// CDXUTDialog class +//====================================================================================== + +CDXUTDialog::CDXUTDialog() noexcept : + m_bNonUserEvents(false), + m_bKeyboardInput(false), + m_bMouseInput(true), + m_nDefaultControlID(0xffff), + m_fTimeLastRefresh(0), + m_pControlMouseOver(nullptr), + m_bVisible(true), + m_bCaption(false), + m_bMinimized(false), + m_bDrag(false), + m_wszCaption{}, + m_x( 0 ), + m_y( 0 ), + m_width( 0 ), + m_height( 0 ), + m_nCaptionHeight(18), + m_colorTopLeft(0), + m_colorTopRight(0), + m_colorBottomLeft(0), + m_colorBottomRight(0), + m_pManager( nullptr ), + m_pCallbackEvent( nullptr ), + m_pCallbackEventUserContext( nullptr ), + m_CapElement{}, + m_pNextDialog(this), + m_pPrevDialog(this) +{ } //-------------------------------------------------------------------------------------- CDXUTDialog::~CDXUTDialog() { - int i = 0; - RemoveAllControls(); - m_Fonts.RemoveAll(); - m_Textures.RemoveAll(); + m_Fonts.clear(); + m_Textures.clear(); - for( i = 0; i < m_DefaultElements.GetSize(); i++ ) + for( auto it = m_DefaultElements.begin(); it != m_DefaultElements.end(); ++it ) { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - SAFE_DELETE( pElementHolder ); + SAFE_DELETE( *it ); } - m_DefaultElements.RemoveAll(); + m_DefaultElements.clear(); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog ) { m_pManager = pManager; @@ -294,6 +463,7 @@ void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDial //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, LPCWSTR pszControlTextureFilename ) { m_pManager = pManager; @@ -305,6 +475,7 @@ void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDial //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, LPCWSTR szControlTextureResourceName, HMODULE hControlTextureResourceModule ) { @@ -318,13 +489,14 @@ void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDial //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTDialog::SetCallback( PCALLBACKDXUTGUIEVENT pCallback, void* pUserContext ) { // If this assert triggers, you need to call CDXUTDialog::Init() first. This change // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The // creation and interfacing with CDXUTDialogResourceManager is now the responsibility // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix call CDXUTDialog::Init() first. See comments for details." ); + assert( m_pManager && L"To fix call CDXUTDialog::Init() first. See comments for details." ); m_pCallbackEvent = pCallback; m_pCallbackEventUserContext = pUserContext; @@ -332,26 +504,25 @@ void CDXUTDialog::SetCallback( PCALLBACKDXUTGUIEVENT pCallback, void* pUserConte //-------------------------------------------------------------------------------------- -void CDXUTDialog::RemoveControl( int ID ) +void CDXUTDialog::RemoveControl( _In_ int ID ) { - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - if( pControl->GetID() == ID ) + if( (*it)->GetID() == ID ) { // Clean focus first ClearFocus(); // Clear references to this control - if( s_pControlFocus == pControl ) - s_pControlFocus = NULL; - if( s_pControlPressed == pControl ) - s_pControlPressed = NULL; - if( m_pControlMouseOver == pControl ) - m_pControlMouseOver = NULL; + if( s_pControlFocus == (*it) ) + s_pControlFocus = nullptr; + if( s_pControlPressed == (*it) ) + s_pControlPressed = nullptr; + if( m_pControlMouseOver == (*it) ) + m_pControlMouseOver = nullptr; - SAFE_DELETE( pControl ); - m_Controls.Remove( i ); + SAFE_DELETE( (*it) ); + m_Controls.erase( it ); return; } @@ -363,1063 +534,274 @@ void CDXUTDialog::RemoveControl( int ID ) void CDXUTDialog::RemoveAllControls() { if( s_pControlFocus && s_pControlFocus->m_pDialog == this ) - s_pControlFocus = NULL; + s_pControlFocus = nullptr; if( s_pControlPressed && s_pControlPressed->m_pDialog == this ) - s_pControlPressed = NULL; - m_pControlMouseOver = NULL; + s_pControlPressed = nullptr; + m_pControlMouseOver = nullptr; - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - SAFE_DELETE( pControl ); + SAFE_DELETE( *it ); } - m_Controls.RemoveAll(); + m_Controls.clear(); } //-------------------------------------------------------------------------------------- -CDXUTDialogResourceManager::CDXUTDialogResourceManager() +void CDXUTDialog::Refresh() { - // Begin D3D9-specific - m_pd3d9Device = NULL; - m_pStateBlock = NULL; - m_pSprite = NULL; - - // Begin D3D11-specific - // Shaders - m_pVSRenderUI11 = NULL; - m_pPSRenderUI11 = NULL; - m_pPSRenderUIUntex11 = NULL; - - // States - m_pDepthStencilStateUI11 = NULL; - m_pRasterizerStateUI11 = NULL; - m_pBlendStateUI11 = NULL; - m_pSamplerStateUI11 = NULL; - m_pDepthStencilStateStored11 = NULL; - m_pRasterizerStateStored11 = NULL; - m_pBlendStateStored11 = NULL; - m_pSamplerStateStored11 = NULL; - - m_pInputLayout11 = NULL; - m_pVBScreenQuad11 = NULL; - m_pSpriteBuffer11 = NULL; -} + if( s_pControlFocus ) + s_pControlFocus->OnFocusOut(); + if( m_pControlMouseOver ) + m_pControlMouseOver->OnMouseLeave(); -//-------------------------------------------------------------------------------------- -CDXUTDialogResourceManager::~CDXUTDialogResourceManager() -{ - int i; - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - SAFE_DELETE( pFontNode ); - } - m_FontCache.RemoveAll(); + s_pControlFocus = nullptr; + s_pControlPressed = nullptr; + m_pControlMouseOver = nullptr; - for( i = 0; i < m_TextureCache.GetSize(); i++ ) + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - SAFE_DELETE( pTextureNode ); + (*it)->Refresh(); } - m_TextureCache.RemoveAll(); - CUniBuffer::Uninitialize(); + if( m_bKeyboardInput ) + FocusDefaultControl(); } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::OnD3D9CreateDevice( LPDIRECT3DDEVICE9 pd3dDevice ) +HRESULT CDXUTDialog::OnRender( _In_ float fElapsedTime ) { - HRESULT hr = S_OK; - int i = 0; - - m_pd3d9Device = pd3dDevice; - - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - hr = CreateFont9( i ); - if( FAILED( hr ) ) - return hr; - } + // If this assert triggers, you need to call CDXUTDialogResourceManager::On*Device() from inside + // the application's device callbacks. See the SDK samples for an example of how to do this. + assert( m_pManager->GetD3D11Device() && + L"To fix hook up CDXUTDialogResourceManager to device callbacks. See comments for details" ); - for( i = 0; i < m_TextureCache.GetSize(); i++ ) + // See if the dialog needs to be refreshed + if( m_fTimeLastRefresh < s_fTimeRefresh ) { - hr = CreateTexture9( i ); - if( FAILED( hr ) ) - return hr; + m_fTimeLastRefresh = DXUTGetTime(); + Refresh(); } - hr = D3DXCreateSprite( pd3dDevice, &m_pSprite ); - if( FAILED( hr ) ) - return DXUT_ERR( L"D3DXCreateSprite", hr ); - - return S_OK; -} + // For invisible dialog, out now. + if( !m_bVisible || + ( m_bMinimized && !m_bCaption ) ) + return S_OK; + auto pd3dDevice = m_pManager->GetD3D11Device(); + auto pd3dDeviceContext = m_pManager->GetD3D11DeviceContext(); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::OnD3D9ResetDevice() -{ - HRESULT hr = S_OK; + // Set up a state block here and restore it when finished drawing all the controls + m_pManager->StoreD3D11State( pd3dDeviceContext ); - for( int i = 0; i < m_FontCache.GetSize(); i++ ) + BOOL bBackgroundIsVisible = ( m_colorTopLeft | m_colorTopRight | m_colorBottomRight | m_colorBottomLeft ) & 0xff000000; + if( !m_bMinimized && bBackgroundIsVisible ) { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); + // Convert the draw rectangle from screen coordinates to clip space coordinates. + float Left, Right, Top, Bottom; + Left = m_x * 2.0f / m_pManager->m_nBackBufferWidth - 1.0f; + Right = ( m_x + m_width ) * 2.0f / m_pManager->m_nBackBufferWidth - 1.0f; + Top = 1.0f - m_y * 2.0f / m_pManager->m_nBackBufferHeight; + Bottom = 1.0f - ( m_y + m_height ) * 2.0f / m_pManager->m_nBackBufferHeight; - if( pFontNode->pFont9 ) - pFontNode->pFont9->OnResetDevice(); - } + DXUT_SCREEN_VERTEX_10 vertices[4] = + { + Left, Top, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorTopLeft ), 0.0f, 0.0f, + Right, Top, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorTopRight ), 1.0f, 0.0f, + Left, Bottom, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorBottomLeft ), 0.0f, 1.0f, + Right, Bottom, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorBottomRight ), 1.0f, 1.0f, + }; - if( m_pSprite ) - m_pSprite->OnResetDevice(); + //DXUT_SCREEN_VERTEX_10 *pVB; + D3D11_MAPPED_SUBRESOURCE MappedData; + if( SUCCEEDED( pd3dDeviceContext->Map( m_pManager->m_pVBScreenQuad11, 0, D3D11_MAP_WRITE_DISCARD, + 0, &MappedData ) ) ) + { + memcpy( MappedData.pData, vertices, sizeof( vertices ) ); + pd3dDeviceContext->Unmap( m_pManager->m_pVBScreenQuad11, 0 ); + } - V_RETURN( m_pd3d9Device->CreateStateBlock( D3DSBT_ALL, &m_pStateBlock ) ); + // Set the quad VB as current + UINT stride = sizeof( DXUT_SCREEN_VERTEX_10 ); + UINT offset = 0; + pd3dDeviceContext->IASetVertexBuffers( 0, 1, &m_pManager->m_pVBScreenQuad11, &stride, &offset ); + pd3dDeviceContext->IASetInputLayout( m_pManager->m_pInputLayout11 ); + pd3dDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); - return S_OK; -} + // Setup for rendering + m_pManager->ApplyRenderUIUntex11( pd3dDeviceContext ); + pd3dDeviceContext->Draw( 4, 0 ); + } -//-------------------------------------------------------------------------------------- -bool CDXUTDialogResourceManager::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) -{ - return false; -} + auto pTextureNode = GetTexture( 0 ); + pd3dDeviceContext->PSSetShaderResources( 0, 1, &pTextureNode->pTexResView11 ); + // Sort depth back to front + m_pManager->BeginSprites11(); + BeginText11(); -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D9LostDevice() -{ - for( int i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); + m_pManager->ApplyRenderUI11( pd3dDeviceContext ); - if( pFontNode->pFont9 ) - pFontNode->pFont9->OnLostDevice(); + // Render the caption if it's enabled. + if( m_bCaption ) + { + // DrawSprite will offset the rect down by + // m_nCaptionHeight, so adjust the rect higher + // here to negate the effect. + RECT rc = { 0, -m_nCaptionHeight, m_width, 0 }; + DrawSprite( &m_CapElement, &rc, 0.99f ); + rc.left += 5; // Make a left margin + WCHAR wszOutput[256]; + wcscpy_s( wszOutput, 256, m_wszCaption ); + if( m_bMinimized ) + wcscat_s( wszOutput, 256, L" (Minimized)" ); + DrawText( wszOutput, &m_CapElement, &rc, true ); } - if( m_pSprite ) - m_pSprite->OnLostDevice(); - - SAFE_RELEASE( m_pStateBlock ); -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D9DestroyDevice() -{ - int i = 0; + // If the dialog is minimized, skip rendering + // its controls. + if( !m_bMinimized ) + { + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) + { + // Focused control is drawn last + if( *it == s_pControlFocus ) + continue; - m_pd3d9Device = NULL; + (*it)->Render( fElapsedTime ); + } - // Release the resources but don't clear the cache, as these will need to be - // recreated if the device is recreated - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - SAFE_RELEASE( pFontNode->pFont9 ); + if( s_pControlFocus && s_pControlFocus->m_pDialog == this ) + s_pControlFocus->Render( fElapsedTime ); } - for( i = 0; i < m_TextureCache.GetSize(); i++ ) + // End sprites + if( m_bCaption ) { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - SAFE_RELEASE( pTextureNode->pTexture9 ); + m_pManager->EndSprites11( pd3dDevice, pd3dDeviceContext ); + EndText11( pd3dDevice, pd3dDeviceContext ); } + m_pManager->RestoreD3D11State( pd3dDeviceContext ); - SAFE_RELEASE( m_pSprite ); + return S_OK; } - -HRESULT CDXUTDialogResourceManager::OnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +VOID CDXUTDialog::SendEvent( UINT nEvent, bool bTriggeredByUser, CDXUTControl* pControl ) { - m_pd3d11Device = pd3dDevice; - m_pd3d11DeviceContext = pd3d11DeviceContext; - - HRESULT hr = S_OK; - - // Compile Shaders - ID3DBlob* pVSBlob = NULL; - ID3DBlob* pPSBlob = NULL; - ID3DBlob* pPSUntexBlob = NULL; - V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", NULL, NULL, "VS", "vs_4_0_level_9_1", - D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pVSBlob, NULL ) ); - V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", NULL, NULL, "PS", "ps_4_0_level_9_1", - D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSBlob, NULL ) ); - V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", NULL, NULL, "PSUntex", "ps_4_0_level_9_1", - D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSUntexBlob, NULL ) ); - - // Create Shaders - V_RETURN( pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &m_pVSRenderUI11 ) ); - DXUT_SetDebugName( m_pVSRenderUI11, "CDXUTDialogResourceManager" ); - - V_RETURN( pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &m_pPSRenderUI11 ) ); - DXUT_SetDebugName( m_pPSRenderUI11, "CDXUTDialogResourceManager" ); - - V_RETURN( pd3dDevice->CreatePixelShader( pPSUntexBlob->GetBufferPointer(), pPSUntexBlob->GetBufferSize(), NULL, &m_pPSRenderUIUntex11 ) ); - DXUT_SetDebugName( m_pPSRenderUIUntex11, "CDXUTDialogResourceManager" ); - - // States - D3D11_DEPTH_STENCIL_DESC DSDesc; - ZeroMemory( &DSDesc, sizeof( D3D11_DEPTH_STENCIL_DESC ) ); - DSDesc.DepthEnable = FALSE; - DSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; - DSDesc.DepthFunc = D3D11_COMPARISON_LESS; - DSDesc.StencilEnable = FALSE; - V_RETURN( pd3dDevice->CreateDepthStencilState( &DSDesc, &m_pDepthStencilStateUI11 ) ); - DXUT_SetDebugName( m_pDepthStencilStateUI11, "CDXUTDialogResourceManager" ); - - D3D11_RASTERIZER_DESC RSDesc; - RSDesc.AntialiasedLineEnable = FALSE; - RSDesc.CullMode = D3D11_CULL_BACK; - RSDesc.DepthBias = 0; - RSDesc.DepthBiasClamp = 0.0f; - RSDesc.DepthClipEnable = TRUE; - RSDesc.FillMode = D3D11_FILL_SOLID; - RSDesc.FrontCounterClockwise = FALSE; - RSDesc.MultisampleEnable = TRUE; - RSDesc.ScissorEnable = FALSE; - RSDesc.SlopeScaledDepthBias = 0.0f; - V_RETURN( pd3dDevice->CreateRasterizerState( &RSDesc, &m_pRasterizerStateUI11 ) ); - DXUT_SetDebugName( m_pRasterizerStateUI11, "CDXUTDialogResourceManager" ); + // If no callback has been registered there's nowhere to send the event to + if( !m_pCallbackEvent ) + return; - D3D11_BLEND_DESC BSDesc; - ZeroMemory( &BSDesc, sizeof( D3D11_BLEND_DESC ) ); - - BSDesc.RenderTarget[0].BlendEnable = TRUE; - BSDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; - BSDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - BSDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - BSDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; - BSDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; - BSDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; - BSDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; + // Discard events triggered programatically if these types of events haven't been + // enabled + if( !bTriggeredByUser && !m_bNonUserEvents ) + return; - V_RETURN( pd3dDevice->CreateBlendState( &BSDesc, &m_pBlendStateUI11 ) ); - DXUT_SetDebugName( m_pBlendStateUI11, "CDXUTDialogResourceManager" ); + m_pCallbackEvent( nEvent, pControl->GetID(), pControl, m_pCallbackEventUserContext ); +} - D3D11_SAMPLER_DESC SSDesc; - ZeroMemory( &SSDesc, sizeof( D3D11_SAMPLER_DESC ) ); - SSDesc.Filter = D3D11_FILTER_ANISOTROPIC ; - SSDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; - SSDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; - SSDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; - SSDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; - SSDesc.MaxAnisotropy = 16; - SSDesc.MinLOD = 0; - SSDesc.MaxLOD = D3D11_FLOAT32_MAX; - if ( pd3dDevice->GetFeatureLevel() < D3D_FEATURE_LEVEL_9_3 ) { - SSDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; - SSDesc.MaxAnisotropy = 0; - } - V_RETURN( pd3dDevice->CreateSamplerState( &SSDesc, &m_pSamplerStateUI11 ) ); - DXUT_SetDebugName( m_pSamplerStateUI11, "CDXUTDialogResourceManager" ); - // Create the font and texture objects in the cache arrays. - int i = 0; - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - hr = CreateFont11( i ); - if( FAILED( hr ) ) - return hr; - } +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTDialog::SetFont( UINT index, LPCWSTR strFaceName, LONG height, LONG weight ) +{ + // If this assert triggers, you need to call CDXUTDialog::Init() first. This change + // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The + // creation and interfacing with CDXUTDialogResourceManager is now the responsibility + // of the application if it wishes to use DXUT's GUI. + assert( m_pManager && L"To fix call CDXUTDialog::Init() first. See comments for details." ); + _Analysis_assume_( m_pManager ); - for( i = 0; i < m_TextureCache.GetSize(); i++ ) + // Make sure the list is at least as large as the index being set + for( size_t i = m_Fonts.size(); i <= index; i++ ) { - hr = CreateTexture11( i ); - if( FAILED( hr ) ) - return hr; + m_Fonts.push_back( -1 ); } - // Create input layout - const D3D11_INPUT_ELEMENT_DESC layout[] = - { - { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - }; - - V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &m_pInputLayout11 ) ); - DXUT_SetDebugName( m_pInputLayout11, "CDXUTDialogResourceManager" ); - - // Release the blobs - SAFE_RELEASE( pVSBlob ); - SAFE_RELEASE( pPSBlob ); - SAFE_RELEASE( pPSUntexBlob ); - - // Create a vertex buffer quad for rendering later - D3D11_BUFFER_DESC BufDesc; - BufDesc.ByteWidth = sizeof( DXUT_SCREEN_VERTEX_10 ) * 4; - BufDesc.Usage = D3D11_USAGE_DYNAMIC; - BufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - BufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - BufDesc.MiscFlags = 0; - V_RETURN( pd3dDevice->CreateBuffer( &BufDesc, NULL, &m_pVBScreenQuad11 ) ); - DXUT_SetDebugName( m_pVBScreenQuad11, "CDXUTDialogResourceManager" ); - - // Init the D3D11 font - InitFont11( pd3dDevice, m_pInputLayout11 ); + int iFont = m_pManager->AddFont( strFaceName, height, weight ); + m_Fonts[ index ] = iFont; return S_OK; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) -{ - HRESULT hr = S_OK; - - m_nBackBufferWidth = pBackBufferSurfaceDesc->Width; - m_nBackBufferHeight = pBackBufferSurfaceDesc->Height; - - return hr; -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D11ReleasingSwapChain() +DXUTFontNode* CDXUTDialog::GetFont( _In_ UINT index ) const { + if( !m_pManager ) + return nullptr; + return m_pManager->GetFontNode( m_Fonts[ index ] ); } //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D11DestroyDevice() +_Use_decl_annotations_ +HRESULT CDXUTDialog::SetTexture( UINT index, LPCWSTR strFilename ) { - int i; - - // Release the resources but don't clear the cache, as these will need to be - // recreated if the device is recreated + // If this assert triggers, you need to call CDXUTDialog::Init() first. This change + // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The + // creation and interfacing with CDXUTDialogResourceManager is now the responsibility + // of the application if it wishes to use DXUT's GUI. + assert( m_pManager && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); + _Analysis_assume_( m_pManager ); - for( i = 0; i < m_TextureCache.GetSize(); i++ ) + // Make sure the list is at least as large as the index being set + for( size_t i = m_Textures.size(); i <= index; i++ ) { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - SAFE_RELEASE( pTextureNode->pTexResView11 ); - SAFE_RELEASE( pTextureNode->pTexture11 ); + m_Textures.push_back( -1 ); } - // D3D11 - SAFE_RELEASE( m_pVBScreenQuad11 ); - SAFE_RELEASE( m_pSpriteBuffer11 ); - m_SpriteBufferBytes11 = 0; - SAFE_RELEASE( m_pInputLayout11 ); - - // Shaders - SAFE_RELEASE( m_pVSRenderUI11 ); - SAFE_RELEASE( m_pPSRenderUI11 ); - SAFE_RELEASE( m_pPSRenderUIUntex11 ); - - // States - SAFE_RELEASE( m_pDepthStencilStateUI11 ); - SAFE_RELEASE( m_pRasterizerStateUI11 ); - SAFE_RELEASE( m_pBlendStateUI11 ); - SAFE_RELEASE( m_pSamplerStateUI11 ); - - SAFE_RELEASE( m_pDepthStencilStateStored11 ); - SAFE_RELEASE( m_pRasterizerStateStored11 ); - SAFE_RELEASE( m_pBlendStateStored11 ); - SAFE_RELEASE( m_pSamplerStateStored11 ); + int iTexture = m_pManager->AddTexture( strFilename ); - EndFont11(); + m_Textures[ index] = iTexture; + return S_OK; } -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::StoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ) -{ - pd3dImmediateContext->OMGetDepthStencilState( &m_pDepthStencilStateStored11, &m_StencilRefStored11 ); - pd3dImmediateContext->RSGetState( &m_pRasterizerStateStored11 ); - pd3dImmediateContext->OMGetBlendState( &m_pBlendStateStored11, m_BlendFactorStored11, &m_SampleMaskStored11 ); - pd3dImmediateContext->PSGetSamplers( 0, 1, &m_pSamplerStateStored11 ); -} //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::RestoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ) +_Use_decl_annotations_ +HRESULT CDXUTDialog::SetTexture( UINT index, LPCWSTR strResourceName, HMODULE hResourceModule ) { - pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateStored11, m_StencilRefStored11 ); - pd3dImmediateContext->RSSetState( m_pRasterizerStateStored11 ); - pd3dImmediateContext->OMSetBlendState( m_pBlendStateStored11, m_BlendFactorStored11, m_SampleMaskStored11 ); - pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateStored11 ); + // If this assert triggers, you need to call CDXUTDialog::Init() first. This change + // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The + // creation and interfacing with CDXUTDialogResourceManager is now the responsibility + // of the application if it wishes to use DXUT's GUI. + assert( m_pManager && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); + _Analysis_assume_( m_pManager ); - SAFE_RELEASE( m_pDepthStencilStateStored11 ); - SAFE_RELEASE( m_pRasterizerStateStored11 ); - SAFE_RELEASE( m_pBlendStateStored11 ); - SAFE_RELEASE( m_pSamplerStateStored11 ); -} + // Make sure the list is at least as large as the index being set + for( size_t i = m_Textures.size(); i <= index; i++ ) + { + m_Textures.push_back( -1 ); + } -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::ApplyRenderUI11( ID3D11DeviceContext* pd3dImmediateContext ) -{ - // Shaders - pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, NULL, 0 ); - pd3dImmediateContext->HSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->DSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->GSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->PSSetShader( m_pPSRenderUI11, NULL, 0 ); + int iTexture = m_pManager->AddTexture( strResourceName, hResourceModule ); - // States - pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); - pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); - float BlendFactor[4] = { 0, 0, 0, 0 }; - pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); - pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); + m_Textures[ index ] = iTexture; + return S_OK; } -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::ApplyRenderUIUntex11( ID3D11DeviceContext* pd3dImmediateContext ) -{ - // Shaders - pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, NULL, 0 ); - pd3dImmediateContext->HSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->DSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->GSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->PSSetShader( m_pPSRenderUIUntex11, NULL, 0 ); - - // States - pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); - pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); - float BlendFactor[4] = { 0, 0, 0, 0 }; - pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); - pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); -} //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::BeginSprites11( ) +DXUTTextureNode* CDXUTDialog::GetTexture( _In_ UINT index ) const { - m_SpriteVertices.Reset(); + if( !m_pManager ) + return nullptr; + return m_pManager->GetTextureNode( m_Textures[ index ] ); } + //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::EndSprites11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) +_Use_decl_annotations_ +bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - - // ensure our buffer size can hold our sprites - UINT SpriteDataBytes = m_SpriteVertices.GetSize() * sizeof( DXUTSpriteVertex ); - if( m_SpriteBufferBytes11 < SpriteDataBytes ) - { - SAFE_RELEASE( m_pSpriteBuffer11 ); - m_SpriteBufferBytes11 = SpriteDataBytes; - - D3D11_BUFFER_DESC BufferDesc; - BufferDesc.ByteWidth = m_SpriteBufferBytes11; - BufferDesc.Usage = D3D11_USAGE_DYNAMIC; - BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - BufferDesc.MiscFlags = 0; - - pd3dDevice->CreateBuffer( &BufferDesc, NULL, &m_pSpriteBuffer11 ); - DXUT_SetDebugName( m_pSpriteBuffer11, "CDXUTDialogResourceManager" ); - } - - // Copy the sprites over - D3D11_BOX destRegion; - destRegion.left = 0; - destRegion.right = SpriteDataBytes; - destRegion.top = 0; - destRegion.bottom = 1; - destRegion.front = 0; - destRegion.back = 1; - D3D11_MAPPED_SUBRESOURCE MappedResource; - if ( S_OK == pd3dImmediateContext->Map( m_pSpriteBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) { - CopyMemory( MappedResource.pData, (void*)m_SpriteVertices.GetData(), SpriteDataBytes ); - pd3dImmediateContext->Unmap(m_pSpriteBuffer11, 0); - } - - // Draw - UINT Stride = sizeof( DXUTSpriteVertex ); - UINT Offset = 0; - pd3dImmediateContext->IASetVertexBuffers( 0, 1, &m_pSpriteBuffer11, &Stride, &Offset ); - pd3dImmediateContext->IASetInputLayout( m_pInputLayout11 ); - pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); - pd3dImmediateContext->Draw( m_SpriteVertices.GetSize(), 0 ); - - m_SpriteVertices.Reset(); -} - -//-------------------------------------------------------------------------------------- -bool CDXUTDialogResourceManager::RegisterDialog( CDXUTDialog* pDialog ) -{ - // Check that the dialog isn't already registered. - for( int i = 0; i < m_Dialogs.GetSize(); ++i ) - if( m_Dialogs.GetAt( i ) == pDialog ) - return true; - - // Add to the list. - if( FAILED( m_Dialogs.Add( pDialog ) ) ) - return false; - - // Set up next and prev pointers. - if( m_Dialogs.GetSize() > 1 ) - m_Dialogs[m_Dialogs.GetSize() - 2]->SetNextDialog( pDialog ); - m_Dialogs[m_Dialogs.GetSize() - 1]->SetNextDialog( m_Dialogs[0] ); - - return true; -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::UnregisterDialog( CDXUTDialog* pDialog ) -{ - // Search for the dialog in the list. - for( int i = 0; i < m_Dialogs.GetSize(); ++i ) - if( m_Dialogs.GetAt( i ) == pDialog ) - { - m_Dialogs.Remove( i ); - if( m_Dialogs.GetSize() > 0 ) - { - int l, r; - - if( 0 == i ) - l = m_Dialogs.GetSize() - 1; - else - l = i - 1; - - if( m_Dialogs.GetSize() == i ) - r = 0; - else - r = i; - - m_Dialogs[l]->SetNextDialog( m_Dialogs[r] ); - } - return; - } -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::EnableKeyboardInputForAllDialogs() -{ - // Enable keyboard input for all registered dialogs - for( int i = 0; i < m_Dialogs.GetSize(); ++i ) - m_Dialogs[i]->EnableKeyboardInput( true ); -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialog::Refresh() -{ - if( s_pControlFocus ) - s_pControlFocus->OnFocusOut(); - - if( m_pControlMouseOver ) - m_pControlMouseOver->OnMouseLeave(); - - s_pControlFocus = NULL; - s_pControlPressed = NULL; - m_pControlMouseOver = NULL; - - for( int i = 0; i < m_Controls.GetSize(); i++ ) - { - CDXUTControl* pControl = m_Controls.GetAt( i ); - pControl->Refresh(); - } - - if( m_bKeyboardInput ) - FocusDefaultControl(); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::OnRender( float fElapsedTime ) -{ - if( m_pManager->GetD3D9Device() ) - return OnRender9( fElapsedTime ); - else - return OnRender11( fElapsedTime ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::OnRender9( float fElapsedTime ) -{ - // If this assert triggers, you need to call CDXUTDialogResourceManager::On*Device() from inside - // the application's device callbacks. See the SDK samples for an example of how to do this. - assert( m_pManager->GetD3D9Device() && m_pManager->m_pStateBlock && - L"To fix hook up CDXUTDialogResourceManager to device callbacks. See comments for details" ); - - // See if the dialog needs to be refreshed - if( m_fTimeLastRefresh < s_fTimeRefresh ) - { - m_fTimeLastRefresh = DXUTGetTime(); - Refresh(); - } - - // For invisible dialog, out now. - if( !m_bVisible || - ( m_bMinimized && !m_bCaption ) ) - return S_OK; - - IDirect3DDevice9* pd3dDevice = m_pManager->GetD3D9Device(); - - // Set up a state block here and restore it when finished drawing all the controls - m_pManager->m_pStateBlock->Capture(); - - //pd3dDevice->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, TRUE); - //pd3dDevice->SetRenderState( D3DRS_SRGBWRITEENABLE, TRUE ); - - pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); - pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); - pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); - pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_SEPARATEALPHABLENDENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD ); - pd3dDevice->SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | - D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED ); - pd3dDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD ); - pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); - pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_RESULTARG, D3DTA_CURRENT ); - pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - BOOL bBackgroundIsVisible = ( m_colorTopLeft | m_colorTopRight | m_colorBottomRight | m_colorBottomLeft ) & - 0xff000000; - if( !m_bMinimized && bBackgroundIsVisible ) - { - DXUT_SCREEN_VERTEX_UNTEX vertices[4] = - { - ( float )m_x, ( float )m_y, 0.5f, 1.0f, m_colorTopLeft, - ( float )m_x + m_width, ( float )m_y, 0.5f, 1.0f, m_colorTopRight, - ( float )m_x + m_width, ( float )m_y + m_height, 0.5f, 1.0f, m_colorBottomRight, - ( float )m_x, ( float )m_y + m_height, 0.5f, 1.0f, m_colorBottomLeft, - }; - - pd3dDevice->SetVertexShader( NULL ); - pd3dDevice->SetPixelShader( NULL ); - - pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); - - pd3dDevice->SetFVF( DXUT_SCREEN_VERTEX_UNTEX::FVF ); - pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices, sizeof( DXUT_SCREEN_VERTEX_UNTEX ) ); - } - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE ); - - pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); - - DXUTTextureNode* pTextureNode = GetTexture( 0 ); - pd3dDevice->SetTexture( 0, pTextureNode->pTexture9 ); - - m_pManager->m_pSprite->Begin( D3DXSPRITE_DONOTSAVESTATE ); - - // Render the caption if it's enabled. - if( m_bCaption ) - { - // DrawSprite will offset the rect down by - // m_nCaptionHeight, so adjust the rect higher - // here to negate the effect. - RECT rc = - { - 0, -m_nCaptionHeight, m_width, 0 - }; - DrawSprite9( &m_CapElement, &rc ); - rc.left += 5; // Make a left margin - WCHAR wszOutput[256]; - wcscpy_s( wszOutput, 256, m_wszCaption ); - if( m_bMinimized ) - wcscat_s( wszOutput, 256, L" (Minimized)" ); - DrawText9( wszOutput, &m_CapElement, &rc, true ); - } - - // If the dialog is minimized, skip rendering - // its controls. - if( !m_bMinimized ) - { - for( int i = 0; i < m_Controls.GetSize(); i++ ) - { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - // Focused control is drawn last - if( pControl == s_pControlFocus ) - continue; - - pControl->Render( fElapsedTime ); - } - - if( s_pControlFocus != NULL && s_pControlFocus->m_pDialog == this ) - s_pControlFocus->Render( fElapsedTime ); - } - - m_pManager->m_pSprite->End(); - - m_pManager->m_pStateBlock->Apply(); - - return S_OK; -} - - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::OnRender11( float fElapsedTime ) -{ - // If this assert triggers, you need to call CDXUTDialogResourceManager::On*Device() from inside - // the application's device callbacks. See the SDK samples for an example of how to do this. - assert( m_pManager->GetD3D11Device() && - L"To fix hook up CDXUTDialogResourceManager to device callbacks. See comments for details" ); - - // See if the dialog needs to be refreshed - if( m_fTimeLastRefresh < s_fTimeRefresh ) - { - m_fTimeLastRefresh = DXUTGetTime(); - Refresh(); - } - - // For invisible dialog, out now. - if( !m_bVisible || - ( m_bMinimized && !m_bCaption ) ) - return S_OK; - - ID3D11Device* pd3dDevice = m_pManager->GetD3D11Device(); - ID3D11DeviceContext* pd3dDeviceContext = m_pManager->GetD3D11DeviceContext(); - - // Set up a state block here and restore it when finished drawing all the controls - m_pManager->StoreD3D11State( pd3dDeviceContext ); - - BOOL bBackgroundIsVisible = ( m_colorTopLeft | m_colorTopRight | m_colorBottomRight | m_colorBottomLeft ) & - 0xff000000; - if( !m_bMinimized && bBackgroundIsVisible ) - { - // Convert the draw rectangle from screen coordinates to clip space coordinates. - float Left, Right, Top, Bottom; - Left = m_x * 2.0f / m_pManager->m_nBackBufferWidth - 1.0f; - Right = ( m_x + m_width ) * 2.0f / m_pManager->m_nBackBufferWidth - 1.0f; - Top = 1.0f - m_y * 2.0f / m_pManager->m_nBackBufferHeight; - Bottom = 1.0f - ( m_y + m_height ) * 2.0f / m_pManager->m_nBackBufferHeight; - - DXUT_SCREEN_VERTEX_10 vertices[4] = - { - Left, Top, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorTopLeft ), 0.0f, 0.0f, - Right, Top, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorTopRight ), 1.0f, 0.0f, - Left, Bottom, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorBottomLeft ), 0.0f, 1.0f, - Right, Bottom, 0.5f, D3DCOLOR_TO_D3DCOLORVALUE( m_colorBottomRight ), 1.0f, 1.0f, - }; - - //DXUT_SCREEN_VERTEX_10 *pVB; - D3D11_MAPPED_SUBRESOURCE MappedData; - if( SUCCEEDED( pd3dDeviceContext->Map( m_pManager->m_pVBScreenQuad11, 0, D3D11_MAP_WRITE_DISCARD, - 0, &MappedData ) ) ) - { - CopyMemory( MappedData.pData, vertices, sizeof( vertices ) ); - pd3dDeviceContext->Unmap( m_pManager->m_pVBScreenQuad11, 0 ); - } - - // Set the quad VB as current - UINT stride = sizeof( DXUT_SCREEN_VERTEX_10 ); - UINT offset = 0; - pd3dDeviceContext->IASetVertexBuffers( 0, 1, &m_pManager->m_pVBScreenQuad11, &stride, &offset ); - pd3dDeviceContext->IASetInputLayout( m_pManager->m_pInputLayout11 ); - pd3dDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); - - // Setup for rendering - m_pManager->ApplyRenderUIUntex11( pd3dDeviceContext ); - pd3dDeviceContext->Draw( 4, 0 ); - } - - DXUTTextureNode* pTextureNode = GetTexture( 0 ); - pd3dDeviceContext->PSSetShaderResources( 0, 1, &pTextureNode->pTexResView11 ); - - // Sort depth back to front - m_pManager->BeginSprites11(); - BeginText11(); - - m_pManager->ApplyRenderUI11( pd3dDeviceContext ); - - // Render the caption if it's enabled. - if( m_bCaption ) - { - // DrawSprite will offset the rect down by - // m_nCaptionHeight, so adjust the rect higher - // here to negate the effect. - RECT rc = { 0, -m_nCaptionHeight, m_width, 0 }; - DrawSprite11( &m_CapElement, &rc, 0.99f ); - rc.left += 5; // Make a left margin - WCHAR wszOutput[256]; - wcscpy_s( wszOutput, 256, m_wszCaption ); - if( m_bMinimized ) - wcscat_s( wszOutput, 256, L" (Minimized)" ); - DrawText11( pd3dDevice, pd3dDeviceContext, wszOutput, &m_CapElement, &rc, true ); - } - - // If the dialog is minimized, skip rendering - // its controls. - if( !m_bMinimized ) - { - for( int i = 0; i < m_Controls.GetSize(); i++ ) - { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - // Focused control is drawn last - if( pControl == s_pControlFocus ) - continue; - - pControl->Render( fElapsedTime ); - } - - if( s_pControlFocus != NULL && s_pControlFocus->m_pDialog == this ) - s_pControlFocus->Render( fElapsedTime ); - } - - // End sprites - if( m_bCaption ) - { - m_pManager->EndSprites11( pd3dDevice, pd3dDeviceContext ); - EndText11( pd3dDevice, pd3dDeviceContext ); - } - m_pManager->RestoreD3D11State( pd3dDeviceContext ); - - return S_OK; -} - -//-------------------------------------------------------------------------------------- -VOID CDXUTDialog::SendEvent( UINT nEvent, bool bTriggeredByUser, CDXUTControl* pControl ) -{ - // If no callback has been registered there's nowhere to send the event to - if( m_pCallbackEvent == NULL ) - return; - - // Discard events triggered programatically if these types of events haven't been - // enabled - if( !bTriggeredByUser && !m_bNonUserEvents ) - return; - - m_pCallbackEvent( nEvent, pControl->GetID(), pControl, m_pCallbackEventUserContext ); -} - - -//-------------------------------------------------------------------------------------- -int CDXUTDialogResourceManager::AddFont( LPCWSTR strFaceName, LONG height, LONG weight ) -{ - // See if this font already exists - for( int i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - size_t nLen = 0; - nLen = wcsnlen( strFaceName, MAX_PATH); - if( 0 == _wcsnicmp( pFontNode->strFace, strFaceName, nLen ) && - pFontNode->nHeight == height && - pFontNode->nWeight == weight ) - { - return i; - } - } - - // Add a new font and try to create it - DXUTFontNode* pNewFontNode = new DXUTFontNode; - if( pNewFontNode == NULL ) - return -1; - - ZeroMemory( pNewFontNode, sizeof( DXUTFontNode ) ); - wcscpy_s( pNewFontNode->strFace, MAX_PATH, strFaceName ); - pNewFontNode->nHeight = height; - pNewFontNode->nWeight = weight; - m_FontCache.Add( pNewFontNode ); - - int iFont = m_FontCache.GetSize() - 1; - - // If a device is available, try to create immediately - if( m_pd3d9Device ) - CreateFont9( iFont ); - - return iFont; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::SetFont( UINT index, LPCWSTR strFaceName, LONG height, LONG weight ) -{ - // If this assert triggers, you need to call CDXUTDialog::Init() first. This change - // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The - // creation and interfacing with CDXUTDialogResourceManager is now the responsibility - // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix call CDXUTDialog::Init() first. See comments for details." ); - - // Make sure the list is at least as large as the index being set - UINT i; - for( i = m_Fonts.GetSize(); i <= index; i++ ) - { - m_Fonts.Add( -1 ); - } - - int iFont = m_pManager->AddFont( strFaceName, height, weight ); - m_Fonts.SetAt( index, iFont ); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -DXUTFontNode* CDXUTDialog::GetFont( UINT index ) -{ - if( NULL == m_pManager ) - return NULL; - return m_pManager->GetFontNode( m_Fonts.GetAt( index ) ); -} - - -//-------------------------------------------------------------------------------------- -int CDXUTDialogResourceManager::AddTexture( LPCWSTR strFilename ) -{ - // See if this texture already exists - for( int i = 0; i < m_TextureCache.GetSize(); i++ ) - { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - size_t nLen = 0; - nLen = wcsnlen( strFilename, MAX_PATH); - if( pTextureNode->bFileSource && // Sources must match - 0 == _wcsnicmp( pTextureNode->strFilename, strFilename, nLen ) ) - { - return i; - } - } - - // Add a new texture and try to create it - DXUTTextureNode* pNewTextureNode = new DXUTTextureNode; - if( pNewTextureNode == NULL ) - return -1; - - ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); - pNewTextureNode->bFileSource = true; - wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strFilename ); - - m_TextureCache.Add( pNewTextureNode ); - - int iTexture = m_TextureCache.GetSize() - 1; - - // If a device is available, try to create immediately - if( m_pd3d9Device ) - CreateTexture9( iTexture ); - - return iTexture; -} - - -//-------------------------------------------------------------------------------------- -int CDXUTDialogResourceManager::AddTexture( LPCWSTR strResourceName, HMODULE hResourceModule ) -{ - // See if this texture already exists - for( int i = 0; i < m_TextureCache.GetSize(); i++ ) - { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - if( !pTextureNode->bFileSource && // Sources must match - pTextureNode->hResourceModule == hResourceModule ) // Module handles must match - { - if( IS_INTRESOURCE( strResourceName ) ) - { - // Integer-based ID - if( ( INT_PTR )strResourceName == pTextureNode->nResourceID ) - return i; - } - else - { - // String-based ID - size_t nLen = 0; - nLen = wcsnlen ( strResourceName, MAX_PATH ); - if( 0 == _wcsnicmp( pTextureNode->strFilename, strResourceName, nLen ) ) - return i; - } - } - } - - // Add a new texture and try to create it - DXUTTextureNode* pNewTextureNode = new DXUTTextureNode; - if( pNewTextureNode == NULL ) - return -1; - - ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); - pNewTextureNode->hResourceModule = hResourceModule; - if( IS_INTRESOURCE( strResourceName ) ) - { - pNewTextureNode->nResourceID = ( int )( size_t )strResourceName; - } - else - { - pNewTextureNode->nResourceID = 0; - wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strResourceName ); - } - - m_TextureCache.Add( pNewTextureNode ); - - int iTexture = m_TextureCache.GetSize() - 1; - - // If a device is available, try to create immediately - if( m_pd3d9Device ) - CreateTexture9( iTexture ); - - return iTexture; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::SetTexture( UINT index, LPCWSTR strFilename ) -{ - // If this assert triggers, you need to call CDXUTDialog::Init() first. This change - // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The - // creation and interfacing with CDXUTDialogResourceManager is now the responsibility - // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); - - // Make sure the list is at least as large as the index being set - for( UINT i = m_Textures.GetSize(); i <= index; i++ ) - { - m_Textures.Add( -1 ); - } - - int iTexture = m_pManager->AddTexture( strFilename ); - - m_Textures.SetAt( index, iTexture ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::SetTexture( UINT index, LPCWSTR strResourceName, HMODULE hResourceModule ) -{ - // If this assert triggers, you need to call CDXUTDialog::Init() first. This change - // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The - // creation and interfacing with CDXUTDialogResourceManager is now the responsibility - // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); - - // Make sure the list is at least as large as the index being set - for( UINT i = m_Textures.GetSize(); i <= index; i++ ) - { - m_Textures.Add( -1 ); - } - - int iTexture = m_pManager->AddTexture( strResourceName, hResourceModule ); - - m_Textures.SetAt( index, iTexture ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -DXUTTextureNode* CDXUTDialog::GetTexture( UINT index ) -{ - if( NULL == m_pManager ) - return NULL; - return m_pManager->GetTextureNode( m_Textures.GetAt( index ) ); -} - - - -//-------------------------------------------------------------------------------------- -bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) -{ - bool bHandled = false; + bool bHandled = false; // For invisible dialog, do not handle anything. if( !m_bVisible ) @@ -1526,6 +908,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) if( s_pControlFocus && s_pControlFocus->m_pDialog == this && s_pControlFocus->GetEnabled() ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { if( s_pControlFocus->HandleKeyboard( uMsg, wParam, lParam ) ) return true; @@ -1538,12 +921,11 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) ( s_pControlFocus->GetType() != DXUT_CONTROL_EDITBOX && s_pControlFocus->GetType() != DXUT_CONTROL_IMEEDITBOX ) ) ) { - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - if( pControl->GetHotkey() == wParam ) + if( (*it)->GetHotkey() == wParam ) { - pControl->OnHotkey(); + (*it)->OnHotkey(); return true; } } @@ -1560,7 +942,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { case VK_RIGHT: case VK_DOWN: - if( s_pControlFocus != NULL ) + if( s_pControlFocus ) { return OnCycleFocus( true ); } @@ -1568,7 +950,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) case VK_LEFT: case VK_UP: - if( s_pControlFocus != NULL ) + if( s_pControlFocus ) { return OnCycleFocus( false ); } @@ -1629,8 +1011,8 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) } // Not yet handled, see if the mouse is over any controls - CDXUTControl* pControl = GetControlAtPoint( mousePoint ); - if( pControl != NULL && pControl->GetEnabled() ) + auto pControl = GetControlAtPoint( mousePoint ); + if( pControl && pControl->GetEnabled() ) { bHandled = pControl->HandleMouse( uMsg, mousePoint, wParam, lParam ); if( bHandled ) @@ -1645,7 +1027,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) s_pControlFocus->m_pDialog == this ) { s_pControlFocus->OnFocusOut(); - s_pControlFocus = NULL; + s_pControlFocus = nullptr; } } @@ -1676,16 +1058,15 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) return false; } + //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetControlAtPoint( POINT pt ) +CDXUTControl* CDXUTDialog::GetControlAtPoint( _In_ const POINT& pt ) const { // Search through all child controls for the first one which // contains the mouse point - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl == NULL ) + if( !*it ) { continue; } @@ -1693,21 +1074,21 @@ CDXUTControl* CDXUTDialog::GetControlAtPoint( POINT pt ) // We only return the current control if it is visible // and enabled. Because GetControlAtPoint() is used to do mouse // hittest, it makes sense to perform this filtering. - if( pControl->ContainsPoint( pt ) && pControl->GetEnabled() && pControl->GetVisible() ) + if( (*it)->ContainsPoint( pt ) && (*it)->GetEnabled() && (*it)->GetVisible() ) { - return pControl; + return *it; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -bool CDXUTDialog::GetControlEnabled( int ID ) +bool CDXUTDialog::GetControlEnabled( _In_ int ID ) const { - CDXUTControl* pControl = GetControl( ID ); - if( pControl == NULL ) + auto pControl = GetControl( ID ); + if( !pControl ) return false; return pControl->GetEnabled(); @@ -1716,10 +1097,10 @@ bool CDXUTDialog::GetControlEnabled( int ID ) //-------------------------------------------------------------------------------------- -void CDXUTDialog::SetControlEnabled( int ID, bool bEnabled ) +void CDXUTDialog::SetControlEnabled( _In_ int ID, _In_ bool bEnabled ) { - CDXUTControl* pControl = GetControl( ID ); - if( pControl == NULL ) + auto pControl = GetControl( ID ); + if( !pControl ) return; pControl->SetEnabled( bEnabled ); @@ -1727,18 +1108,19 @@ void CDXUTDialog::SetControlEnabled( int ID, bool bEnabled ) //-------------------------------------------------------------------------------------- -void CDXUTDialog::OnMouseUp( POINT pt ) +void CDXUTDialog::OnMouseUp( _In_ const POINT& pt ) { - s_pControlPressed = NULL; - m_pControlMouseOver = NULL; + UNREFERENCED_PARAMETER(pt); + s_pControlPressed = nullptr; + m_pControlMouseOver = nullptr; } //-------------------------------------------------------------------------------------- -void CDXUTDialog::OnMouseMove( POINT pt ) +void CDXUTDialog::OnMouseMove( _In_ const POINT& pt ) { // Figure out which control the mouse is over now - CDXUTControl* pControl = GetControlAtPoint( pt ); + auto pControl = GetControlAtPoint( pt ); // If the mouse is still over the same control, nothing needs to be done if( pControl == m_pControlMouseOver ) @@ -1750,77 +1132,72 @@ void CDXUTDialog::OnMouseMove( POINT pt ) // Handle mouse entering the new control m_pControlMouseOver = pControl; - if( pControl != NULL ) + if( pControl ) m_pControlMouseOver->OnMouseEnter(); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::SetDefaultElement( UINT nControlType, UINT iElement, CDXUTElement* pElement ) { // If this Element type already exist in the list, simply update the stored Element - for( int i = 0; i < m_DefaultElements.GetSize(); i++ ) + for( auto it = m_DefaultElements.begin(); it != m_DefaultElements.end(); ++it ) { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - - if( pElementHolder->nControlType == nControlType && - pElementHolder->iElement == iElement ) + if( (*it)->nControlType == nControlType && + (*it)->iElement == iElement ) { - pElementHolder->Element = *pElement; + (*it)->Element = *pElement; return S_OK; } } // Otherwise, add a new entry DXUTElementHolder* pNewHolder; - pNewHolder = new DXUTElementHolder; - if( pNewHolder == NULL ) + pNewHolder = new (std::nothrow) DXUTElementHolder; + if( !pNewHolder ) return E_OUTOFMEMORY; pNewHolder->nControlType = nControlType; pNewHolder->iElement = iElement; pNewHolder->Element = *pElement; - HRESULT hr = m_DefaultElements.Add( pNewHolder ); - if( FAILED( hr ) ) - { - delete pNewHolder; - } - return hr; + m_DefaultElements.push_back( pNewHolder ); + + return S_OK; } //-------------------------------------------------------------------------------------- -CDXUTElement* CDXUTDialog::GetDefaultElement( UINT nControlType, UINT iElement ) +_Use_decl_annotations_ +CDXUTElement* CDXUTDialog::GetDefaultElement( UINT nControlType, UINT iElement ) const { - for( int i = 0; i < m_DefaultElements.GetSize(); i++ ) + for( auto it = m_DefaultElements.cbegin(); it != m_DefaultElements.cend(); ++it ) { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - - if( pElementHolder->nControlType == nControlType && - pElementHolder->iElement == iElement ) + if( (*it)->nControlType == nControlType && + (*it)->iElement == iElement ) { - return &pElementHolder->Element; + return &(*it)->Element; } } - return NULL; + return nullptr; } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddStatic( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault, CDXUTStatic** ppCreated ) { HRESULT hr = S_OK; - CDXUTStatic* pStatic = new CDXUTStatic( this ); + auto pStatic = new (std::nothrow) CDXUTStatic( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pStatic; - if( pStatic == NULL ) + if( !pStatic ) return E_OUTOFMEMORY; hr = AddControl( pStatic ); @@ -1839,17 +1216,18 @@ HRESULT CDXUTDialog::AddStatic( int ID, LPCWSTR strText, int x, int y, int width //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddButton( int ID, LPCWSTR strText, int x, int y, int width, int height, UINT nHotkey, bool bIsDefault, CDXUTButton** ppCreated ) { HRESULT hr = S_OK; - CDXUTButton* pButton = new CDXUTButton( this ); + auto pButton = new (std::nothrow) CDXUTButton( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pButton; - if( pButton == NULL ) + if( !pButton ) return E_OUTOFMEMORY; hr = AddControl( pButton ); @@ -1869,17 +1247,18 @@ HRESULT CDXUTDialog::AddButton( int ID, LPCWSTR strText, int x, int y, int width //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddCheckBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bChecked, UINT nHotkey, bool bIsDefault, CDXUTCheckBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTCheckBox* pCheckBox = new CDXUTCheckBox( this ); + auto pCheckBox = new (std::nothrow) CDXUTCheckBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pCheckBox; - if( pCheckBox == NULL ) + if( !pCheckBox ) return E_OUTOFMEMORY; hr = AddControl( pCheckBox ); @@ -1899,19 +1278,19 @@ HRESULT CDXUTDialog::AddCheckBox( int ID, LPCWSTR strText, int x, int y, int wid } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddRadioButton( int ID, UINT nButtonGroup, LPCWSTR strText, int x, int y, int width, int height, bool bChecked, UINT nHotkey, bool bIsDefault, CDXUTRadioButton** ppCreated ) { HRESULT hr = S_OK; - CDXUTRadioButton* pRadioButton = new CDXUTRadioButton( this ); + auto pRadioButton = new (std::nothrow) CDXUTRadioButton( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pRadioButton; - if( pRadioButton == NULL ) + if( !pRadioButton ) return E_OUTOFMEMORY; hr = AddControl( pRadioButton ); @@ -1933,20 +1312,19 @@ HRESULT CDXUTDialog::AddRadioButton( int ID, UINT nButtonGroup, LPCWSTR strText, } - - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddComboBox( int ID, int x, int y, int width, int height, UINT nHotkey, bool bIsDefault, CDXUTComboBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTComboBox* pComboBox = new CDXUTComboBox( this ); + auto pComboBox = new (std::nothrow) CDXUTComboBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pComboBox; - if( pComboBox == NULL ) + if( !pComboBox ) return E_OUTOFMEMORY; hr = AddControl( pComboBox ); @@ -1964,19 +1342,19 @@ HRESULT CDXUTDialog::AddComboBox( int ID, int x, int y, int width, int height, U } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddSlider( int ID, int x, int y, int width, int height, int min, int max, int value, bool bIsDefault, CDXUTSlider** ppCreated ) { HRESULT hr = S_OK; - CDXUTSlider* pSlider = new CDXUTSlider( this ); + auto pSlider = new (std::nothrow) CDXUTSlider( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pSlider; - if( pSlider == NULL ) + if( !pSlider ) return E_OUTOFMEMORY; hr = AddControl( pSlider ); @@ -1996,19 +1374,19 @@ HRESULT CDXUTDialog::AddSlider( int ID, int x, int y, int width, int height, int } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddEditBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault, CDXUTEditBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTEditBox* pEditBox = new CDXUTEditBox( this ); + auto pEditBox = new (std::nothrow) CDXUTEditBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pEditBox; - if( pEditBox == NULL ) + if( !pEditBox ) return E_OUTOFMEMORY; hr = AddControl( pEditBox ); @@ -2029,15 +1407,16 @@ HRESULT CDXUTDialog::AddEditBox( int ID, LPCWSTR strText, int x, int y, int widt //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddListBox( int ID, int x, int y, int width, int height, DWORD dwStyle, CDXUTListBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTListBox* pListBox = new CDXUTListBox( this ); + auto pListBox = new (std::nothrow) CDXUTListBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pListBox; - if( pListBox == NULL ) + if( !pListBox ) return E_OUTOFMEMORY; hr = AddControl( pListBox ); @@ -2054,23 +1433,21 @@ HRESULT CDXUTDialog::AddListBox( int ID, int x, int y, int width, int height, DW } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::InitControl( CDXUTControl* pControl ) +HRESULT CDXUTDialog::InitControl( _In_ CDXUTControl* pControl ) { HRESULT hr; - if( pControl == NULL ) + if( !pControl ) return E_INVALIDARG; - pControl->m_Index = m_Controls.GetSize(); + pControl->m_Index = static_cast( m_Controls.size() ); // Look for a default Element entries - for( int i = 0; i < m_DefaultElements.GetSize(); i++ ) + for( auto it = m_DefaultElements.begin(); it != m_DefaultElements.end(); ++it ) { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - if( pElementHolder->nControlType == pControl->GetType() ) - pControl->SetElement( pElementHolder->iElement, &pElementHolder->Element ); + if( (*it)->nControlType == pControl->GetType() ) + pControl->SetElement( (*it)->iElement, &(*it)->Element ); } V_RETURN( pControl->OnInit() ); @@ -2079,9 +1456,8 @@ HRESULT CDXUTDialog::InitControl( CDXUTControl* pControl ) } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::AddControl( CDXUTControl* pControl ) +HRESULT CDXUTDialog::AddControl( _In_ CDXUTControl* pControl ) { HRESULT hr = S_OK; @@ -2090,81 +1466,72 @@ HRESULT CDXUTDialog::AddControl( CDXUTControl* pControl ) return DXTRACE_ERR( L"CDXUTDialog::InitControl", hr ); // Add to the list - hr = m_Controls.Add( pControl ); - if( FAILED( hr ) ) - { - return DXTRACE_ERR( L"CGrowableArray::Add", hr ); - } + m_Controls.push_back( pControl ); return S_OK; } //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetControl( int ID ) +CDXUTControl* CDXUTDialog::GetControl( _In_ int ID ) const { // Try to find the control with the given ID - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl->GetID() == ID ) + if( (*it)->GetID() == ID ) { - return pControl; + return *it; } } // Not found - return NULL; + return nullptr; } - //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetControl( int ID, UINT nControlType ) +CDXUTControl* CDXUTDialog::GetControl( _In_ int ID, _In_ UINT nControlType ) const { // Try to find the control with the given ID - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl->GetID() == ID && pControl->GetType() == nControlType ) + if( (*it)->GetID() == ID && (*it)->GetType() == nControlType ) { - return pControl; + return *it; } } // Not found - return NULL; + return nullptr; } - //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetNextControl( CDXUTControl* pControl ) +CDXUTControl* CDXUTDialog::GetNextControl( _In_ CDXUTControl* pControl ) { int index = pControl->m_Index + 1; - CDXUTDialog* pDialog = pControl->m_pDialog; + auto pDialog = pControl->m_pDialog; // Cycle through dialogs in the loop to find the next control. Note // that if only one control exists in all looped dialogs it will // be the returned 'next' control. - while( index >= ( int )pDialog->m_Controls.GetSize() ) + while( index >= ( int )pDialog->m_Controls.size() ) { pDialog = pDialog->m_pNextDialog; index = 0; } - return pDialog->m_Controls.GetAt( index ); + return pDialog->m_Controls[ index ]; } + //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetPrevControl( CDXUTControl* pControl ) +CDXUTControl* CDXUTDialog::GetPrevControl( _In_ CDXUTControl* pControl ) { int index = pControl->m_Index - 1; - CDXUTDialog* pDialog = pControl->m_pDialog; + auto pDialog = pControl->m_pDialog; // Cycle through dialogs in the loop to find the next control. Note // that if only one control exists in all looped dialogs it will @@ -2172,217 +1539,78 @@ CDXUTControl* CDXUTDialog::GetPrevControl( CDXUTControl* pControl ) while( index < 0 ) { pDialog = pDialog->m_pPrevDialog; - if( pDialog == NULL ) - pDialog = pControl->m_pDialog; - - index = pDialog->m_Controls.GetSize() - 1; - } - - return pDialog->m_Controls.GetAt( index ); -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialog::ClearRadioButtonGroup( UINT nButtonGroup ) -{ - // Find all radio buttons with the given group number - for( int i = 0; i < m_Controls.GetSize(); i++ ) - { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl->GetType() == DXUT_CONTROL_RADIOBUTTON ) - { - CDXUTRadioButton* pRadioButton = ( CDXUTRadioButton* )pControl; - - if( pRadioButton->GetButtonGroup() == nButtonGroup ) - pRadioButton->SetChecked( false, false ); - } - } -} - - - -//-------------------------------------------------------------------------------------- -void CDXUTDialog::ClearComboBox( int ID ) -{ - CDXUTComboBox* pComboBox = GetComboBox( ID ); - if( pComboBox == NULL ) - return; - - pComboBox->RemoveAllItems(); -} - - - - -//-------------------------------------------------------------------------------------- -void CDXUTDialog::RequestFocus( CDXUTControl* pControl ) -{ - if( s_pControlFocus == pControl ) - return; - - if( !pControl->CanHaveFocus() ) - return; - - if( s_pControlFocus ) - s_pControlFocus->OnFocusOut(); - - pControl->OnFocusIn(); - s_pControlFocus = pControl; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawRect( RECT* pRect, D3DCOLOR color ) -{ - if( m_pManager->GetD3D9Device() ) - return DrawRect9( pRect, color ); - return E_FAIL; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawRect9( RECT* pRect, D3DCOLOR color ) -{ - RECT rcScreen = *pRect; - OffsetRect( &rcScreen, m_x, m_y ); - - // If caption is enabled, offset the Y position by its height. - if( m_bCaption ) - OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - - DXUT_SCREEN_VERTEX vertices[4] = - { - ( float )rcScreen.left - 0.5f, ( float )rcScreen.top - 0.5f, 0.5f, 1.0f, color, 0, 0, - ( float )rcScreen.right - 0.5f, ( float )rcScreen.top - 0.5f, 0.5f, 1.0f, color, 0, 0, - ( float )rcScreen.right - 0.5f, ( float )rcScreen.bottom - 0.5f, 0.5f, 1.0f, color, 0, 0, - ( float )rcScreen.left - 0.5f, ( float )rcScreen.bottom - 0.5f, 0.5f, 1.0f, color, 0, 0, - }; - - IDirect3DDevice9* pd3dDevice = m_pManager->GetD3D9Device(); - - // Since we're doing our own drawing here we need to flush the sprites - m_pManager->m_pSprite->Flush(); - IDirect3DVertexDeclaration9* pDecl = NULL; - pd3dDevice->GetVertexDeclaration( &pDecl ); // Preserve the sprite's current vertex decl - pd3dDevice->SetFVF( DXUT_SCREEN_VERTEX::FVF ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2 ); - - pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices, sizeof( DXUT_SCREEN_VERTEX ) ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - - // Restore the vertex decl - pd3dDevice->SetVertexDeclaration( pDecl ); - pDecl->Release(); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawPolyLine( POINT* apPoints, UINT nNumPoints, D3DCOLOR color ) -{ - DXUT_SCREEN_VERTEX* vertices = new DXUT_SCREEN_VERTEX[ nNumPoints ]; - if( vertices == NULL ) - return E_OUTOFMEMORY; - - DXUT_SCREEN_VERTEX* pVertex = vertices; - POINT* pt = apPoints; - for( UINT i = 0; i < nNumPoints; i++ ) - { - pVertex->x = m_x + ( float )pt->x; - pVertex->y = m_y + ( float )pt->y; - pVertex->z = 0.5f; - pVertex->h = 1.0f; - pVertex->color = color; - pVertex->tu = 0.0f; - pVertex->tv = 0.0f; - - pVertex++; - pt++; - } - - IDirect3DDevice9* pd3dDevice = m_pManager->GetD3D9Device(); - - // Since we're doing our own drawing here we need to flush the sprites - m_pManager->m_pSprite->Flush(); - IDirect3DVertexDeclaration9* pDecl = NULL; - pd3dDevice->GetVertexDeclaration( &pDecl ); // Preserve the sprite's current vertex decl - pd3dDevice->SetFVF( DXUT_SCREEN_VERTEX::FVF ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2 ); - - pd3dDevice->DrawPrimitiveUP( D3DPT_LINESTRIP, nNumPoints - 1, vertices, sizeof( DXUT_SCREEN_VERTEX ) ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); + if( !pDialog ) + pDialog = pControl->m_pDialog; - // Restore the vertex decl - pd3dDevice->SetVertexDeclaration( pDecl ); - pDecl->Release(); + index = int( pDialog->m_Controls.size() ) - 1; + } - SAFE_DELETE_ARRAY( vertices ); - return S_OK; + return pDialog->m_Controls[ index ]; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawSprite( CDXUTElement* pElement, RECT* prcDest, float fDepth ) +void CDXUTDialog::ClearRadioButtonGroup( _In_ UINT nButtonGroup ) { - if( m_pManager->GetD3D9Device() ) - return DrawSprite9( pElement, prcDest ); - else - return DrawSprite11( pElement, prcDest, fDepth ); + // Find all radio buttons with the given group number + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) + { + if( (*it)->GetType() == DXUT_CONTROL_RADIOBUTTON ) + { + auto pRadioButton = ( CDXUTRadioButton* )*it; + + if( pRadioButton->GetButtonGroup() == nButtonGroup ) + pRadioButton->SetChecked( false, false ); + } + } } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawSprite9( CDXUTElement* pElement, RECT* prcDest ) +void CDXUTDialog::ClearComboBox( _In_ int ID ) { - // No need to draw fully transparent layers - if( pElement->TextureColor.Current.a == 0 ) - return S_OK; - - RECT rcTexture = pElement->rcTexture; - - RECT rcScreen = *prcDest; - OffsetRect( &rcScreen, m_x, m_y ); + auto pComboBox = GetComboBox( ID ); + if( !pComboBox ) + return; - // If caption is enabled, offset the Y position by its height. - if( m_bCaption ) - OffsetRect( &rcScreen, 0, m_nCaptionHeight ); + pComboBox->RemoveAllItems(); +} - DXUTTextureNode* pTextureNode = GetTexture( pElement->iTexture ); - if( pTextureNode == NULL ) - return E_FAIL; - float fScaleX = ( float )RectWidth( rcScreen ) / RectWidth( rcTexture ); - float fScaleY = ( float )RectHeight( rcScreen ) / RectHeight( rcTexture ); +//-------------------------------------------------------------------------------------- +void CDXUTDialog::RequestFocus( _In_ CDXUTControl* pControl ) +{ + if( s_pControlFocus == pControl ) + return; - D3DXMATRIXA16 matTransform; - D3DXMatrixScaling( &matTransform, fScaleX, fScaleY, 1.0f ); + if( !pControl->CanHaveFocus() ) + return; - m_pManager->m_pSprite->SetTransform( &matTransform ); + if( s_pControlFocus ) + s_pControlFocus->OnFocusOut(); - D3DXVECTOR3 vPos( ( float )rcScreen.left, ( float )rcScreen.top, 0.0f ); + pControl->OnFocusIn(); + s_pControlFocus = pControl; +} - vPos.x /= fScaleX; - vPos.y /= fScaleY; - return m_pManager->m_pSprite->Draw( pTextureNode->pTexture9, &rcTexture, NULL, &vPos, - pElement->TextureColor.Current ); +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTDialog::DrawRect( const RECT* pRect, DWORD color ) +{ + UNREFERENCED_PARAMETER(pRect); + UNREFERENCED_PARAMETER(color); + // TODO - + return E_FAIL; } + //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float fDepth ) +_Use_decl_annotations_ +HRESULT CDXUTDialog::DrawSprite( CDXUTElement* pElement, const RECT* prcDest, float fDepth ) { // No need to draw fully transparent layers - if( pElement->TextureColor.Current.a == 0 ) + if( pElement->TextureColor.Current.w == 0 ) return S_OK; RECT rcTexture = pElement->rcTexture; @@ -2394,8 +1622,8 @@ HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float if( m_bCaption ) OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - DXUTTextureNode* pTextureNode = GetTexture( pElement->iTexture ); - if( pTextureNode == NULL ) + auto pTextureNode = GetTexture( pElement->iTexture ); + if( !pTextureNode ) return E_FAIL; float fBBWidth = ( float )m_pManager->m_nBackBufferWidth; @@ -2419,39 +1647,39 @@ HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float float fTexBottom = rcTexture.bottom / fTexHeight; // Add 6 sprite vertices - DXUTSpriteVertex SpriteVertex; + DXUTSpriteVertex SpriteVertex = {}; // tri1 - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexTop ); + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectLeft, fRectTop, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexLeft, fTexTop ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexRight, fTexTop ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexLeft, fTexBottom ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); // tri2 - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexRight, fTexTop ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexBottom ); + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectRight, fRectBottom, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexRight, fTexBottom ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); + SpriteVertex.vPos = DirectX::XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = DirectX::XMFLOAT2( fTexLeft, fTexBottom ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); // Why are we drawing the sprite every time? This is very inefficient, but the sprite workaround doesn't have support for sorting now, so we have to // draw a sprite every time to keep the order correct between sprites and text. @@ -2462,1003 +1690,1158 @@ HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::CalcTextRect( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, int nCount ) +_Use_decl_annotations_ +HRESULT CDXUTDialog::CalcTextRect( LPCWSTR strText, CDXUTElement* pElement, const RECT* prcDest, int nCount ) { - HRESULT hr = S_OK; - - DXUTFontNode* pFontNode = GetFont( pElement->iFont ); - if( pFontNode == NULL ) + auto pFontNode = GetFont( pElement->iFont ); + if( !pFontNode ) return E_FAIL; - DWORD dwTextFormat = pElement->dwTextFormat | DT_CALCRECT; - // Since we are only computing the rectangle, we don't need a sprite. - if( pFontNode->pFont9 ) + UNREFERENCED_PARAMETER(strText); + UNREFERENCED_PARAMETER(prcDest); + UNREFERENCED_PARAMETER(nCount); + // TODO - + + return S_OK; +} + + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTDialog::DrawText( LPCWSTR strText, CDXUTElement* pElement, const RECT* prcDest, bool bShadow, bool bCenter ) +{ + // No need to draw fully transparent layers + if( pElement->FontColor.Current.w == 0 ) + return S_OK; + + RECT rcScreen = *prcDest; + OffsetRect( &rcScreen, m_x, m_y); + + // If caption is enabled, offset the Y position by its height. + if( m_bCaption ) + OffsetRect( &rcScreen, 0, m_nCaptionHeight ); + + float fBBWidth = ( float )m_pManager->m_nBackBufferWidth; + float fBBHeight = ( float )m_pManager->m_nBackBufferHeight; + + auto pd3dDevice = m_pManager->GetD3D11Device(); + auto pd3d11DeviceContext = m_pManager->GetD3D11DeviceContext(); + + if( bShadow ) { - hr = pFontNode->pFont9->DrawText( NULL, strText, nCount, prcDest, dwTextFormat, pElement->FontColor.Current ); - if( FAILED( hr ) ) - return hr; + RECT rcShadow = rcScreen; + OffsetRect( &rcShadow, 1, 1 ); + + DirectX::XMFLOAT4 vShadowColor( 0,0,0, 1.0f ); + DrawText11DXUT( pd3dDevice, pd3d11DeviceContext, + strText, rcShadow, vShadowColor, + fBBWidth, fBBHeight, bCenter ); + + } + + DirectX::XMFLOAT4 vFontColor( pElement->FontColor.Current.x, pElement->FontColor.Current.y, pElement->FontColor.Current.z, 1.0f ); + DrawText11DXUT( pd3dDevice, pd3d11DeviceContext, + strText, rcScreen, vFontColor, + fBBWidth, fBBHeight, bCenter ); + + return S_OK; +} + + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +void CDXUTDialog::SetBackgroundColors( DWORD colorTopLeft, DWORD colorTopRight, DWORD colorBottomLeft, + DWORD colorBottomRight ) +{ + m_colorTopLeft = colorTopLeft; + m_colorTopRight = colorTopRight; + m_colorBottomLeft = colorBottomLeft; + m_colorBottomRight = colorBottomRight; +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialog::SetNextDialog( _In_ CDXUTDialog* pNextDialog ) +{ + if( !pNextDialog ) + pNextDialog = this; + + m_pNextDialog = pNextDialog; + if( pNextDialog ) + m_pNextDialog->m_pPrevDialog = this; +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialog::ClearFocus() +{ + if( s_pControlFocus ) + { + s_pControlFocus->OnFocusOut(); + s_pControlFocus = nullptr; + } + + ReleaseCapture(); +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialog::FocusDefaultControl() +{ + // Check for default control in this dialog + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) + { + if( (*it)->m_bIsDefault ) + { + // Remove focus from the current control + ClearFocus(); + + // Give focus to the default control + s_pControlFocus = *it; + s_pControlFocus->OnFocusIn(); + return; + } } +} + + +//-------------------------------------------------------------------------------------- +bool CDXUTDialog::OnCycleFocus( _In_ bool bForward ) +{ + CDXUTControl* pControl = nullptr; + CDXUTDialog* pDialog = nullptr; // pDialog and pLastDialog are used to track wrapping of + CDXUTDialog* pLastDialog; // focus from first control to last or vice versa. + + if( !s_pControlFocus ) + { + // If s_pControlFocus is nullptr, we focus the first control of first dialog in + // the case that bForward is true, and focus the last control of last dialog when + // bForward is false. + // + if( bForward ) + { + // Search for the first control from the start of the dialog + // array. + for( auto it = m_pManager->m_Dialogs.cbegin(); it != m_pManager->m_Dialogs.cend(); ++it ) + { + pDialog = pLastDialog = *it; + if( pDialog && !pDialog->m_Controls.empty() ) + { + pControl = pDialog->m_Controls[ 0 ]; + break; + } + } + + if( !pDialog || !pControl ) + { + // No dialog has been registered yet or no controls have been + // added to the dialogs. Cannot proceed. + return true; + } + } + else + { + // Search for the first control from the end of the dialog + // array. + for( auto it = m_pManager->m_Dialogs.crbegin(); it != m_pManager->m_Dialogs.crend(); ++it ) + { + pDialog = pLastDialog = *it; + if( pDialog && !pDialog->m_Controls.empty() ) + { + pControl = pDialog->m_Controls[ pDialog->m_Controls.size() - 1 ]; + break; + } + } + + if( !pDialog || !pControl ) + { + // No dialog has been registered yet or no controls have been + // added to the dialogs. Cannot proceed. + return true; + } + } + } + else if( s_pControlFocus->m_pDialog != this ) + { + // If a control belonging to another dialog has focus, let that other + // dialog handle this event by returning false. + // + return false; + } + else + { + // Focused control belongs to this dialog. Cycle to the + // next/previous control. + assert( pControl != 0 ); + _Analysis_assume_( pControl != 0 ); + pLastDialog = s_pControlFocus->m_pDialog; + pControl = ( bForward ) ? GetNextControl( s_pControlFocus ) : GetPrevControl( s_pControlFocus ); + pDialog = pControl->m_pDialog; + } + + assert( pControl != 0 ); + _Analysis_assume_( pControl != 0 ); + + for( int i = 0; i < 0xffff; i++ ) + { + // If we just wrapped from last control to first or vice versa, + // set the focused control to nullptr. This state, where no control + // has focus, allows the camera to work. + int nLastDialogIndex = -1; + auto fit = std::find( m_pManager->m_Dialogs.cbegin(), m_pManager->m_Dialogs.cend(), pLastDialog ); + if ( fit != m_pManager->m_Dialogs.cend() ) + { + nLastDialogIndex = int( fit - m_pManager->m_Dialogs.begin() ); + } + + int nDialogIndex = -1; + fit = std::find( m_pManager->m_Dialogs.cbegin(), m_pManager->m_Dialogs.cend(), pDialog ); + if ( fit != m_pManager->m_Dialogs.cend() ) + { + nDialogIndex = int( fit - m_pManager->m_Dialogs.begin() ); + } + + if( ( !bForward && nLastDialogIndex < nDialogIndex ) || + ( bForward && nDialogIndex < nLastDialogIndex ) ) + { + if( s_pControlFocus ) + s_pControlFocus->OnFocusOut(); + s_pControlFocus = nullptr; + return true; + } + + // If we've gone in a full circle then focus doesn't change + if( pControl == s_pControlFocus ) + return true; + + // If the dialog accepts keybord input and the control can have focus then + // move focus + if( pControl->m_pDialog->m_bKeyboardInput && pControl->CanHaveFocus() ) + { + if( s_pControlFocus ) + s_pControlFocus->OnFocusOut(); + s_pControlFocus = pControl; + if( s_pControlFocus ) + s_pControlFocus->OnFocusIn(); + return true; + } + + pLastDialog = pDialog; + pControl = ( bForward ) ? GetNextControl( pControl ) : GetPrevControl( pControl ); + pDialog = pControl->m_pDialog; + } + + // If we reached this point, the chain of dialogs didn't form a complete loop + DXTRACE_ERR( L"CDXUTDialog: Multiple dialogs are improperly chained together", E_FAIL ); + return false; +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialog::InitDefaultElements() +{ + SetFont( 0, L"Arial", 14, FW_NORMAL ); + + CDXUTElement Element; + RECT rcTexture; + + //------------------------------------- + // Element for the caption + //------------------------------------- + m_CapElement.SetFont( 0 ); + SetRect( &rcTexture, 17, 269, 241, 287 ); + m_CapElement.SetTexture( 0, &rcTexture ); + m_CapElement.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); + m_CapElement.FontColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); + m_CapElement.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_VCENTER ); + // Pre-blend as we don't need to transition the state + m_CapElement.TextureColor.Blend( DXUT_STATE_NORMAL, 10.0f ); + m_CapElement.FontColor.Blend( DXUT_STATE_NORMAL, 10.0f ); - return S_OK; -} + //------------------------------------- + // CDXUTStatic + //------------------------------------- + Element.SetFont( 0 ); + Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_STATIC, 0, &Element ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawText( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow, int nCount, bool bCenter ) -{ - if( m_pManager->GetD3D9Device() ) - return DrawText9( strText, pElement, prcDest, bShadow, nCount ); - else - return DrawText11( m_pManager->GetD3D11Device(), m_pManager->GetD3D11DeviceContext(), strText, pElement, prcDest, bShadow, nCount, bCenter ); -} + //------------------------------------- + // CDXUTButton - Button + //------------------------------------- + SetRect( &rcTexture, 0, 0, 136, 54 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0 ); + Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); + Element.FontColor.States[ DXUT_STATE_MOUSEOVER ] = D3DCOLOR_ARGB( 255, 0, 0, 0 ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawText9( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow, int nCount ) -{ - HRESULT hr = S_OK; + // Assign the Element + SetDefaultElement( DXUT_CONTROL_BUTTON, 0, &Element ); - // No need to draw fully transparent layers - if( pElement->FontColor.Current.a == 0 ) - return S_OK; - RECT rcScreen = *prcDest; - OffsetRect( &rcScreen, m_x, m_y ); + //------------------------------------- + // CDXUTButton - Fill layer + //------------------------------------- + SetRect( &rcTexture, 136, 0, 252, 54 ); + Element.SetTexture( 0, &rcTexture, D3DCOLOR_ARGB( 0, 255, 255, 255 ) ); + Element.TextureColor.States[ DXUT_STATE_MOUSEOVER ] = D3DCOLOR_ARGB( 160, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 60, 0, 0, 0 ); + Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 30, 255, 255, 255 ); - // If caption is enabled, offset the Y position by its height. - if( m_bCaption ) - OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - D3DXMATRIX matTransform; - D3DXMatrixIdentity( &matTransform ); - m_pManager->m_pSprite->SetTransform( &matTransform ); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_BUTTON, 1, &Element ); - DXUTFontNode* pFontNode = GetFont( pElement->iFont ); - if( bShadow ) - { - RECT rcShadow = rcScreen; - OffsetRect( &rcShadow, 1, 1 ); - hr = pFontNode->pFont9->DrawText( m_pManager->m_pSprite, strText, nCount, &rcShadow, pElement->dwTextFormat, - D3DCOLOR_ARGB( DWORD( pElement->FontColor.Current.a * 255 ), 0, 0, 0 ) ); - if( FAILED( hr ) ) - return hr; - } + //------------------------------------- + // CDXUTCheckBox - Box + //------------------------------------- + SetRect( &rcTexture, 0, 54, 27, 81 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_VCENTER ); + Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); + Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); - hr = pFontNode->pFont9->DrawText( m_pManager->m_pSprite, strText, nCount, &rcScreen, pElement->dwTextFormat, - pElement->FontColor.Current ); - if( FAILED( hr ) ) - return hr; + // Assign the Element + SetDefaultElement( DXUT_CONTROL_CHECKBOX, 0, &Element ); - return S_OK; -} -ID3D11Buffer* g_pFontBuffer11 = NULL; -UINT g_FontBufferBytes11 = 0; -CGrowableArray g_FontVertices; -ID3D11ShaderResourceView* g_pFont11 = NULL; -ID3D11InputLayout* g_pInputLayout11 = NULL; -HRESULT InitFont11( ID3D11Device* pd3d11Device, ID3D11InputLayout* pInputLayout ) -{ - HRESULT hr = S_OK; - WCHAR str[MAX_PATH]; - V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"UI\\Font.dds" ) ); - - if (pd3d11Device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0 ) { - - D3DX11_IMAGE_INFO dii; - D3DX11GetImageInfoFromFile( str, NULL, &dii, NULL ); - - D3DX11_IMAGE_LOAD_INFO dili; - dili.BindFlags = D3DX11_DEFAULT; - dili.CpuAccessFlags = D3DX11_DEFAULT; - dili.Depth = D3DX11_DEFAULT; - dili.Filter = D3DX11_DEFAULT; - dili.FirstMipLevel = 0; - dili.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - dili.Height = D3DX11_DEFAULT; - dili.MipFilter = D3DX11_DEFAULT; - dili.MipLevels = 1; - dili.MiscFlags = D3DX11_DEFAULT; - dili.pSrcInfo = &dii; - dili.Usage = D3D11_USAGE_DEFAULT ; - dili.Width = D3DX11_DEFAULT; - - V_RETURN( D3DX11CreateShaderResourceViewFromFile( pd3d11Device, str, &dili, NULL, &g_pFont11, &hr) ); - } - else - { - V_RETURN( D3DX11CreateShaderResourceViewFromFile( pd3d11Device, str, NULL, NULL, &g_pFont11, &hr) ); - } + //------------------------------------- + // CDXUTCheckBox - Check + //------------------------------------- + SetRect( &rcTexture, 27, 54, 54, 81 ); + Element.SetTexture( 0, &rcTexture ); -#if defined(PROFILE) || defined(DEBUG) - if (g_pFont11) - { - ID3D11Resource *pRes = NULL; - g_pFont11->GetResource( &pRes ); - DXUT_SetDebugName( pRes, "DXUT Text11" ); - SAFE_RELEASE( pRes ); - } + // Assign the Element + SetDefaultElement( DXUT_CONTROL_CHECKBOX, 1, &Element ); - DXUT_SetDebugName( g_pFont11, "DXUT Text11" ); -#endif - g_pInputLayout11 = pInputLayout; - return hr; -} + //------------------------------------- + // CDXUTRadioButton - Box + //------------------------------------- + SetRect( &rcTexture, 54, 54, 81, 81 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_VCENTER ); + Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); + Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); -void EndFont11() -{ - SAFE_RELEASE( g_pFontBuffer11 ); - g_FontBufferBytes11 = 0; - SAFE_RELEASE( g_pFont11 ); -} + // Assign the Element + SetDefaultElement( DXUT_CONTROL_RADIOBUTTON, 0, &Element ); -void BeginText11() -{ - g_FontVertices.Reset(); -} -void DrawText11DXUT( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, RECT rcScreen, D3DXCOLOR vFontColor, - float fBBWidth, float fBBHeight, bool bCenter ) -{ - float fCharTexSizeX = 0.010526315f; - //float fGlyphSizeX = 14.0f / fBBWidth; - //float fGlyphSizeY = 32.0f / fBBHeight; - float fGlyphSizeX = 15.0f / fBBWidth; - float fGlyphSizeY = 42.0f / fBBHeight; + //------------------------------------- + // CDXUTRadioButton - Check + //------------------------------------- + SetRect( &rcTexture, 81, 54, 108, 81 ); + Element.SetTexture( 0, &rcTexture ); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_RADIOBUTTON, 1, &Element ); - float fRectLeft = rcScreen.left / fBBWidth; - float fRectTop = 1.0f - rcScreen.top / fBBHeight; - fRectLeft = fRectLeft * 2.0f - 1.0f; - fRectTop = fRectTop * 2.0f - 1.0f; + //------------------------------------- + // CDXUTComboBox - Main + //------------------------------------- + SetRect( &rcTexture, 7, 81, 247, 123 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0 ); + Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 200, 200, 200 ); + Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 170, 230, 230, 230 ); + Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 70, 200, 200, 200 ); + Element.FontColor.States[ DXUT_STATE_MOUSEOVER ] = D3DCOLOR_ARGB( 255, 0, 0, 0 ); + Element.FontColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 0, 0, 0 ); + Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); - int NumChars = (int)wcslen( strText ); - if (bCenter) { - float fRectRight = rcScreen.right / fBBWidth; - fRectRight = fRectRight * 2.0f - 1.0f; - float fRectBottom = 1.0f - rcScreen.bottom / fBBHeight; - fRectBottom = fRectBottom * 2.0f - 1.0f; - float fcenterx = ((fRectRight - fRectLeft) - (float)NumChars*fGlyphSizeX) *0.5f; - float fcentery = ((fRectTop - fRectBottom) - (float)1*fGlyphSizeY) *0.5f; - fRectLeft += fcenterx ; - fRectTop -= fcentery; - } - float fOriginalLeft = fRectLeft; - float fTexTop = 0.0f; - float fTexBottom = 1.0f; - float fDepth = 0.5f; - for( int i=0; i 126 ) - { - continue; - } - // Add 6 sprite vertices - DXUTSpriteVertex SpriteVertex; - float fRectRight = fRectLeft + fGlyphSizeX; - float fRectBottom = fRectTop - fGlyphSizeY; - float fTexLeft = ( strText[i] - 32 ) * fCharTexSizeX; - float fTexRight = fTexLeft + fCharTexSizeX; + //------------------------------------- + // CDXUTComboBox - Button + //------------------------------------- + SetRect( &rcTexture, 98, 189, 151, 238 ); + Element.SetTexture( 0, &rcTexture ); + Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 150, 150, 150 ); + Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 70, 255, 255, 255 ); - // tri1 - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexTop ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_COMBOBOX, 1, &Element ); - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); + //------------------------------------- + // CDXUTComboBox - Dropdown + //------------------------------------- + SetRect( &rcTexture, 13, 123, 241, 160 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0, D3DCOLOR_ARGB( 255, 0, 0, 0 ), DT_LEFT | DT_TOP ); - // tri2 - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_COMBOBOX, 2, &Element ); - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexBottom ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); + //------------------------------------- + // CDXUTComboBox - Selection + //------------------------------------- + SetRect( &rcTexture, 12, 163, 239, 183 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_TOP ); - fRectLeft += fGlyphSizeX; + // Assign the Element + SetDefaultElement( DXUT_CONTROL_COMBOBOX, 3, &Element ); - } - // We have to end text after every line so that rendering order between sprites and fonts is preserved - EndText11( pd3dDevice, pd3d11DeviceContext ); -} + //------------------------------------- + // CDXUTSlider - Track + //------------------------------------- + SetRect( &rcTexture, 1, 187, 93, 228 ); + Element.SetTexture( 0, &rcTexture ); + Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); + Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 70, 255, 255, 255 ); -void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) -{ + // Assign the Element + SetDefaultElement( DXUT_CONTROL_SLIDER, 0, &Element ); - // ensure our buffer size can hold our sprites - UINT FontDataBytes = g_FontVertices.GetSize() * sizeof( DXUTSpriteVertex ); - if( g_FontBufferBytes11 < FontDataBytes ) - { - SAFE_RELEASE( g_pFontBuffer11 ); - g_FontBufferBytes11 = FontDataBytes; + //------------------------------------- + // CDXUTSlider - Button + //------------------------------------- + SetRect( &rcTexture, 151, 193, 192, 234 ); + Element.SetTexture( 0, &rcTexture ); - D3D11_BUFFER_DESC BufferDesc; - BufferDesc.ByteWidth = g_FontBufferBytes11; - BufferDesc.Usage = D3D11_USAGE_DYNAMIC; - BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - BufferDesc.MiscFlags = 0; + // Assign the Element + SetDefaultElement( DXUT_CONTROL_SLIDER, 1, &Element ); - pd3dDevice->CreateBuffer( &BufferDesc, NULL, &g_pFontBuffer11 ); - DXUT_SetDebugName( g_pFontBuffer11, "DXUT Text11" ); - } + //------------------------------------- + // CDXUTScrollBar - Track + //------------------------------------- + int nScrollBarStartX = 196; + int nScrollBarStartY = 191; + SetRect( &rcTexture, nScrollBarStartX + 0, nScrollBarStartY + 21, nScrollBarStartX + 22, nScrollBarStartY + 32 ); + Element.SetTexture( 0, &rcTexture ); + Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 255, 200, 200, 200 ); + + // Assign the Element + SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 0, &Element ); - // Copy the sprites over - D3D11_BOX destRegion; - destRegion.left = 0; - destRegion.right = FontDataBytes; - destRegion.top = 0; - destRegion.bottom = 1; - destRegion.front = 0; - destRegion.back = 1; - D3D11_MAPPED_SUBRESOURCE MappedResource; - if ( S_OK == pd3d11DeviceContext->Map( g_pFontBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) { - CopyMemory( MappedResource.pData, (void*)g_FontVertices.GetData(), FontDataBytes ); - pd3d11DeviceContext->Unmap(g_pFontBuffer11, 0); - } + //------------------------------------- + // CDXUTScrollBar - Up Arrow + //------------------------------------- + SetRect( &rcTexture, nScrollBarStartX + 0, nScrollBarStartY + 1, nScrollBarStartX + 22, nScrollBarStartY + 21 ); + Element.SetTexture( 0, &rcTexture ); + Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 255, 200, 200, 200 ); - ID3D11ShaderResourceView* pOldTexture = NULL; - pd3d11DeviceContext->PSGetShaderResources( 0, 1, &pOldTexture ); - pd3d11DeviceContext->PSSetShaderResources( 0, 1, &g_pFont11 ); - // Draw - UINT Stride = sizeof( DXUTSpriteVertex ); - UINT Offset = 0; - pd3d11DeviceContext->IASetVertexBuffers( 0, 1, &g_pFontBuffer11, &Stride, &Offset ); - pd3d11DeviceContext->IASetInputLayout( g_pInputLayout11 ); - pd3d11DeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); - pd3d11DeviceContext->Draw( g_FontVertices.GetSize(), 0 ); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 1, &Element ); - pd3d11DeviceContext->PSSetShaderResources( 0, 1, &pOldTexture ); - SAFE_RELEASE( pOldTexture ); + //------------------------------------- + // CDXUTScrollBar - Down Arrow + //------------------------------------- + SetRect( &rcTexture, nScrollBarStartX + 0, nScrollBarStartY + 32, nScrollBarStartX + 22, nScrollBarStartY + 53 ); + Element.SetTexture( 0, &rcTexture ); + Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 255, 200, 200, 200 ); - g_FontVertices.Reset(); -} -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow, int nCount, bool bCenter ) -{ - //HRESULT hr = S_OK; + // Assign the Element + SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 2, &Element ); - // No need to draw fully transparent layers - if( pElement->FontColor.Current.a == 0 ) - return S_OK; + //------------------------------------- + // CDXUTScrollBar - Button + //------------------------------------- + SetRect( &rcTexture, 220, 192, 238, 234 ); + Element.SetTexture( 0, &rcTexture ); - RECT rcScreen = *prcDest; - OffsetRect( &rcScreen, m_x, m_y); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 3, &Element ); - // If caption is enabled, offset the Y position by its height. - if( m_bCaption ) - OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - float fBBWidth = ( float )m_pManager->m_nBackBufferWidth; - float fBBHeight = ( float )m_pManager->m_nBackBufferHeight; + //------------------------------------- + // CDXUTEditBox + //------------------------------------- + // Element assignment: + // 0 - text area + // 1 - top left border + // 2 - top border + // 3 - top right border + // 4 - left border + // 5 - right border + // 6 - lower left border + // 7 - lower border + // 8 - lower right border - if( bShadow ) - { - RECT rcShadow = rcScreen; - OffsetRect( &rcShadow, 1, 1 ); + Element.SetFont( 0, D3DCOLOR_ARGB( 255, 0, 0, 0 ), DT_LEFT | DT_TOP ); - D3DXCOLOR vShadowColor( 0,0,0, 1.0f ); - DrawText11DXUT( pd3dDevice, pd3d11DeviceContext, - strText, rcShadow, vShadowColor, - fBBWidth, fBBHeight, bCenter ); + // Assign the style + SetRect( &rcTexture, 14, 90, 241, 113 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 0, &Element ); + SetRect( &rcTexture, 8, 82, 14, 90 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 1, &Element ); + SetRect( &rcTexture, 14, 82, 241, 90 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 2, &Element ); + SetRect( &rcTexture, 241, 82, 246, 90 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 3, &Element ); + SetRect( &rcTexture, 8, 90, 14, 113 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 4, &Element ); + SetRect( &rcTexture, 241, 90, 246, 113 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 5, &Element ); + SetRect( &rcTexture, 8, 113, 14, 121 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 6, &Element ); + SetRect( &rcTexture, 14, 113, 241, 121 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 7, &Element ); + SetRect( &rcTexture, 241, 113, 246, 121 ); + Element.SetTexture( 0, &rcTexture ); + SetDefaultElement( DXUT_CONTROL_EDITBOX, 8, &Element ); - } + //------------------------------------- + // CDXUTListBox - Main + //------------------------------------- + SetRect( &rcTexture, 13, 123, 241, 160 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0, D3DCOLOR_ARGB( 255, 0, 0, 0 ), DT_LEFT | DT_TOP ); - D3DXCOLOR vFontColor( pElement->FontColor.Current.r, pElement->FontColor.Current.g, pElement->FontColor.Current.b, 1.0f ); - DrawText11DXUT( pd3dDevice, pd3d11DeviceContext, - strText, rcScreen, vFontColor, - fBBWidth, fBBHeight, bCenter ); + // Assign the Element + SetDefaultElement( DXUT_CONTROL_LISTBOX, 0, &Element ); - return S_OK; -} + //------------------------------------- + // CDXUTListBox - Selection + //------------------------------------- + SetRect( &rcTexture, 16, 166, 240, 183 ); + Element.SetTexture( 0, &rcTexture ); + Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_TOP ); -//-------------------------------------------------------------------------------------- -void CDXUTDialog::SetBackgroundColors( D3DCOLOR colorTopLeft, D3DCOLOR colorTopRight, D3DCOLOR colorBottomLeft, - D3DCOLOR colorBottomRight ) -{ - m_colorTopLeft = colorTopLeft; - m_colorTopRight = colorTopRight; - m_colorBottomLeft = colorBottomLeft; - m_colorBottomRight = colorBottomRight; + // Assign the Element + SetDefaultElement( DXUT_CONTROL_LISTBOX, 1, &Element ); } +//====================================================================================== +// CDXUTDialogResourceManager +//====================================================================================== + //-------------------------------------------------------------------------------------- -void CDXUTDialog::SetNextDialog( CDXUTDialog* pNextDialog ) +CDXUTDialogResourceManager::CDXUTDialogResourceManager() noexcept : + m_pVSRenderUI11(nullptr), + m_pPSRenderUI11(nullptr), + m_pPSRenderUIUntex11(nullptr), + m_pDepthStencilStateUI11(nullptr), + m_pRasterizerStateUI11(nullptr), + m_pBlendStateUI11(nullptr), + m_pSamplerStateUI11(nullptr), + m_pDepthStencilStateStored11(nullptr), + m_StencilRefStored11(0), + m_pRasterizerStateStored11(nullptr), + m_pBlendStateStored11(nullptr), + m_BlendFactorStored11{}, + m_SampleMaskStored11(0), + m_pSamplerStateStored11(nullptr), + m_pInputLayout11(nullptr), + m_pVBScreenQuad11(nullptr), + m_pSpriteBuffer11(nullptr), + m_SpriteBufferBytes11(0), + m_nBackBufferWidth(0), + m_nBackBufferHeight(0), + m_pd3d11Device(nullptr), + m_pd3d11DeviceContext(nullptr) { - if( pNextDialog == NULL ) - pNextDialog = this; - - m_pNextDialog = pNextDialog; - if( pNextDialog ) - m_pNextDialog->m_pPrevDialog = this; } //-------------------------------------------------------------------------------------- -void CDXUTDialog::ClearFocus() +CDXUTDialogResourceManager::~CDXUTDialogResourceManager() { - if( s_pControlFocus ) + for( auto it = m_FontCache.begin(); it != m_FontCache.end(); ++it ) { - s_pControlFocus->OnFocusOut(); - s_pControlFocus = NULL; + SAFE_DELETE( *it ); } + m_FontCache.clear(); - ReleaseCapture(); + for( auto it = m_TextureCache.begin(); it != m_TextureCache.end(); ++it ) + { + SAFE_DELETE( *it ); + } + m_TextureCache.clear(); } //-------------------------------------------------------------------------------------- -void CDXUTDialog::FocusDefaultControl() +_Use_decl_annotations_ +bool CDXUTDialogResourceManager::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - // Check for default control in this dialog - for( int i = 0; i < m_Controls.GetSize(); i++ ) - { - CDXUTControl* pControl = m_Controls.GetAt( i ); - if( pControl->m_bIsDefault ) - { - // Remove focus from the current control - ClearFocus(); - - // Give focus to the default control - s_pControlFocus = pControl; - s_pControlFocus->OnFocusIn(); - return; - } - } + UNREFERENCED_PARAMETER(hWnd); + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + return false; } -//-------------------------------------------------------------------------------------- -bool CDXUTDialog::OnCycleFocus( bool bForward ) +_Use_decl_annotations_ +HRESULT CDXUTDialogResourceManager::OnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) { - CDXUTControl* pControl = NULL; - CDXUTDialog* pDialog = NULL; // pDialog and pLastDialog are used to track wrapping of - CDXUTDialog* pLastDialog; // focus from first control to last or vice versa. + m_pd3d11Device = pd3dDevice; + m_pd3d11DeviceContext = pd3d11DeviceContext; - if( s_pControlFocus == NULL ) - { - // If s_pControlFocus is NULL, we focus the first control of first dialog in - // the case that bForward is true, and focus the last control of last dialog when - // bForward is false. - // - if( bForward ) - { - // Search for the first control from the start of the dialog - // array. - for( int d = 0; d < m_pManager->m_Dialogs.GetSize(); ++d ) - { - pDialog = pLastDialog = m_pManager->m_Dialogs.GetAt( d ); - if( pDialog && pDialog->m_Controls.GetSize() > 0 ) - { - pControl = pDialog->m_Controls.GetAt( 0 ); - break; - } - } + HRESULT hr = S_OK; - if( !pDialog || !pControl ) - { - // No dialog has been registered yet or no controls have been - // added to the dialogs. Cannot proceed. - return true; - } - } - else - { - // Search for the first control from the end of the dialog - // array. - for( int d = m_pManager->m_Dialogs.GetSize() - 1; d >= 0; --d ) - { - pDialog = pLastDialog = m_pManager->m_Dialogs.GetAt( d ); - if( pDialog && pDialog->m_Controls.GetSize() > 0 ) - { - pControl = pDialog->m_Controls.GetAt( pDialog->m_Controls.GetSize() - 1 ); - break; - } - } + // Compile Shaders + ID3DBlob* pVSBlob = nullptr; + ID3DBlob* pPSBlob = nullptr; + ID3DBlob* pPSUntexBlob = nullptr; + V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", nullptr, nullptr, "VS", "vs_4_0_level_9_1", + D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pVSBlob, nullptr ) ); + V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", nullptr, nullptr, "PS", "ps_4_0_level_9_1", + D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSBlob, nullptr ) ); + V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", nullptr, nullptr, "PSUntex", "ps_4_0_level_9_1", + D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSUntexBlob, nullptr ) ); - if( !pDialog || !pControl ) - { - // No dialog has been registered yet or no controls have been - // added to the dialogs. Cannot proceed. - return true; - } - } - } - else if( s_pControlFocus->m_pDialog != this ) + // Create Shaders + V_RETURN( pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &m_pVSRenderUI11 ) ); + DXUT_SetDebugName( m_pVSRenderUI11, "CDXUTDialogResourceManager" ); + + V_RETURN( pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &m_pPSRenderUI11 ) ); + DXUT_SetDebugName( m_pPSRenderUI11, "CDXUTDialogResourceManager" ); + + V_RETURN( pd3dDevice->CreatePixelShader( pPSUntexBlob->GetBufferPointer(), pPSUntexBlob->GetBufferSize(), nullptr, &m_pPSRenderUIUntex11 ) ); + DXUT_SetDebugName( m_pPSRenderUIUntex11, "CDXUTDialogResourceManager" ); + + // States + D3D11_DEPTH_STENCIL_DESC DSDesc = {}; + DSDesc.DepthEnable = FALSE; + DSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; + DSDesc.DepthFunc = D3D11_COMPARISON_LESS; + DSDesc.StencilEnable = FALSE; + V_RETURN( pd3dDevice->CreateDepthStencilState( &DSDesc, &m_pDepthStencilStateUI11 ) ); + DXUT_SetDebugName( m_pDepthStencilStateUI11, "CDXUTDialogResourceManager" ); + + D3D11_RASTERIZER_DESC RSDesc; + RSDesc.AntialiasedLineEnable = FALSE; + RSDesc.CullMode = D3D11_CULL_BACK; + RSDesc.DepthBias = 0; + RSDesc.DepthBiasClamp = 0.0f; + RSDesc.DepthClipEnable = TRUE; + RSDesc.FillMode = D3D11_FILL_SOLID; + RSDesc.FrontCounterClockwise = FALSE; + RSDesc.MultisampleEnable = TRUE; + RSDesc.ScissorEnable = FALSE; + RSDesc.SlopeScaledDepthBias = 0.0f; + V_RETURN( pd3dDevice->CreateRasterizerState( &RSDesc, &m_pRasterizerStateUI11 ) ); + DXUT_SetDebugName( m_pRasterizerStateUI11, "CDXUTDialogResourceManager" ); + + D3D11_BLEND_DESC BSDesc = {}; + BSDesc.RenderTarget[0].BlendEnable = TRUE; + BSDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; + BSDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + BSDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + BSDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + BSDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; + BSDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + BSDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; + + V_RETURN( pd3dDevice->CreateBlendState( &BSDesc, &m_pBlendStateUI11 ) ); + DXUT_SetDebugName( m_pBlendStateUI11, "CDXUTDialogResourceManager" ); + + D3D11_SAMPLER_DESC SSDesc = {}; + SSDesc.Filter = D3D11_FILTER_ANISOTROPIC ; + SSDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; + SSDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; + SSDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; + SSDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; + SSDesc.MaxAnisotropy = 16; + SSDesc.MinLOD = 0; + SSDesc.MaxLOD = D3D11_FLOAT32_MAX; + if ( pd3dDevice->GetFeatureLevel() < D3D_FEATURE_LEVEL_9_3 ) { - // If a control belonging to another dialog has focus, let that other - // dialog handle this event by returning false. - // - return false; + SSDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + SSDesc.MaxAnisotropy = 0; } - else + V_RETURN( pd3dDevice->CreateSamplerState( &SSDesc, &m_pSamplerStateUI11 ) ); + DXUT_SetDebugName( m_pSamplerStateUI11, "CDXUTDialogResourceManager" ); + + // Create the texture objects in the cache arrays. + for( size_t i = 0; i < m_TextureCache.size(); i++ ) { - // Focused control belongs to this dialog. Cycle to the - // next/previous control. - pLastDialog = s_pControlFocus->m_pDialog; - pControl = ( bForward ) ? GetNextControl( s_pControlFocus ) : GetPrevControl( s_pControlFocus ); - pDialog = pControl->m_pDialog; + hr = CreateTexture11( static_cast( i ) ); + if( FAILED( hr ) ) + return hr; } - for( int i = 0; i < 0xffff; i++ ) - { - // If we just wrapped from last control to first or vice versa, - // set the focused control to NULL. This state, where no control - // has focus, allows the camera to work. - int nLastDialogIndex = m_pManager->m_Dialogs.IndexOf( pLastDialog ); - int nDialogIndex = m_pManager->m_Dialogs.IndexOf( pDialog ); - if( ( !bForward && nLastDialogIndex < nDialogIndex ) || - ( bForward && nDialogIndex < nLastDialogIndex ) ) + // Create input layout + const D3D11_INPUT_ELEMENT_DESC layout[] = { - if( s_pControlFocus ) - s_pControlFocus->OnFocusOut(); - s_pControlFocus = NULL; - return true; - } + { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + }; - // If we've gone in a full circle then focus doesn't change - if( pControl == s_pControlFocus ) - return true; + V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &m_pInputLayout11 ) ); + DXUT_SetDebugName( m_pInputLayout11, "CDXUTDialogResourceManager" ); - // If the dialog accepts keybord input and the control can have focus then - // move focus - if( pControl->m_pDialog->m_bKeyboardInput && pControl->CanHaveFocus() ) - { - if( s_pControlFocus ) - s_pControlFocus->OnFocusOut(); - s_pControlFocus = pControl; - s_pControlFocus->OnFocusIn(); - return true; - } + // Release the blobs + SAFE_RELEASE( pVSBlob ); + SAFE_RELEASE( pPSBlob ); + SAFE_RELEASE( pPSUntexBlob ); - pLastDialog = pDialog; - pControl = ( bForward ) ? GetNextControl( pControl ) : GetPrevControl( pControl ); - pDialog = pControl->m_pDialog; - } + // Create a vertex buffer quad for rendering later + D3D11_BUFFER_DESC BufDesc; + BufDesc.ByteWidth = sizeof( DXUT_SCREEN_VERTEX_10 ) * 4; + BufDesc.Usage = D3D11_USAGE_DYNAMIC; + BufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + BufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + BufDesc.MiscFlags = 0; + V_RETURN( pd3dDevice->CreateBuffer( &BufDesc, nullptr, &m_pVBScreenQuad11 ) ); + DXUT_SetDebugName( m_pVBScreenQuad11, "CDXUTDialogResourceManager" ); - // If we reached this point, the chain of dialogs didn't form a complete loop - DXTRACE_ERR( L"CDXUTDialog: Multiple dialogs are improperly chained together", E_FAIL ); - return false; + // Init the D3D11 font + InitFont11( pd3dDevice, m_pInputLayout11 ); + + return S_OK; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateFont9( UINT iFont ) +_Use_decl_annotations_ +HRESULT CDXUTDialogResourceManager::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, + const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) { - HRESULT hr = S_OK; - - DXUTFontNode* pFontNode = m_FontCache.GetAt( iFont ); + UNREFERENCED_PARAMETER(pd3dDevice); - SAFE_RELEASE( pFontNode->pFont9 ); + HRESULT hr = S_OK; - V_RETURN( D3DXCreateFont( m_pd3d9Device, pFontNode->nHeight, 0, pFontNode->nWeight, 1, FALSE, DEFAULT_CHARSET, - OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, - pFontNode->strFace, &pFontNode->pFont9 ) ); + m_nBackBufferWidth = pBackBufferSurfaceDesc->Width; + m_nBackBufferHeight = pBackBufferSurfaceDesc->Height; - return S_OK; + return hr; } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateFont11( UINT iFont ) +void CDXUTDialogResourceManager::OnD3D11ReleasingSwapChain() { - return S_OK; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateTexture9( UINT iTexture ) +void CDXUTDialogResourceManager::OnD3D11DestroyDevice() { - HRESULT hr = S_OK; - - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( iTexture ); - - - D3DXIMAGE_INFO info; + // Release the resources but don't clear the cache, as these will need to be + // recreated if the device is recreated - if( !pTextureNode->bFileSource ) + for( auto it = m_TextureCache.begin(); it != m_TextureCache.end(); ++it ) { - if( pTextureNode->nResourceID == 0xFFFF && pTextureNode->hResourceModule == ( HMODULE )0xFFFF ) - { - hr = DXUTCreateGUITextureFromInternalArray9( m_pd3d9Device, &pTextureNode->pTexture9, &info ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"D3DXCreateTextureFromFileInMemoryEx", hr ); - DXUT_SetDebugName( pTextureNode->pTexture9, "DXUT GUI Texture" ); - } - else - { - LPCWSTR pID = pTextureNode->nResourceID ? ( LPCWSTR )( size_t )pTextureNode->nResourceID : - pTextureNode->strFilename; - - // Create texture from resource - hr = D3DXCreateTextureFromResourceEx( m_pd3d9Device, pTextureNode->hResourceModule, pID, D3DX_DEFAULT, - D3DX_DEFAULT, - 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, - &info, NULL, &pTextureNode->pTexture9 ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"D3DXCreateTextureFromResourceEx", hr ); - } + SAFE_RELEASE( (*it)->pTexResView11 ); + SAFE_RELEASE( (*it)->pTexture11 ); } - else - { - // Make sure there's a texture to create - if( pTextureNode->strFilename[0] == 0 ) - return S_OK; - // Create texture from file - hr = D3DXCreateTextureFromFileEx( m_pd3d9Device, pTextureNode->strFilename, D3DX_DEFAULT, D3DX_DEFAULT, - 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, - &info, NULL, &pTextureNode->pTexture9 ); - if( FAILED( hr ) ) - { - return DXTRACE_ERR( L"D3DXCreateTextureFromFileEx", hr ); - } - } + // D3D11 + SAFE_RELEASE( m_pVBScreenQuad11 ); + SAFE_RELEASE( m_pSpriteBuffer11 ); + m_SpriteBufferBytes11 = 0; + SAFE_RELEASE( m_pInputLayout11 ); - // Store dimensions - pTextureNode->dwWidth = info.Width; - pTextureNode->dwHeight = info.Height; + // Shaders + SAFE_RELEASE( m_pVSRenderUI11 ); + SAFE_RELEASE( m_pPSRenderUI11 ); + SAFE_RELEASE( m_pPSRenderUIUntex11 ); - return S_OK; + // States + SAFE_RELEASE( m_pDepthStencilStateUI11 ); + SAFE_RELEASE( m_pRasterizerStateUI11 ); + SAFE_RELEASE( m_pBlendStateUI11 ); + SAFE_RELEASE( m_pSamplerStateUI11 ); + + SAFE_RELEASE( m_pDepthStencilStateStored11 ); + SAFE_RELEASE( m_pRasterizerStateStored11 ); + SAFE_RELEASE( m_pBlendStateStored11 ); + SAFE_RELEASE( m_pSamplerStateStored11 ); + + EndFont11(); } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateTexture11( UINT iTexture ) +void CDXUTDialogResourceManager::StoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ) { - HRESULT hr = S_OK; - - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( iTexture ); - - if( !pTextureNode->bFileSource ) - { - if( pTextureNode->nResourceID == 0xFFFF && pTextureNode->hResourceModule == ( HMODULE )0xFFFF ) - { - hr = DXUTCreateGUITextureFromInternalArray11( m_pd3d11Device, &pTextureNode->pTexture11, NULL ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"D3DX11CreateResourceFromFileInMemory", hr ); - DXUT_SetDebugName( pTextureNode->pTexture11, "DXUT GUI Texture" ); - } - //else - //{ - // LPCWSTR pID = pTextureNode->nResourceID ? ( LPCWSTR )( size_t )pTextureNode->nResourceID : - // pTextureNode->strFilename; - - // D3DX10_IMAGE_INFO SrcInfo; - // D3DX10GetImageInfoFromResource( NULL, pID, NULL, &SrcInfo, NULL ); - - // // Create texture from resource - // ID3D10Resource* pRes; - // D3DX10_IMAGE_LOAD_INFO loadInfo; - // loadInfo.Width = D3DX10_DEFAULT; - // loadInfo.Height = D3DX10_DEFAULT; - // loadInfo.Depth = D3DX10_DEFAULT; - // loadInfo.FirstMipLevel = 0; - // loadInfo.MipLevels = 1; - // loadInfo.Usage = D3D10_USAGE_DEFAULT; - // loadInfo.BindFlags = D3D10_BIND_SHADER_RESOURCE; - // loadInfo.CpuAccessFlags = 0; - // loadInfo.MiscFlags = 0; - // loadInfo.Format = MAKE_TYPELESS( SrcInfo.Format ); - // loadInfo.Filter = D3DX10_FILTER_NONE; - // loadInfo.MipFilter = D3DX10_FILTER_NONE; - // loadInfo.pSrcInfo = &SrcInfo; - - // hr = D3DX10CreateTextureFromResource( m_pd3d10Device, pTextureNode->hResourceModule, pID, &loadInfo, - // NULL, &pRes, NULL ); - // if( FAILED( hr ) ) - // return DXTRACE_ERR( L"D3DX10CreateResourceFromResource", hr ); - // hr = pRes->QueryInterface( __uuidof( ID3D10Texture2D ), ( LPVOID* )&pTextureNode->pTexture10 ); - // SAFE_RELEASE( pRes ); - // if( FAILED( hr ) ) - // return hr; - //} - } - else - { - // - //// Make sure there's a texture to create - //if( pTextureNode->strFilename[0] == 0 ) - // return S_OK; - - //D3DX10_IMAGE_INFO SrcInfo; - //D3DX10GetImageInfoFromFile( pTextureNode->strFilename, NULL, &SrcInfo, NULL ); - - //// Create texture from file - //ID3D10Resource* pRes; - //D3DX10_IMAGE_LOAD_INFO loadInfo; - //loadInfo.Width = D3DX10_DEFAULT; - //loadInfo.Height = D3DX10_DEFAULT; - //loadInfo.Depth = D3DX10_DEFAULT; - //loadInfo.FirstMipLevel = 0; - //loadInfo.MipLevels = 1; - //loadInfo.Usage = D3D10_USAGE_DEFAULT; - //loadInfo.BindFlags = D3D10_BIND_SHADER_RESOURCE; - //loadInfo.CpuAccessFlags = 0; - //loadInfo.MiscFlags = 0; - //loadInfo.Format = MAKE_TYPELESS( SrcInfo.Format ); - //loadInfo.Filter = D3DX10_FILTER_NONE; - //loadInfo.MipFilter = D3DX10_FILTER_NONE; - //loadInfo.pSrcInfo = &SrcInfo; - //hr = D3DX10CreateTextureFromFile( m_pd3d10Device, pTextureNode->strFilename, &loadInfo, NULL, &pRes, NULL ); - //if( FAILED( hr ) ) - //{ - // return DXTRACE_ERR( L"D3DX10CreateResourceFromFileEx", hr ); - //} - //hr = pRes->QueryInterface( __uuidof( ID3D10Texture2D ), ( LPVOID* )&pTextureNode->pTexture10 ); - //SAFE_RELEASE( pRes ); - //if( FAILED( hr ) ) - // return hr; - // - } - - // Store dimensions - D3D11_TEXTURE2D_DESC desc; - pTextureNode->pTexture11->GetDesc( &desc ); - pTextureNode->dwWidth = desc.Width; - pTextureNode->dwHeight = desc.Height; - - // Create resource view - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Format = MAKE_SRGB( desc.Format ); - SRVDesc.Texture2D.MipLevels = 1; - SRVDesc.Texture2D.MostDetailedMip = 0; - hr = m_pd3d11Device->CreateShaderResourceView( pTextureNode->pTexture11, &SRVDesc, &pTextureNode->pTexResView11 ); - DXUT_SetDebugName( pTextureNode->pTexResView11, "DXUT GUI Texture" ); - - return hr; + pd3dImmediateContext->OMGetDepthStencilState( &m_pDepthStencilStateStored11, &m_StencilRefStored11 ); + pd3dImmediateContext->RSGetState( &m_pRasterizerStateStored11 ); + pd3dImmediateContext->OMGetBlendState( &m_pBlendStateStored11, m_BlendFactorStored11, &m_SampleMaskStored11 ); + pd3dImmediateContext->PSGetSamplers( 0, 1, &m_pSamplerStateStored11 ); } //-------------------------------------------------------------------------------------- -void CDXUTDialog::InitDefaultElements() +void CDXUTDialogResourceManager::RestoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ) { - SetFont( 0, L"Arial", 14, FW_NORMAL ); - - CDXUTElement Element; - RECT rcTexture; - - //------------------------------------- - // Element for the caption - //------------------------------------- - m_CapElement.SetFont( 0 ); - SetRect( &rcTexture, 17, 269, 241, 287 ); - m_CapElement.SetTexture( 0, &rcTexture ); - m_CapElement.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); - m_CapElement.FontColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); - m_CapElement.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_VCENTER ); - // Pre-blend as we don't need to transition the state - m_CapElement.TextureColor.Blend( DXUT_STATE_NORMAL, 10.0f ); - m_CapElement.FontColor.Blend( DXUT_STATE_NORMAL, 10.0f ); - - //------------------------------------- - // CDXUTStatic - //------------------------------------- - Element.SetFont( 0 ); - Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); + pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateStored11, m_StencilRefStored11 ); + pd3dImmediateContext->RSSetState( m_pRasterizerStateStored11 ); + pd3dImmediateContext->OMSetBlendState( m_pBlendStateStored11, m_BlendFactorStored11, m_SampleMaskStored11 ); + pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateStored11 ); - // Assign the Element - SetDefaultElement( DXUT_CONTROL_STATIC, 0, &Element ); + SAFE_RELEASE( m_pDepthStencilStateStored11 ); + SAFE_RELEASE( m_pRasterizerStateStored11 ); + SAFE_RELEASE( m_pBlendStateStored11 ); + SAFE_RELEASE( m_pSamplerStateStored11 ); +} - //------------------------------------- - // CDXUTButton - Button - //------------------------------------- - SetRect( &rcTexture, 0, 0, 136, 54 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0 ); - Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); - Element.FontColor.States[ DXUT_STATE_MOUSEOVER ] = D3DCOLOR_ARGB( 255, 0, 0, 0 ); +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::ApplyRenderUI11( _In_ ID3D11DeviceContext* pd3dImmediateContext ) +{ + // Shaders + pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, nullptr, 0 ); + pd3dImmediateContext->HSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->DSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->GSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->PSSetShader( m_pPSRenderUI11, nullptr, 0 ); - // Assign the Element - SetDefaultElement( DXUT_CONTROL_BUTTON, 0, &Element ); + // States + pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); + pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); + float BlendFactor[4] = { 0, 0, 0, 0 }; + pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); + pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); +} - //------------------------------------- - // CDXUTButton - Fill layer - //------------------------------------- - SetRect( &rcTexture, 136, 0, 252, 54 ); - Element.SetTexture( 0, &rcTexture, D3DCOLOR_ARGB( 0, 255, 255, 255 ) ); - Element.TextureColor.States[ DXUT_STATE_MOUSEOVER ] = D3DCOLOR_ARGB( 160, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 60, 0, 0, 0 ); - Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 30, 255, 255, 255 ); +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::ApplyRenderUIUntex11( _In_ ID3D11DeviceContext* pd3dImmediateContext ) +{ + // Shaders + pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, nullptr, 0 ); + pd3dImmediateContext->HSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->DSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->GSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->PSSetShader( m_pPSRenderUIUntex11, nullptr, 0 ); + // States + pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); + pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); + float BlendFactor[4] = { 0, 0, 0, 0 }; + pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); + pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); +} - // Assign the Element - SetDefaultElement( DXUT_CONTROL_BUTTON, 1, &Element ); +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::BeginSprites11( ) +{ + m_SpriteVertices.clear(); +} - //------------------------------------- - // CDXUTCheckBox - Box - //------------------------------------- - SetRect( &rcTexture, 0, 54, 27, 81 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_VCENTER ); - Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); - Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); - // Assign the Element - SetDefaultElement( DXUT_CONTROL_CHECKBOX, 0, &Element ); +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +void CDXUTDialogResourceManager::EndSprites11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) +{ + // ensure our buffer size can hold our sprites + UINT SpriteDataBytes = static_cast( m_SpriteVertices.size() * sizeof( DXUTSpriteVertex ) ); + if( m_SpriteBufferBytes11 < SpriteDataBytes ) + { + SAFE_RELEASE( m_pSpriteBuffer11 ); + m_SpriteBufferBytes11 = SpriteDataBytes; - //------------------------------------- - // CDXUTCheckBox - Check - //------------------------------------- - SetRect( &rcTexture, 27, 54, 54, 81 ); - Element.SetTexture( 0, &rcTexture ); + D3D11_BUFFER_DESC BufferDesc; + BufferDesc.ByteWidth = m_SpriteBufferBytes11; + BufferDesc.Usage = D3D11_USAGE_DYNAMIC; + BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + BufferDesc.MiscFlags = 0; - // Assign the Element - SetDefaultElement( DXUT_CONTROL_CHECKBOX, 1, &Element ); + if ( FAILED(pd3dDevice->CreateBuffer(&BufferDesc, nullptr, &m_pSpriteBuffer11)) ) + { + m_pSpriteBuffer11 = nullptr; + m_SpriteBufferBytes11 = 0; + return; + } + DXUT_SetDebugName( m_pSpriteBuffer11, "CDXUTDialogResourceManager" ); + } + // Copy the sprites over + D3D11_BOX destRegion; + destRegion.left = 0; + destRegion.right = SpriteDataBytes; + destRegion.top = 0; + destRegion.bottom = 1; + destRegion.front = 0; + destRegion.back = 1; + D3D11_MAPPED_SUBRESOURCE MappedResource; + if ( S_OK == pd3dImmediateContext->Map( m_pSpriteBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) + { + memcpy( MappedResource.pData, (const void*)&m_SpriteVertices[0], SpriteDataBytes ); + pd3dImmediateContext->Unmap(m_pSpriteBuffer11, 0); + } - //------------------------------------- - // CDXUTRadioButton - Box - //------------------------------------- - SetRect( &rcTexture, 54, 54, 81, 81 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_VCENTER ); - Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); - Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 255, 255, 255 ); + // Draw + UINT Stride = sizeof( DXUTSpriteVertex ); + UINT Offset = 0; + pd3dImmediateContext->IASetVertexBuffers( 0, 1, &m_pSpriteBuffer11, &Stride, &Offset ); + pd3dImmediateContext->IASetInputLayout( m_pInputLayout11 ); + pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); + pd3dImmediateContext->Draw( static_cast( m_SpriteVertices.size() ), 0 ); - // Assign the Element - SetDefaultElement( DXUT_CONTROL_RADIOBUTTON, 0, &Element ); + m_SpriteVertices.clear(); +} - //------------------------------------- - // CDXUTRadioButton - Check - //------------------------------------- - SetRect( &rcTexture, 81, 54, 108, 81 ); - Element.SetTexture( 0, &rcTexture ); +//-------------------------------------------------------------------------------------- +bool CDXUTDialogResourceManager::RegisterDialog( _In_ CDXUTDialog* pDialog ) +{ + // Check that the dialog isn't already registered. + for( auto it = m_Dialogs.cbegin(); it != m_Dialogs.cend(); ++it ) + { + if( *it == pDialog ) + return true; + } - // Assign the Element - SetDefaultElement( DXUT_CONTROL_RADIOBUTTON, 1, &Element ); + // Add to the list. + m_Dialogs.push_back( pDialog ); + // Set up next and prev pointers. + if( m_Dialogs.size() > 1 ) + m_Dialogs[m_Dialogs.size() - 2]->SetNextDialog( pDialog ); + m_Dialogs[m_Dialogs.size() - 1]->SetNextDialog( m_Dialogs[0] ); - //------------------------------------- - // CDXUTComboBox - Main - //------------------------------------- - SetRect( &rcTexture, 7, 81, 247, 123 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0 ); - Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 200, 200, 200 ); - Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 170, 230, 230, 230 ); - Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 70, 200, 200, 200 ); - Element.FontColor.States[ DXUT_STATE_MOUSEOVER ] = D3DCOLOR_ARGB( 255, 0, 0, 0 ); - Element.FontColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 0, 0, 0 ); - Element.FontColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 200, 200, 200, 200 ); + return true; +} - // Assign the Element - SetDefaultElement( DXUT_CONTROL_COMBOBOX, 0, &Element ); +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::UnregisterDialog( _In_ CDXUTDialog* pDialog ) +{ + // Search for the dialog in the list. + for( size_t i = 0; i < m_Dialogs.size(); ++i ) + { + if( m_Dialogs[ i ] == pDialog ) + { + m_Dialogs.erase( m_Dialogs.begin() + i ); + if( !m_Dialogs.empty() ) + { + int l, r; + if( 0 == i ) + l = int( m_Dialogs.size() - 1 ); + else + l = int(i) - 1; - //------------------------------------- - // CDXUTComboBox - Button - //------------------------------------- - SetRect( &rcTexture, 98, 189, 151, 238 ); - Element.SetTexture( 0, &rcTexture ); - Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_PRESSED ] = D3DCOLOR_ARGB( 255, 150, 150, 150 ); - Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 70, 255, 255, 255 ); + if( m_Dialogs.size() == i ) + r = 0; + else + r = int( i ); - // Assign the Element - SetDefaultElement( DXUT_CONTROL_COMBOBOX, 1, &Element ); + m_Dialogs[l]->SetNextDialog( m_Dialogs[r] ); + } + return; + } + } +} - //------------------------------------- - // CDXUTComboBox - Dropdown - //------------------------------------- - SetRect( &rcTexture, 13, 123, 241, 160 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0, D3DCOLOR_ARGB( 255, 0, 0, 0 ), DT_LEFT | DT_TOP ); +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::EnableKeyboardInputForAllDialogs() +{ + // Enable keyboard input for all registered dialogs + for( auto it = m_Dialogs.begin(); it != m_Dialogs.end(); ++it ) + (*it)->EnableKeyboardInput( true ); +} - // Assign the Element - SetDefaultElement( DXUT_CONTROL_COMBOBOX, 2, &Element ); +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +int CDXUTDialogResourceManager::AddFont( LPCWSTR strFaceName, LONG height, LONG weight ) +{ + // See if this font already exists + for( size_t i = 0; i < m_FontCache.size(); ++i ) + { + auto pFontNode = m_FontCache[ i ]; + size_t nLen = 0; + nLen = wcsnlen( strFaceName, MAX_PATH); + if( 0 == _wcsnicmp( pFontNode->strFace, strFaceName, nLen ) && + pFontNode->nHeight == height && + pFontNode->nWeight == weight ) + { + return static_cast( i ); + } + } - //------------------------------------- - // CDXUTComboBox - Selection - //------------------------------------- - SetRect( &rcTexture, 12, 163, 239, 183 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_TOP ); + // Add a new font and try to create it + auto pNewFontNode = new (std::nothrow) DXUTFontNode; + if( !pNewFontNode ) + return -1; - // Assign the Element - SetDefaultElement( DXUT_CONTROL_COMBOBOX, 3, &Element ); + ZeroMemory( pNewFontNode, sizeof( DXUTFontNode ) ); + wcscpy_s( pNewFontNode->strFace, MAX_PATH, strFaceName ); + pNewFontNode->nHeight = height; + pNewFontNode->nWeight = weight; + m_FontCache.push_back( pNewFontNode ); + int iFont = (int)m_FontCache.size() - 1; - //------------------------------------- - // CDXUTSlider - Track - //------------------------------------- - SetRect( &rcTexture, 1, 187, 93, 228 ); - Element.SetTexture( 0, &rcTexture ); - Element.TextureColor.States[ DXUT_STATE_NORMAL ] = D3DCOLOR_ARGB( 150, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_FOCUS ] = D3DCOLOR_ARGB( 200, 255, 255, 255 ); - Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 70, 255, 255, 255 ); + // If a device is available, try to create immediately + return iFont; +} - // Assign the Element - SetDefaultElement( DXUT_CONTROL_SLIDER, 0, &Element ); - //------------------------------------- - // CDXUTSlider - Button - //------------------------------------- - SetRect( &rcTexture, 151, 193, 192, 234 ); - Element.SetTexture( 0, &rcTexture ); +//-------------------------------------------------------------------------------------- +int CDXUTDialogResourceManager::AddTexture( _In_z_ LPCWSTR strFilename ) +{ + // See if this texture already exists + for( size_t i = 0; i < m_TextureCache.size(); ++i ) + { + auto pTextureNode = m_TextureCache[ i ]; + size_t nLen = 0; + nLen = wcsnlen( strFilename, MAX_PATH); + if( pTextureNode->bFileSource && // Sources must match + 0 == _wcsnicmp( pTextureNode->strFilename, strFilename, nLen ) ) + { + return static_cast( i ); + } + } - // Assign the Element - SetDefaultElement( DXUT_CONTROL_SLIDER, 1, &Element ); + // Add a new texture and try to create it + auto pNewTextureNode = new (std::nothrow) DXUTTextureNode; + if( !pNewTextureNode ) + return -1; - //------------------------------------- - // CDXUTScrollBar - Track - //------------------------------------- - int nScrollBarStartX = 196; - int nScrollBarStartY = 191; - SetRect( &rcTexture, nScrollBarStartX + 0, nScrollBarStartY + 21, nScrollBarStartX + 22, nScrollBarStartY + 32 ); - Element.SetTexture( 0, &rcTexture ); - Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 255, 200, 200, 200 ); + ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); + pNewTextureNode->bFileSource = true; + wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strFilename ); - // Assign the Element - SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 0, &Element ); + m_TextureCache.push_back( pNewTextureNode ); - //------------------------------------- - // CDXUTScrollBar - Up Arrow - //------------------------------------- - SetRect( &rcTexture, nScrollBarStartX + 0, nScrollBarStartY + 1, nScrollBarStartX + 22, nScrollBarStartY + 21 ); - Element.SetTexture( 0, &rcTexture ); - Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 255, 200, 200, 200 ); + int iTexture = int( m_TextureCache.size() ) - 1; + // If a device is available, try to create immediately - // Assign the Element - SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 1, &Element ); + return iTexture; +} - //------------------------------------- - // CDXUTScrollBar - Down Arrow - //------------------------------------- - SetRect( &rcTexture, nScrollBarStartX + 0, nScrollBarStartY + 32, nScrollBarStartX + 22, nScrollBarStartY + 53 ); - Element.SetTexture( 0, &rcTexture ); - Element.TextureColor.States[ DXUT_STATE_DISABLED ] = D3DCOLOR_ARGB( 255, 200, 200, 200 ); +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +int CDXUTDialogResourceManager::AddTexture( LPCWSTR strResourceName, HMODULE hResourceModule ) +{ + // See if this texture already exists + for( size_t i = 0; i < m_TextureCache.size(); i++ ) + { + auto pTextureNode = m_TextureCache[ i ]; + if( !pTextureNode->bFileSource && // Sources must match + pTextureNode->hResourceModule == hResourceModule ) // Module handles must match + { + if( IS_INTRESOURCE( strResourceName ) ) + { + // Integer-based ID + if( ( INT_PTR )strResourceName == pTextureNode->nResourceID ) + return static_cast( i ); + } + else + { + // String-based ID + size_t nLen = 0; + nLen = wcsnlen ( strResourceName, MAX_PATH ); + if( 0 == _wcsnicmp( pTextureNode->strFilename, strResourceName, nLen ) ) + return static_cast( i ); + } + } + } + + // Add a new texture and try to create it + auto pNewTextureNode = new (std::nothrow) DXUTTextureNode; + if( !pNewTextureNode ) + return -1; + + ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); + pNewTextureNode->hResourceModule = hResourceModule; + if( IS_INTRESOURCE( strResourceName ) ) + { + pNewTextureNode->nResourceID = ( int )( size_t )strResourceName; + } + else + { + pNewTextureNode->nResourceID = 0; + wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strResourceName ); + } - // Assign the Element - SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 2, &Element ); + m_TextureCache.push_back( pNewTextureNode ); - //------------------------------------- - // CDXUTScrollBar - Button - //------------------------------------- - SetRect( &rcTexture, 220, 192, 238, 234 ); - Element.SetTexture( 0, &rcTexture ); + int iTexture = int( m_TextureCache.size() ) - 1; - // Assign the Element - SetDefaultElement( DXUT_CONTROL_SCROLLBAR, 3, &Element ); + // If a device is available, try to create immediately + return iTexture; +} - //------------------------------------- - // CDXUTEditBox - //------------------------------------- - // Element assignment: - // 0 - text area - // 1 - top left border - // 2 - top border - // 3 - top right border - // 4 - left border - // 5 - right border - // 6 - lower left border - // 7 - lower border - // 8 - lower right border - Element.SetFont( 0, D3DCOLOR_ARGB( 255, 0, 0, 0 ), DT_LEFT | DT_TOP ); +//-------------------------------------------------------------------------------------- +HRESULT CDXUTDialogResourceManager::CreateTexture11( _In_ UINT iTexture ) +{ + HRESULT hr = S_OK; - // Assign the style - SetRect( &rcTexture, 14, 90, 241, 113 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 0, &Element ); - SetRect( &rcTexture, 8, 82, 14, 90 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 1, &Element ); - SetRect( &rcTexture, 14, 82, 241, 90 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 2, &Element ); - SetRect( &rcTexture, 241, 82, 246, 90 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 3, &Element ); - SetRect( &rcTexture, 8, 90, 14, 113 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 4, &Element ); - SetRect( &rcTexture, 241, 90, 246, 113 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 5, &Element ); - SetRect( &rcTexture, 8, 113, 14, 121 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 6, &Element ); - SetRect( &rcTexture, 14, 113, 241, 121 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 7, &Element ); - SetRect( &rcTexture, 241, 113, 246, 121 ); - Element.SetTexture( 0, &rcTexture ); - SetDefaultElement( DXUT_CONTROL_EDITBOX, 8, &Element ); + auto pTextureNode = m_TextureCache[ iTexture ]; - //------------------------------------- - // CDXUTListBox - Main - //------------------------------------- - SetRect( &rcTexture, 13, 123, 241, 160 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0, D3DCOLOR_ARGB( 255, 0, 0, 0 ), DT_LEFT | DT_TOP ); + if( !pTextureNode->bFileSource ) + { + if( pTextureNode->nResourceID == 0xFFFF && pTextureNode->hResourceModule == ( HMODULE )0xFFFF ) + { + hr = DXUTCreateGUITextureFromInternalArray( m_pd3d11Device, &pTextureNode->pTexture11 ); + if( FAILED( hr ) ) + return DXTRACE_ERR( L"DXUTCreateGUITextureFromInternalArray", hr ); + DXUT_SetDebugName( pTextureNode->pTexture11, "DXUT GUI Texture" ); + } + } - // Assign the Element - SetDefaultElement( DXUT_CONTROL_LISTBOX, 0, &Element ); + // Store dimensions + D3D11_TEXTURE2D_DESC desc; + pTextureNode->pTexture11->GetDesc( &desc ); + pTextureNode->dwWidth = desc.Width; + pTextureNode->dwHeight = desc.Height; - //------------------------------------- - // CDXUTListBox - Selection - //------------------------------------- + // Create resource view + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Format = desc.Format; + SRVDesc.Texture2D.MipLevels = 1; + SRVDesc.Texture2D.MostDetailedMip = 0; + hr = m_pd3d11Device->CreateShaderResourceView( pTextureNode->pTexture11, &SRVDesc, &pTextureNode->pTexResView11 ); + if ( FAILED(hr) ) + return hr; - SetRect( &rcTexture, 16, 166, 240, 183 ); - Element.SetTexture( 0, &rcTexture ); - Element.SetFont( 0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), DT_LEFT | DT_TOP ); + DXUT_SetDebugName( pTextureNode->pTexResView11, "DXUT GUI Texture" ); - // Assign the Element - SetDefaultElement( DXUT_CONTROL_LISTBOX, 1, &Element ); + return hr; } - -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTControl class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTControl::CDXUTControl( CDXUTDialog* pDialog ) +CDXUTControl::CDXUTControl( _In_opt_ CDXUTDialog* pDialog ) noexcept { m_Type = DXUT_CONTROL_BUTTON; m_pDialog = pDialog; m_ID = 0; + m_nHotkey = 0; m_Index = 0; - m_pUserData = NULL; + m_pUserData = nullptr; m_bEnabled = true; m_bVisible = true; @@ -3466,7 +2849,7 @@ CDXUTControl::CDXUTControl( CDXUTDialog* pDialog ) m_bHasFocus = false; m_bIsDefault = false; - m_pDialog = NULL; + m_pDialog = nullptr; m_x = 0; m_y = 0; @@ -3477,20 +2860,22 @@ CDXUTControl::CDXUTControl( CDXUTDialog* pDialog ) } +//-------------------------------------------------------------------------------------- CDXUTControl::~CDXUTControl() { - for( int i = 0; i < m_Elements.GetSize(); ++i ) + for( auto it = m_Elements.begin(); it != m_Elements.end(); ++it ) { - delete m_Elements[i]; + auto pElement = *it; + delete pElement; } - m_Elements.RemoveAll(); + m_Elements.clear(); } //-------------------------------------------------------------------------------------- -void CDXUTControl::SetTextColor( D3DCOLOR Color ) +void CDXUTControl::SetTextColor( _In_ DWORD Color ) { - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; if( pElement ) pElement->FontColor.States[DXUT_STATE_NORMAL] = Color; @@ -3498,30 +2883,23 @@ void CDXUTControl::SetTextColor( D3DCOLOR Color ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTControl::SetElement( UINT iElement, CDXUTElement* pElement ) +HRESULT CDXUTControl::SetElement( _In_ UINT iElement, _In_ CDXUTElement* pElement ) { - HRESULT hr = S_OK; - - if( pElement == NULL ) + if( !pElement ) return E_INVALIDARG; // Make certain the array is this large - for( UINT i = m_Elements.GetSize(); i <= iElement; i++ ) + for( size_t i = m_Elements.size(); i <= iElement; i++ ) { - CDXUTElement* pNewElement = new CDXUTElement(); - if( pNewElement == NULL ) + auto pNewElement = new (std::nothrow) CDXUTElement(); + if( !pNewElement ) return E_OUTOFMEMORY; - hr = m_Elements.Add( pNewElement ); - if( FAILED( hr ) ) - { - SAFE_DELETE( pNewElement ); - return hr; - } + m_Elements.push_back( pNewElement ); } // Update the data - CDXUTElement* pCurElement = m_Elements.GetAt( iElement ); + auto pCurElement = m_Elements[ iElement ]; *pCurElement = *pElement; return S_OK; @@ -3534,10 +2912,9 @@ void CDXUTControl::Refresh() m_bMouseOver = false; m_bHasFocus = false; - for( int i = 0; i < m_Elements.GetSize(); i++ ) + for( auto it = m_Elements.begin(); it != m_Elements.end(); ++it ) { - CDXUTElement* pElement = m_Elements.GetAt( i ); - pElement->Refresh(); + (*it)->Refresh(); } } @@ -3549,30 +2926,30 @@ void CDXUTControl::UpdateRects() } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTStatic class -//-------------------------------------------------------------------------------------- +//====================================================================================== //-------------------------------------------------------------------------------------- -CDXUTStatic::CDXUTStatic( CDXUTDialog* pDialog ) +CDXUTStatic::CDXUTStatic( _In_opt_ CDXUTDialog* pDialog ) noexcept { m_Type = DXUT_CONTROL_STATIC; m_pDialog = pDialog; ZeroMemory( &m_strText, sizeof( m_strText ) ); - for( int i = 0; i < m_Elements.GetSize(); i++ ) + for( auto it = m_Elements.begin(); it != m_Elements.end(); ++it ) { - CDXUTElement* pElement = m_Elements.GetAt( i ); + auto pElement = *it; SAFE_DELETE( pElement ); } - m_Elements.RemoveAll(); + m_Elements.clear(); } //-------------------------------------------------------------------------------------- -void CDXUTStatic::Render( float fElapsedTime ) +void CDXUTStatic::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -3582,20 +2959,20 @@ void CDXUTStatic::Render( float fElapsedTime ) if( m_bEnabled == false ) iState = DXUT_STATE_DISABLED; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; pElement->FontColor.Blend( iState, fElapsedTime ); - m_pDialog->DrawText( m_strText, pElement, &m_rcBoundingBox, false, -1, false); + m_pDialog->DrawText( m_strText, pElement, &m_rcBoundingBox, false, false); } //-------------------------------------------------------------------------------------- -HRESULT CDXUTStatic::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ) +_Use_decl_annotations_ +HRESULT CDXUTStatic::GetTextCopy( LPWSTR strDest, UINT bufferCount ) const { // Validate incoming parameters - if( strDest == NULL || bufferCount == 0 ) + if( !strDest || bufferCount == 0 ) { return E_INVALIDARG; } @@ -3608,9 +2985,9 @@ HRESULT CDXUTStatic::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, //-------------------------------------------------------------------------------------- -HRESULT CDXUTStatic::SetText( LPCWSTR strText ) +HRESULT CDXUTStatic::SetText( _In_z_ LPCWSTR strText ) { - if( strText == NULL ) + if( !strText ) { m_strText[0] = 0; return S_OK; @@ -3621,12 +2998,11 @@ HRESULT CDXUTStatic::SetText( LPCWSTR strText ) } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTButton class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTButton::CDXUTButton( CDXUTDialog* pDialog ) +CDXUTButton::CDXUTButton( _In_opt_ CDXUTDialog* pDialog ) noexcept { m_Type = DXUT_CONTROL_BUTTON; m_pDialog = pDialog; @@ -3636,8 +3012,12 @@ CDXUTButton::CDXUTButton( CDXUTDialog* pDialog ) } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) + { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3672,8 +3052,12 @@ bool CDXUTButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTButton::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3722,7 +3106,7 @@ bool CDXUTButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam } //-------------------------------------------------------------------------------------- -void CDXUTButton::Render( float fElapsedTime ) +void CDXUTButton::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -3760,7 +3144,7 @@ void CDXUTButton::Render( float fElapsedTime ) } // Background fill layer - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; @@ -3773,38 +3157,41 @@ void CDXUTButton::Render( float fElapsedTime ) pElement->FontColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &rcWindow, DXUT_FAR_BUTTON_DEPTH ); - m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, -1, true ); + m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, true ); // Main button - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); pElement->FontColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &rcWindow, DXUT_NEAR_BUTTON_DEPTH ); - m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, -1, true ); + m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, true ); } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTCheckBox class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTCheckBox::CDXUTCheckBox( CDXUTDialog* pDialog ) +CDXUTCheckBox::CDXUTCheckBox( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_bChecked(false), + m_rcButton{}, + m_rcText{} { m_Type = DXUT_CONTROL_CHECKBOX; m_pDialog = pDialog; - - m_bChecked = false; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTCheckBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3839,8 +3226,12 @@ bool CDXUTCheckBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTCheckBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTCheckBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3887,6 +3278,7 @@ bool CDXUTCheckBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTCheckBox::SetCheckedInternal( bool bChecked, bool bFromInput ) { m_bChecked = bChecked; @@ -3896,14 +3288,13 @@ void CDXUTCheckBox::SetCheckedInternal( bool bChecked, bool bFromInput ) //-------------------------------------------------------------------------------------- -BOOL CDXUTCheckBox::ContainsPoint( POINT pt ) +bool CDXUTCheckBox::ContainsPoint( _In_ const POINT& pt ) { return ( PtInRect( &m_rcBoundingBox, pt ) || PtInRect( &m_rcButton, pt ) ); } - //-------------------------------------------------------------------------------------- void CDXUTCheckBox::UpdateRects() { @@ -3917,9 +3308,8 @@ void CDXUTCheckBox::UpdateRects() } - //-------------------------------------------------------------------------------------- -void CDXUTCheckBox::Render( float fElapsedTime ) +void CDXUTCheckBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -3936,7 +3326,7 @@ void CDXUTCheckBox::Render( float fElapsedTime ) else if( m_bHasFocus ) iState = DXUT_STATE_FOCUS; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; @@ -3944,26 +3334,24 @@ void CDXUTCheckBox::Render( float fElapsedTime ) pElement->FontColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcButton, DXUT_NEAR_BUTTON_DEPTH ); - m_pDialog->DrawText( m_strText, pElement, &m_rcText, false, -1, false ); + m_pDialog->DrawText( m_strText, pElement, &m_rcText, false, false ); if( !m_bChecked ) iState = DXUT_STATE_HIDDEN; - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcButton, DXUT_FAR_BUTTON_DEPTH ); } - - -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTRadioButton class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTRadioButton::CDXUTRadioButton( CDXUTDialog* pDialog ) +CDXUTRadioButton::CDXUTRadioButton( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_nButtonGroup(0) { m_Type = DXUT_CONTROL_RADIOBUTTON; m_pDialog = pDialog; @@ -3972,8 +3360,11 @@ CDXUTRadioButton::CDXUTRadioButton( CDXUTDialog* pDialog ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTRadioButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4012,8 +3403,12 @@ bool CDXUTRadioButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTRadioButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTRadioButton::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4064,6 +3459,7 @@ bool CDXUTRadioButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM l } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTRadioButton::SetCheckedInternal( bool bChecked, bool bClearGroup, bool bFromInput ) { if( bChecked && bClearGroup ) @@ -4074,24 +3470,24 @@ void CDXUTRadioButton::SetCheckedInternal( bool bChecked, bool bClearGroup, bool } - - -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTComboBox class -//-------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------- -CDXUTComboBox::CDXUTComboBox( CDXUTDialog* pDialog ) : m_ScrollBar( pDialog ) +//====================================================================================== + +CDXUTComboBox::CDXUTComboBox( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_iSelected(-1), + m_iFocused(-1), + m_nDropHeight(100), + m_ScrollBar( pDialog ), + m_nSBWidth(16), + m_bOpened(false), + m_rcText{}, + m_rcButton{}, + m_rcDropdown{}, + m_rcDropdownText{} { m_Type = DXUT_CONTROL_COMBOBOX; - m_pDialog = pDialog; - - m_nDropHeight = 100; - - m_nSBWidth = 16; - m_bOpened = false; - m_iSelected = -1; - m_iFocused = -1; + m_pDialog = pDialog; } @@ -4103,14 +3499,14 @@ CDXUTComboBox::~CDXUTComboBox() //-------------------------------------------------------------------------------------- -void CDXUTComboBox::SetTextColor( D3DCOLOR Color ) +void CDXUTComboBox::SetTextColor( _In_ DWORD Color ) { - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; if( pElement ) pElement->FontColor.States[DXUT_STATE_NORMAL] = Color; - pElement = m_Elements.GetAt( 2 ); + pElement = m_Elements[ 2 ]; if( pElement ) pElement->FontColor.States[DXUT_STATE_NORMAL] = Color; @@ -4130,20 +3526,20 @@ void CDXUTComboBox::UpdateRects() m_rcText.right = m_rcButton.left; m_rcDropdown = m_rcText; - OffsetRect( &m_rcDropdown, 0, ( int )( 0.90f * RectHeight( m_rcText ) ) ); + OffsetRect( &m_rcDropdown, 0, static_cast( 0.90f * RectHeight( m_rcText ) ) ); m_rcDropdown.bottom += m_nDropHeight; m_rcDropdown.right -= m_nSBWidth; m_rcDropdownText = m_rcDropdown; - m_rcDropdownText.left += ( int )( 0.1f * RectWidth( m_rcDropdown ) ); - m_rcDropdownText.right -= ( int )( 0.1f * RectWidth( m_rcDropdown ) ); - m_rcDropdownText.top += ( int )( 0.1f * RectHeight( m_rcDropdown ) ); - m_rcDropdownText.bottom -= ( int )( 0.1f * RectHeight( m_rcDropdown ) ); + m_rcDropdownText.left += static_cast(0.1f * RectWidth(m_rcDropdown)); + m_rcDropdownText.right -= static_cast(0.1f * RectWidth(m_rcDropdown)); + m_rcDropdownText.top += static_cast(0.1f * RectHeight(m_rcDropdown)); + m_rcDropdownText.bottom -= static_cast(0.1f * RectHeight(m_rcDropdown)); // Update the scrollbar's rects m_ScrollBar.SetLocation( m_rcDropdown.right, m_rcDropdown.top + 2 ); m_ScrollBar.SetSize( m_nSBWidth, RectHeight( m_rcDropdown ) - 2 ); - DXUTFontNode* pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements.GetAt( 2 )->iFont ); + auto pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements[ 2 ]->iFont ); if( pFontNode && pFontNode->nHeight ) { m_ScrollBar.SetPageSize( RectHeight( m_rcDropdownText ) / pFontNode->nHeight ); @@ -4165,6 +3561,7 @@ void CDXUTComboBox::OnFocusOut() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTComboBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { const DWORD REPEAT_MASK = ( 0x40000000 ); @@ -4251,7 +3648,8 @@ bool CDXUTComboBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTComboBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) return false; @@ -4267,13 +3665,13 @@ bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar if( m_bOpened && PtInRect( &m_rcDropdown, pt ) ) { // Determine which item has been selected - for( int i = 0; i < m_Items.GetSize(); i++ ) + for( size_t i = 0; i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->bVisible && PtInRect( &pItem->rcActive, pt ) ) { - m_iFocused = i; + m_iFocused = static_cast( i ); } } return true; @@ -4312,13 +3710,13 @@ bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar if( m_bOpened && PtInRect( &m_rcDropdown, pt ) ) { // Determine which item has been selected - for( int i = m_ScrollBar.GetTrackPos(); i < m_Items.GetSize(); i++ ) + for( size_t i = m_ScrollBar.GetTrackPos(); i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->bVisible && PtInRect( &pItem->rcActive, pt ) ) { - m_iFocused = m_iSelected = i; + m_iFocused = m_iSelected = static_cast( i ); m_pDialog->SendEvent( EVENT_COMBOBOX_SELECTION_CHANGED, true, this ); m_bOpened = false; @@ -4371,8 +3769,9 @@ bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar int zDelta = ( short )HIWORD( wParam ) / WHEEL_DELTA; if( m_bOpened ) { - UINT uLines; - SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &uLines, 0 ); + UINT uLines = 0; + if ( !SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &uLines, 0) ) + uLines = 0; m_ScrollBar.Scroll( -zDelta * uLines ); } else @@ -4422,7 +3821,7 @@ void CDXUTComboBox::OnHotkey() m_iSelected++; - if( m_iSelected >= ( int )m_Items.GetSize() ) + if( m_iSelected >= ( int )m_Items.size() ) m_iSelected = 0; m_iFocused = m_iSelected; @@ -4431,17 +3830,18 @@ void CDXUTComboBox::OnHotkey() //-------------------------------------------------------------------------------------- -void CDXUTComboBox::Render( float fElapsedTime ) +void CDXUTComboBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; + DXUT_CONTROL_STATE iState = DXUT_STATE_NORMAL; if( !m_bOpened ) iState = DXUT_STATE_HIDDEN; // Dropdown box - CDXUTElement* pElement = m_Elements.GetAt( 2 ); + auto pElement = m_Elements[ 2 ]; // If we have not initialized the scroll bar page size, // do that now. @@ -4468,20 +3868,19 @@ void CDXUTComboBox::Render( float fElapsedTime ) m_pDialog->DrawSprite( pElement, &m_rcDropdown, DXUT_NEAR_BUTTON_DEPTH ); // Selection outline - CDXUTElement* pSelectionElement = m_Elements.GetAt( 3 ); + auto pSelectionElement = m_Elements[ 3 ]; pSelectionElement->TextureColor.Current = pElement->TextureColor.Current; - pSelectionElement->FontColor.Current = pSelectionElement->FontColor.States[ DXUT_STATE_NORMAL ]; + pSelectionElement->FontColor.SetCurrent( pSelectionElement->FontColor.States[ DXUT_STATE_NORMAL ] ); - DXUTFontNode* pFont = m_pDialog->GetFont( pElement->iFont ); + auto pFont = m_pDialog->GetFont( pElement->iFont ); if( pFont ) { int curY = m_rcDropdownText.top; int nRemainingHeight = RectHeight( m_rcDropdownText ); - //WCHAR strDropdown[4096] = {0}; - - for( int i = m_ScrollBar.GetTrackPos(); i < m_Items.GetSize(); i++ ) + + for( size_t i = m_ScrollBar.GetTrackPos(); i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; // Make sure there's room left in the dropdown nRemainingHeight -= pFont->nHeight; @@ -4494,10 +3893,6 @@ void CDXUTComboBox::Render( float fElapsedTime ) SetRect( &pItem->rcActive, m_rcDropdownText.left, curY, m_rcDropdownText.right, curY + pFont->nHeight ); curY += pFont->nHeight; - //debug - //int blue = 50 * i; - //m_pDialog->DrawRect( &pItem->rcActive, 0xFFFF0000 | blue ); - pItem->bVisible = true; if( m_bOpened ) @@ -4505,7 +3900,7 @@ void CDXUTComboBox::Render( float fElapsedTime ) if( ( int )i == m_iFocused ) { RECT rc; - SetRect( &rc, m_rcDropdown.left, pItem->rcActive.top - 2, m_rcDropdown.right, + SetRect( &rc, m_rcDropdown.left, pItem->rcActive.top, m_rcDropdown.right, pItem->rcActive.bottom + 2 ); m_pDialog->DrawSprite( pSelectionElement, &rc, DXUT_NEAR_BUTTON_DEPTH ); m_pDialog->DrawText( pItem->strText, pSelectionElement, &pItem->rcActive ); @@ -4547,7 +3942,7 @@ void CDXUTComboBox::Render( float fElapsedTime ) float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; // Button - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -4560,7 +3955,7 @@ void CDXUTComboBox::Render( float fElapsedTime ) iState = DXUT_STATE_PRESSED; // Main text box - pElement = m_Elements.GetAt( 0 ); + pElement = m_Elements[ 0 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -4568,12 +3963,12 @@ void CDXUTComboBox::Render( float fElapsedTime ) m_pDialog->DrawSprite( pElement, &m_rcText, DXUT_NEAR_BUTTON_DEPTH ); - if( m_iSelected >= 0 && m_iSelected < ( int )m_Items.GetSize() ) + if( m_iSelected >= 0 && m_iSelected < ( int )m_Items.size() ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( m_iSelected ); - if( pItem != NULL ) + auto pItem = m_Items[ m_iSelected ]; + if( pItem ) { - m_pDialog->DrawText( pItem->strText, pElement, &m_rcText, false, -1, true ); + m_pDialog->DrawText( pItem->strText, pElement, &m_rcText, false, true ); } } @@ -4581,17 +3976,18 @@ void CDXUTComboBox::Render( float fElapsedTime ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTComboBox::AddItem( const WCHAR* strText, void* pData ) { // Validate parameters - if( strText == NULL ) + if( !strText ) { return E_INVALIDARG; } // Create a new item and set the data - DXUTComboBoxItem* pItem = new DXUTComboBoxItem; - if( pItem == NULL ) + auto pItem = new (std::nothrow) DXUTComboBoxItem; + if( !pItem ) { return DXTRACE_ERR_MSGBOX( L"new", E_OUTOFMEMORY ); } @@ -4600,10 +3996,10 @@ HRESULT CDXUTComboBox::AddItem( const WCHAR* strText, void* pData ) wcscpy_s( pItem->strText, 256, strText ); pItem->pData = pData; - m_Items.Add( pItem ); + m_Items.push_back( pItem ); // Update the scroll bar with new range - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); // If this is the only item in the list, it's selected if( GetNumItems() == 1 ) @@ -4618,53 +4014,53 @@ HRESULT CDXUTComboBox::AddItem( const WCHAR* strText, void* pData ) //-------------------------------------------------------------------------------------- -void CDXUTComboBox::RemoveItem( UINT index ) +void CDXUTComboBox::RemoveItem( _In_ UINT index ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( index ); + auto it = m_Items.begin() + index; + auto pItem = *it; SAFE_DELETE( pItem ); - m_Items.Remove( index ); - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - if( m_iSelected >= m_Items.GetSize() ) - m_iSelected = m_Items.GetSize() - 1; + m_Items.erase( it ); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); + if( m_iSelected >= (int)m_Items.size() ) + m_iSelected = (int)m_Items.size() - 1; } //-------------------------------------------------------------------------------------- void CDXUTComboBox::RemoveAllItems() { - for( int i = 0; i < m_Items.GetSize(); i++ ) + for( auto it = m_Items.begin(); it != m_Items.end(); ++it ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = *it; SAFE_DELETE( pItem ); } - m_Items.RemoveAll(); + m_Items.clear(); m_ScrollBar.SetTrackRange( 0, 1 ); m_iFocused = m_iSelected = -1; } - //-------------------------------------------------------------------------------------- -bool CDXUTComboBox::ContainsItem( const WCHAR* strText, UINT iStart ) +bool CDXUTComboBox::ContainsItem( _In_z_ const WCHAR* strText, _In_ UINT iStart ) { return ( -1 != FindItem( strText, iStart ) ); } //-------------------------------------------------------------------------------------- -int CDXUTComboBox::FindItem( const WCHAR* strText, UINT iStart ) +int CDXUTComboBox::FindItem( _In_z_ const WCHAR* strText, _In_ UINT iStart ) const { - if( strText == NULL ) + if( !strText ) return -1; - for( int i = iStart; i < m_Items.GetSize(); i++ ) + for( size_t i = iStart; i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( 0 == wcscmp( pItem->strText, strText ) ) { - return i; + return static_cast( i ); } } @@ -4673,40 +4069,40 @@ int CDXUTComboBox::FindItem( const WCHAR* strText, UINT iStart ) //-------------------------------------------------------------------------------------- -void* CDXUTComboBox::GetSelectedData() +void* CDXUTComboBox::GetSelectedData() const { if( m_iSelected < 0 ) - return NULL; + return nullptr; - DXUTComboBoxItem* pItem = m_Items.GetAt( m_iSelected ); + auto pItem = m_Items[ m_iSelected ]; return pItem->pData; } //-------------------------------------------------------------------------------------- -DXUTComboBoxItem* CDXUTComboBox::GetSelectedItem() +DXUTComboBoxItem* CDXUTComboBox::GetSelectedItem() const { if( m_iSelected < 0 ) - return NULL; + return nullptr; - return m_Items.GetAt( m_iSelected ); + return m_Items[ m_iSelected ]; } //-------------------------------------------------------------------------------------- -void* CDXUTComboBox::GetItemData( const WCHAR* strText ) +void* CDXUTComboBox::GetItemData( _In_z_ const WCHAR* strText ) const { int index = FindItem( strText ); if( index == -1 ) { - return NULL; + return nullptr; } - DXUTComboBoxItem* pItem = m_Items.GetAt( index ); - if( pItem == NULL ) + auto pItem = m_Items[ index ]; + if( !pItem ) { - DXTRACE_ERR( L"CGrowableArray::GetAt", E_FAIL ); - return NULL; + DXTRACE_ERR( L"CDXUTComboBox::GetItemData", E_FAIL ); + return nullptr; } return pItem->pData; @@ -4714,17 +4110,17 @@ void* CDXUTComboBox::GetItemData( const WCHAR* strText ) //-------------------------------------------------------------------------------------- -void* CDXUTComboBox::GetItemData( int nIndex ) +void* CDXUTComboBox::GetItemData( _In_ int nIndex ) const { - if( nIndex < 0 || nIndex >= m_Items.GetSize() ) - return NULL; + if( nIndex < 0 || nIndex >= (int)m_Items.size() ) + return nullptr; - return m_Items.GetAt( nIndex )->pData; + return m_Items[ nIndex ]->pData; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTComboBox::SetSelectedByIndex( UINT index ) +HRESULT CDXUTComboBox::SetSelectedByIndex( _In_ UINT index ) { if( index >= GetNumItems() ) return E_INVALIDARG; @@ -4738,9 +4134,9 @@ HRESULT CDXUTComboBox::SetSelectedByIndex( UINT index ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTComboBox::SetSelectedByText( const WCHAR* strText ) +HRESULT CDXUTComboBox::SetSelectedByText( _In_z_ const WCHAR* strText ) { - if( strText == NULL ) + if( !strText ) return E_INVALIDARG; int index = FindItem( strText ); @@ -4756,15 +4152,15 @@ HRESULT CDXUTComboBox::SetSelectedByText( const WCHAR* strText ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTComboBox::SetSelectedByData( void* pData ) +HRESULT CDXUTComboBox::SetSelectedByData( _In_ void* pData ) { - for( int i = 0; i < m_Items.GetSize(); i++ ) + for( size_t i = 0; i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->pData == pData ) { - m_iFocused = m_iSelected = i; + m_iFocused = m_iSelected = static_cast( i ); m_pDialog->SendEvent( EVENT_COMBOBOX_SELECTION_CHANGED, false, this ); return S_OK; } @@ -4774,23 +4170,27 @@ HRESULT CDXUTComboBox::SetSelectedByData( void* pData ) } +//====================================================================================== +// CDXUTSlider class +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTSlider::CDXUTSlider( CDXUTDialog* pDialog ) +CDXUTSlider::CDXUTSlider( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_nValue(50), + m_nMin(0), + m_nMax(100), + m_nDragX(0), + m_nDragOffset(0), + m_nButtonX(0), + m_bPressed(false), + m_rcButton{} { m_Type = DXUT_CONTROL_SLIDER; m_pDialog = pDialog; - - m_nMin = 0; - m_nMax = 100; - m_nValue = 50; - - m_bPressed = false; } //-------------------------------------------------------------------------------------- -BOOL CDXUTSlider::ContainsPoint( POINT pt ) +bool CDXUTSlider::ContainsPoint( _In_ const POINT& pt ) { return ( PtInRect( &m_rcBoundingBox, pt ) || PtInRect( &m_rcButton, pt ) ); @@ -4810,15 +4210,21 @@ void CDXUTSlider::UpdateRects() OffsetRect( &m_rcButton, m_nButtonX, 0 ); } -int CDXUTSlider::ValueFromPos( int x ) + +//-------------------------------------------------------------------------------------- +int CDXUTSlider::ValueFromPos( _In_ int x ) { float fValuePerPixel = ( float )( m_nMax - m_nMin ) / RectWidth( m_rcBoundingBox ); return ( int )( 0.5f + m_nMin + fValuePerPixel * ( x - m_rcBoundingBox.left ) ); } + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTSlider::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4866,8 +4272,11 @@ bool CDXUTSlider::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTSlider::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTSlider::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4957,7 +4366,7 @@ bool CDXUTSlider::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam //-------------------------------------------------------------------------------------- -void CDXUTSlider::SetRange( int nMin, int nMax ) +void CDXUTSlider::SetRange( _In_ int nMin, _In_ int nMax ) { m_nMin = nMin; m_nMax = nMax; @@ -4967,11 +4376,11 @@ void CDXUTSlider::SetRange( int nMin, int nMax ) //-------------------------------------------------------------------------------------- -void CDXUTSlider::SetValueInternal( int nValue, bool bFromInput ) +void CDXUTSlider::SetValueInternal( _In_ int nValue, _In_ bool bFromInput ) { // Clamp to range - nValue = __max( m_nMin, nValue ); - nValue = __min( m_nMax, nValue ); + nValue = std::max( m_nMin, nValue ); + nValue = std::min( m_nMax, nValue ); if( nValue == m_nValue ) return; @@ -4984,7 +4393,7 @@ void CDXUTSlider::SetValueInternal( int nValue, bool bFromInput ) //-------------------------------------------------------------------------------------- -void CDXUTSlider::Render( float fElapsedTime ) +void CDXUTSlider::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -5023,13 +4432,13 @@ void CDXUTSlider::Render( float fElapsedTime ) float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcBoundingBox, DXUT_FAR_BUTTON_DEPTH ); - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -5037,29 +4446,27 @@ void CDXUTSlider::Render( float fElapsedTime ) } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTScrollBar class -//-------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------- -CDXUTScrollBar::CDXUTScrollBar( CDXUTDialog* pDialog ) +//====================================================================================== + +CDXUTScrollBar::CDXUTScrollBar( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_bShowThumb(true), + m_bDrag(false), + m_rcUpButton{}, + m_rcDownButton{}, + m_rcTrack{}, + m_rcThumb{}, + m_nPosition(0), + m_nPageSize(1), + m_nStart(0), + m_nEnd(1), + m_LastMouse{ 0, 0 }, + m_Arrow(CLEAR), + m_dArrowTS(0.0) { m_Type = DXUT_CONTROL_SCROLLBAR; m_pDialog = pDialog; - - m_bShowThumb = true; - m_bDrag = false; - - SetRect( &m_rcUpButton, 0, 0, 0, 0 ); - SetRect( &m_rcDownButton, 0, 0, 0, 0 ); - SetRect( &m_rcTrack, 0, 0, 0, 0 ); - SetRect( &m_rcThumb, 0, 0, 0, 0 ); - m_nPosition = 0; - m_nPageSize = 1; - m_nStart = 0; - m_nEnd = 1; - m_Arrow = CLEAR; - m_dArrowTS = 0.0; } @@ -5095,7 +4502,7 @@ void CDXUTScrollBar::UpdateThumbRect() { if( m_nEnd - m_nStart > m_nPageSize ) { - int nThumbHeight = __max( RectHeight( m_rcTrack ) * m_nPageSize / ( m_nEnd - m_nStart ), + int nThumbHeight = std::max( RectHeight( m_rcTrack ) * m_nPageSize / ( m_nEnd - m_nStart ), SCROLLBAR_MINTHUMBSIZE ); int nMaxPosition = m_nEnd - m_nStart - m_nPageSize; m_rcThumb.top = m_rcTrack.top + ( m_nPosition - m_nStart ) * ( RectHeight( m_rcTrack ) - nThumbHeight ) @@ -5116,7 +4523,7 @@ void CDXUTScrollBar::UpdateThumbRect() //-------------------------------------------------------------------------------------- // Scroll() scrolls by nDelta items. A positive value scrolls down, while a negative // value scrolls up. -void CDXUTScrollBar::Scroll( int nDelta ) +void CDXUTScrollBar::Scroll( _In_ int nDelta ) { // Perform scroll m_nPosition += nDelta; @@ -5130,7 +4537,7 @@ void CDXUTScrollBar::Scroll( int nDelta ) //-------------------------------------------------------------------------------------- -void CDXUTScrollBar::ShowItem( int nIndex ) +void CDXUTScrollBar::ShowItem( _In_ int nIndex ) { // Cap the index @@ -5152,15 +4559,23 @@ void CDXUTScrollBar::ShowItem( int nIndex ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTScrollBar::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } //-------------------------------------------------------------------------------------- -bool CDXUTScrollBar::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTScrollBar::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + static int ThumbOffsetY; m_LastMouse = pt; @@ -5270,8 +4685,11 @@ bool CDXUTScrollBar::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPa //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTScrollBar::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + if( WM_CAPTURECHANGED == uMsg ) { // The application just lost mouse capture. We may not have gotten @@ -5285,7 +4703,7 @@ bool CDXUTScrollBar::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTScrollBar::Render( float fElapsedTime ) +void CDXUTScrollBar::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -5355,28 +4773,28 @@ void CDXUTScrollBar::Render( float fElapsedTime ) float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; // Background track layer - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcTrack, DXUT_FAR_BUTTON_DEPTH ); // Up Arrow - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcUpButton, DXUT_NEAR_BUTTON_DEPTH ); // Down Arrow - pElement = m_Elements.GetAt( 2 ); + pElement = m_Elements[ 2 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcDownButton, DXUT_NEAR_BUTTON_DEPTH ); // Thumb button - pElement = m_Elements.GetAt( 3 ); + pElement = m_Elements[ 3 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -5386,7 +4804,7 @@ void CDXUTScrollBar::Render( float fElapsedTime ) //-------------------------------------------------------------------------------------- -void CDXUTScrollBar::SetTrackRange( int nStart, int nEnd ) +void CDXUTScrollBar::SetTrackRange( _In_ int nStart, _In_ int nEnd ) { m_nStart = nStart; m_nEnd = nEnd; Cap(); @@ -5406,24 +4824,26 @@ void CDXUTScrollBar::Cap() // Clips position at boundaries. Ensures it stays wi m_nPosition = m_nEnd - m_nPageSize + 1; } -//-------------------------------------------------------------------------------------- -// CDXUTListBox class -//-------------------------------------------------------------------------------------- -//-------------------------------------------------------------------------------------- -CDXUTListBox::CDXUTListBox( CDXUTDialog* pDialog ) : m_ScrollBar( pDialog ) +//====================================================================================== +// CDXUTListBox class +//====================================================================================== + +CDXUTListBox::CDXUTListBox( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_rcText{}, + m_rcSelection{}, + m_ScrollBar(pDialog), + m_nSBWidth(16), + m_nBorder(6), + m_nMargin(5), + m_nTextHeight(0), + m_dwStyle(0), + m_nSelected(-1), + m_nSelStart(0), + m_bDrag(false) { m_Type = DXUT_CONTROL_LISTBOX; m_pDialog = pDialog; - - m_dwStyle = 0; - m_nSBWidth = 16; - m_nSelected = -1; - m_nSelStart = 0; - m_bDrag = false; - m_nBorder = 6; - m_nMargin = 5; - m_nTextHeight = 0; } @@ -5448,7 +4868,7 @@ void CDXUTListBox::UpdateRects() // Update the scrollbar's rects m_ScrollBar.SetLocation( m_rcBoundingBox.right - m_nSBWidth, m_rcBoundingBox.top ); m_ScrollBar.SetSize( m_nSBWidth, m_height ); - DXUTFontNode* pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements.GetAt( 0 )->iFont ); + auto pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements[ 0 ]->iFont ); if( pFontNode && pFontNode->nHeight ) { m_ScrollBar.SetPageSize( RectHeight( m_rcText ) / pFontNode->nHeight ); @@ -5461,9 +4881,10 @@ void CDXUTListBox::UpdateRects() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTListBox::AddItem( const WCHAR* wszText, void* pData ) { - DXUTListBoxItem* pNewItem = new DXUTListBoxItem; + auto pNewItem = new (std::nothrow) DXUTListBoxItem; if( !pNewItem ) return E_OUTOFMEMORY; @@ -5472,24 +4893,18 @@ HRESULT CDXUTListBox::AddItem( const WCHAR* wszText, void* pData ) SetRect( &pNewItem->rcActive, 0, 0, 0, 0 ); pNewItem->bSelected = false; - HRESULT hr = m_Items.Add( pNewItem ); - if( FAILED( hr ) ) - { - SAFE_DELETE( pNewItem ); - } - else - { - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - } + m_Items.push_back( pNewItem ); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); - return hr; + return S_OK; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTListBox::InsertItem( int nIndex, const WCHAR* wszText, void* pData ) { - DXUTListBoxItem* pNewItem = new DXUTListBoxItem; + auto pNewItem = new (std::nothrow) DXUTListBoxItem; if( !pNewItem ) return E_OUTOFMEMORY; @@ -5498,56 +4913,50 @@ HRESULT CDXUTListBox::InsertItem( int nIndex, const WCHAR* wszText, void* pData SetRect( &pNewItem->rcActive, 0, 0, 0, 0 ); pNewItem->bSelected = false; - HRESULT hr = m_Items.Insert( nIndex, pNewItem ); - if( SUCCEEDED( hr ) ) - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - else - SAFE_DELETE( pNewItem ); + m_Items[ nIndex ] = pNewItem; + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); - return hr; + return S_OK; } //-------------------------------------------------------------------------------------- -void CDXUTListBox::RemoveItem( int nIndex ) +void CDXUTListBox::RemoveItem( _In_ int nIndex ) { - if( nIndex < 0 || nIndex >= ( int )m_Items.GetSize() ) + if( nIndex < 0 || nIndex >= ( int )m_Items.size() ) return; - DXUTListBoxItem* pItem = m_Items.GetAt( nIndex ); - + auto it = m_Items.begin() + nIndex; + auto pItem = *it; delete pItem; - m_Items.Remove( nIndex ); - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - if( m_nSelected >= ( int )m_Items.GetSize() ) - m_nSelected = m_Items.GetSize() - 1; + m_Items.erase(it); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); + if( m_nSelected >= ( int )m_Items.size() ) + m_nSelected = int( m_Items.size() ) - 1; m_pDialog->SendEvent( EVENT_LISTBOX_SELECTION, true, this ); } - - - //-------------------------------------------------------------------------------------- void CDXUTListBox::RemoveAllItems() { - for( int i = 0; i < m_Items.GetSize(); ++i ) + for( auto it = m_Items.begin(); it != m_Items.end(); ++it ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = *it; delete pItem; } - m_Items.RemoveAll(); + m_Items.clear(); m_ScrollBar.SetTrackRange( 0, 1 ); } //-------------------------------------------------------------------------------------- -DXUTListBoxItem* CDXUTListBox::GetItem( int nIndex ) +DXUTListBoxItem* CDXUTListBox::GetItem( _In_ int nIndex ) const { - if( nIndex < 0 || nIndex >= ( int )m_Items.GetSize() ) - return NULL; + if( nIndex < 0 || nIndex >= ( int )m_Items.size() ) + return nullptr; return m_Items[nIndex]; } @@ -5560,7 +4969,7 @@ DXUTListBoxItem* CDXUTListBox::GetItem( int nIndex ) // subsequent searches, the app passes the returned index back to GetSelectedIndex as. // nPreviousSelected. // Returns -1 on error or if no item is selected. -int CDXUTListBox::GetSelectedIndex( int nPreviousSelected ) +int CDXUTListBox::GetSelectedIndex( _In_ int nPreviousSelected ) const { if( nPreviousSelected < -1 ) return -1; @@ -5568,9 +4977,9 @@ int CDXUTListBox::GetSelectedIndex( int nPreviousSelected ) if( m_dwStyle & MULTISELECTION ) { // Multiple selection enabled. Search for the next item with the selected flag. - for( int i = nPreviousSelected + 1; i < ( int )m_Items.GetSize(); ++i ) + for( int i = nPreviousSelected + 1; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->bSelected ) return i; @@ -5587,10 +4996,10 @@ int CDXUTListBox::GetSelectedIndex( int nPreviousSelected ) //-------------------------------------------------------------------------------------- -void CDXUTListBox::SelectItem( int nNewIndex ) +void CDXUTListBox::SelectItem( _In_ int nNewIndex ) { // If no item exists, do nothing. - if( m_Items.GetSize() == 0 ) + if( m_Items.size() == 0 ) return; int nOldSelected = m_nSelected; @@ -5601,8 +5010,8 @@ void CDXUTListBox::SelectItem( int nNewIndex ) // Perform capping if( m_nSelected < 0 ) m_nSelected = 0; - if( m_nSelected >= ( int )m_Items.GetSize() ) - m_nSelected = m_Items.GetSize() - 1; + if( m_nSelected >= ( int )m_Items.size() ) + m_nSelected = int( m_Items.size() ) - 1; if( nOldSelected != m_nSelected ) { @@ -5623,6 +5032,7 @@ void CDXUTListBox::SelectItem( int nNewIndex ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) @@ -5645,7 +5055,7 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) case VK_END: { // If no item exists, do nothing. - if( m_Items.GetSize() == 0 ) + if( m_Items.size() == 0 ) return true; int nOldSelected = m_nSelected; @@ -5664,14 +5074,14 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) case VK_HOME: m_nSelected = 0; break; case VK_END: - m_nSelected = m_Items.GetSize() - 1; break; + m_nSelected = int( m_Items.size() ) - 1; break; } // Perform capping if( m_nSelected < 0 ) m_nSelected = 0; - if( m_nSelected >= ( int )m_Items.GetSize() ) - m_nSelected = m_Items.GetSize() - 1; + if( m_nSelected >= ( int )m_Items.size() ) + m_nSelected = int( m_Items.size() ) - 1; if( nOldSelected != m_nSelected ) { @@ -5680,9 +5090,9 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) // Multiple selection // Clear all selection - for( int i = 0; i < ( int )m_Items.GetSize(); ++i ) + for( int i = 0; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items[i]; + auto pItem = m_Items[i]; pItem->bSelected = false; } @@ -5690,9 +5100,9 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { // Select all items from m_nSelStart to // m_nSelected - int nEnd = __max( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); - for( int n = __min( m_nSelStart, m_nSelected ); n <= nEnd; ++n ) + for( int n = std::min( m_nSelStart, m_nSelected ); n <= nEnd; ++n ) m_Items[n]->bSelected = true; } else @@ -5731,7 +5141,8 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTListBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) return false; @@ -5750,7 +5161,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: // Check for clicks in the text area - if( m_Items.GetSize() > 0 && PtInRect( &m_rcSelection, pt ) ) + if( !m_Items.empty() && PtInRect( &m_rcSelection, pt ) ) { // Compute the index of the clicked item @@ -5763,7 +5174,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Only proceed if the click falls on top of an item. if( nClicked >= m_ScrollBar.GetTrackPos() && - nClicked < ( int )m_Items.GetSize() && + nClicked < ( int )m_Items.size() && nClicked < m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize() ) { SetCapture( DXUTGetHWND() ); @@ -5789,7 +5200,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara { // Determine behavior based on the state of Shift and Ctrl - DXUTListBoxItem* pSelItem = m_Items.GetAt( m_nSelected ); + auto pSelItem = m_Items[ m_nSelected ]; if( ( wParam & ( MK_SHIFT | MK_CONTROL ) ) == MK_CONTROL ) { // Control click. Reverse the selection of this item. @@ -5802,24 +5213,24 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // from last selected item to the current item. // Clear everything else. - int nBegin = __min( m_nSelStart, m_nSelected ); - int nEnd = __max( m_nSelStart, m_nSelected ); + int nBegin = std::min( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); for( int i = 0; i < nBegin; ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = false; } - for( int i = nEnd + 1; i < ( int )m_Items.GetSize(); ++i ) + for( int i = nEnd + 1; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = false; } for( int i = nBegin; i <= nEnd; ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = true; } } @@ -5832,15 +5243,15 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // the same state as m_nSelStart, not including m_nSelected. // Set m_nSelected to selected. - int nBegin = __min( m_nSelStart, m_nSelected ); - int nEnd = __max( m_nSelStart, m_nSelected ); + int nBegin = std::min( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); // The two ends do not need to be set here. - bool bLastSelected = m_Items.GetAt( m_nSelStart )->bSelected; + bool bLastSelected = m_Items[ m_nSelStart ]->bSelected; for( int i = nBegin + 1; i < nEnd; ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = bLastSelected; } @@ -5857,9 +5268,9 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // item. - for( int i = 0; i < ( int )m_Items.GetSize(); ++i ) + for( int i = 0; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = false; } @@ -5883,9 +5294,9 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara { // Set all items between m_nSelStart and m_nSelected to // the same state as m_nSelStart - int nEnd = __max( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); - for( int n = __min( m_nSelStart, m_nSelected ) + 1; n < nEnd; ++n ) + for( int n = std::min( m_nSelStart, m_nSelected ) + 1; n < nEnd; ++n ) m_Items[n]->bSelected = m_Items[m_nSelStart]->bSelected; m_Items[m_nSelected]->bSelected = m_Items[m_nSelStart]->bSelected; @@ -5914,7 +5325,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Only proceed if the cursor is on top of an item. if( nItem >= ( int )m_ScrollBar.GetTrackPos() && - nItem < ( int )m_Items.GetSize() && + nItem < ( int )m_Items.size() && nItem < m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize() ) { m_nSelected = nItem; @@ -5931,7 +5342,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara { // User drags the mouse below window bottom m_ScrollBar.Scroll( 1 ); - m_nSelected = __min( ( int )m_Items.GetSize(), m_ScrollBar.GetTrackPos() + + m_nSelected = std::min( ( int )m_Items.size(), m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize() ) - 1; m_pDialog->SendEvent( EVENT_LISTBOX_SELECTION, true, this ); } @@ -5940,8 +5351,9 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara case WM_MOUSEWHEEL: { - UINT uLines; - SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &uLines, 0 ); + UINT uLines = 0; + if ( !SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &uLines, 0 ) ) + uLines = 0; int nScrollAmount = int( ( short )HIWORD( wParam ) ) / WHEEL_DELTA * uLines; m_ScrollBar.Scroll( -nScrollAmount ); return true; @@ -5953,8 +5365,11 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTListBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + if( WM_CAPTURECHANGED == uMsg ) { // The application just lost mouse capture. We may not have gotten @@ -5968,23 +5383,23 @@ bool CDXUTListBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTListBox::Render( float fElapsedTime ) +void CDXUTListBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; pElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); pElement->FontColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); - CDXUTElement* pSelElement = m_Elements.GetAt( 1 ); + auto pSelElement = m_Elements[ 1 ]; pSelElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); pSelElement->FontColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); m_pDialog->DrawSprite( pElement, &m_rcBoundingBox, DXUT_FAR_BUTTON_DEPTH ); // Render the text - if( m_Items.GetSize() > 0 ) + if( !m_Items.empty() ) { // Find out the height of a single line of text RECT rc = m_rcText; @@ -6006,12 +5421,12 @@ void CDXUTListBox::Render( float fElapsedTime ) } rc.right = m_rcText.right; - for( int i = m_ScrollBar.GetTrackPos(); i < ( int )m_Items.GetSize(); ++i ) + for( int i = m_ScrollBar.GetTrackPos(); i < ( int )m_Items.size(); ++i ) { if( rc.bottom > m_rcText.bottom ) break; - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; // Determine if we need to render this item with the // selected element. @@ -6048,54 +5463,41 @@ void CDXUTListBox::Render( float fElapsedTime ) } -// Static member initialization -HINSTANCE CUniBuffer::s_hDll = NULL; -HRESULT ( WINAPI*CUniBuffer::_ScriptApplyDigitSubstitution )( const SCRIPT_DIGITSUBSTITUTE*, SCRIPT_CONTROL*, - SCRIPT_STATE* ) = Dummy_ScriptApplyDigitSubstitution; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringAnalyse )( HDC, const void*, int, int, int, DWORD, int, SCRIPT_CONTROL*, - SCRIPT_STATE*, const int*, SCRIPT_TABDEF*, const BYTE*, - SCRIPT_STRING_ANALYSIS* ) = Dummy_ScriptStringAnalyse; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringCPtoX )( SCRIPT_STRING_ANALYSIS, int, BOOL, int* ) = Dummy_ScriptStringCPtoX; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringXtoCP )( SCRIPT_STRING_ANALYSIS, int, int*, int* ) = Dummy_ScriptStringXtoCP; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringFree )( SCRIPT_STRING_ANALYSIS* ) = Dummy_ScriptStringFree; -const SCRIPT_LOGATTR* ( WINAPI*CUniBuffer::_ScriptString_pLogAttr )( SCRIPT_STRING_ANALYSIS ) = - Dummy_ScriptString_pLogAttr; -const int* ( WINAPI*CUniBuffer::_ScriptString_pcOutChars )( SCRIPT_STRING_ANALYSIS ) = - Dummy_ScriptString_pcOutChars; -bool CDXUTEditBox::s_bHideCaret; // If true, we don't render the caret. - - - -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTEditBox class -//-------------------------------------------------------------------------------------- +//====================================================================================== + +// Static member initialization +bool CDXUTEditBox::s_bHideCaret; // If true, we don't render the caret. // When scrolling, EDITBOX_SCROLLEXTENT is reciprocal of the amount to scroll. // If EDITBOX_SCROLLEXTENT = 4, then we scroll 1/4 of the control each time. #define EDITBOX_SCROLLEXTENT 4 //-------------------------------------------------------------------------------------- -CDXUTEditBox::CDXUTEditBox( CDXUTDialog* pDialog ) +CDXUTEditBox::CDXUTEditBox( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_nBorder(5), + m_nSpacing(4), + m_rcText{}, + m_rcRender{}, + m_bCaretOn(true), + m_nCaret(0), + m_bInsertMode(true), + m_nSelStart(0), + m_nFirstVisible(0), + m_bMouseDrag(false) { m_Type = DXUT_CONTROL_EDITBOX; m_pDialog = pDialog; - m_nBorder = 5; // Default border width - m_nSpacing = 4; // Default spacing - - m_bCaretOn = true; - m_dfBlink = GetCaretBlinkTime() * 0.001f; + m_dfBlink = double(GetCaretBlinkTime()) * 0.001; m_dfLastBlink = DXUTGetGlobalTimer()->GetAbsoluteTime(); s_bHideCaret = false; - m_nFirstVisible = 0; + m_TextColor = D3DCOLOR_ARGB( 255, 16, 16, 16 ); m_SelTextColor = D3DCOLOR_ARGB( 255, 255, 255, 255 ); m_SelBkColor = D3DCOLOR_ARGB( 255, 40, 50, 92 ); m_CaretColor = D3DCOLOR_ARGB( 255, 0, 0, 0 ); - m_nCaret = m_nSelStart = 0; - m_bInsertMode = true; - - m_bMouseDrag = false; } @@ -6109,7 +5511,7 @@ CDXUTEditBox::~CDXUTEditBox() // PlaceCaret: Set the caret to a character position, and adjust the scrolling if // necessary. //-------------------------------------------------------------------------------------- -void CDXUTEditBox::PlaceCaret( int nCP ) +void CDXUTEditBox::PlaceCaret( _In_ int nCP ) { assert( nCP >= 0 && nCP <= m_Buffer.GetTextSize() ); m_nCaret = nCP; @@ -6118,7 +5520,7 @@ void CDXUTEditBox::PlaceCaret( int nCP ) int nX1st, nX, nX2; m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nX1st ); // 1st visible char m_Buffer.CPtoX( nCP, FALSE, &nX ); // LEAD - // If nCP is the NULL terminator, get the leading edge instead of trailing. + // If nCP is the nul terminator, get the leading edge instead of trailing. if( nCP == m_Buffer.GetTextSize() ) nX2 = nX; else @@ -6166,9 +5568,9 @@ void CDXUTEditBox::ClearText() //-------------------------------------------------------------------------------------- -void CDXUTEditBox::SetText( LPCWSTR wszText, bool bSelected ) +void CDXUTEditBox::SetText( _In_z_ LPCWSTR wszText, _In_ bool bSelected ) { - assert( wszText != NULL ); + assert( wszText ); m_Buffer.SetText( wszText ); m_nFirstVisible = 0; @@ -6179,8 +5581,8 @@ void CDXUTEditBox::SetText( LPCWSTR wszText, bool bSelected ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTEditBox::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ) +_Use_decl_annotations_ +HRESULT CDXUTEditBox::GetTextCopy( LPWSTR strDest, UINT bufferCount ) const { assert( strDest ); @@ -6193,8 +5595,8 @@ HRESULT CDXUTEditBox::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, //-------------------------------------------------------------------------------------- void CDXUTEditBox::DeleteSelectionText() { - int nFirst = __min( m_nCaret, m_nSelStart ); - int nLast = __max( m_nCaret, m_nSelStart ); + int nFirst = std::min( m_nCaret, m_nSelStart ); + int nLast = std::max( m_nCaret, m_nSelStart ); // Update caret and selection PlaceCaret( nFirst ); m_nSelStart = m_nCaret; @@ -6230,23 +5632,27 @@ void CDXUTEditBox::UpdateRects() } +#pragma warning(push) +#pragma warning( disable : 4616 6386 ) void CDXUTEditBox::CopyToClipboard() { // Copy the selection text to the clipboard - if( m_nCaret != m_nSelStart && OpenClipboard( NULL ) ) + if( m_nCaret != m_nSelStart && OpenClipboard( nullptr ) ) { EmptyClipboard(); HGLOBAL hBlock = GlobalAlloc( GMEM_MOVEABLE, sizeof( WCHAR ) * ( m_Buffer.GetTextSize() + 1 ) ); if( hBlock ) { - WCHAR* pwszText = ( WCHAR* )GlobalLock( hBlock ); + auto pwszText = reinterpret_cast( GlobalLock( hBlock ) ); if( pwszText ) { - int nFirst = __min( m_nCaret, m_nSelStart ); - int nLast = __max( m_nCaret, m_nSelStart ); + int nFirst = std::min( m_nCaret, m_nSelStart ); + int nLast = std::max( m_nCaret, m_nSelStart ); if( nLast - nFirst > 0 ) - CopyMemory( pwszText, m_Buffer.GetBuffer() + nFirst, ( nLast - nFirst ) * sizeof( WCHAR ) ); + { + memcpy( pwszText, m_Buffer.GetBuffer() + nFirst, ( nLast - nFirst ) * sizeof( WCHAR ) ); + } pwszText[nLast - nFirst] = L'\0'; // Terminate it GlobalUnlock( hBlock ); } @@ -6264,19 +5670,19 @@ void CDXUTEditBox::PasteFromClipboard() { DeleteSelectionText(); - if( OpenClipboard( NULL ) ) + if( OpenClipboard( nullptr ) ) { HANDLE handle = GetClipboardData( CF_UNICODETEXT ); if( handle ) { // Convert the ANSI string to Unicode, then // insert to our buffer. - WCHAR* pwszText = ( WCHAR* )GlobalLock( handle ); + auto pwszText = reinterpret_cast( GlobalLock( handle ) ); if( pwszText ) { // Copy all characters up to null. if( m_Buffer.InsertString( m_nCaret, pwszText ) ) - PlaceCaret( m_nCaret + lstrlenW( pwszText ) ); + PlaceCaret( m_nCaret + (int)wcslen( pwszText ) ); m_nSelStart = m_nCaret; GlobalUnlock( handle ); } @@ -6284,11 +5690,15 @@ void CDXUTEditBox::PasteFromClipboard() CloseClipboard(); } } +#pragma warning(pop) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTEditBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -6413,8 +5823,12 @@ bool CDXUTEditBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTEditBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -6434,9 +5848,9 @@ bool CDXUTEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Determine the character corresponding to the coordinates. int nCP, nTrail, nX1st; m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nX1st ); // X offset of the 1st visible char - if( SUCCEEDED( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) ) + if( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) { - // Cap at the NULL character. + // Cap at the nul character. if( nTrail && nCP < m_Buffer.GetTextSize() ) PlaceCaret( nCP + 1 ); else @@ -6458,9 +5872,9 @@ bool CDXUTEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Determine the character corresponding to the coordinates. int nCP, nTrail, nX1st; m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nX1st ); // X offset of the 1st visible char - if( SUCCEEDED( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) ) + if( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) { - // Cap at the NULL character. + // Cap at the nul character. if( nTrail && nCP < m_Buffer.GetTextSize() ) PlaceCaret( nCP + 1 ); else @@ -6484,8 +5898,11 @@ void CDXUTEditBox::OnFocusIn() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -6624,15 +6041,14 @@ bool CDXUTEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTEditBox::Render( float fElapsedTime ) +void CDXUTEditBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; - HRESULT hr; int nSelStartX = 0, nCaretX = 0; // Left and right X cordinates of the selection region - CDXUTElement* pElement = GetElement( 0 ); + auto pElement = GetElement( 0 ); if( pElement ) { m_Buffer.SetFontNode( m_pDialog->GetFont( pElement->iFont ) ); @@ -6643,7 +6059,7 @@ void CDXUTEditBox::Render( float fElapsedTime ) // Render the control graphics for( int e = 0; e < 9; ++e ) { - pElement = m_Elements.GetAt( e ); + pElement = m_Elements[ e ]; pElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); m_pDialog->DrawSprite( pElement, &m_rcRender[e], DXUT_FAR_BUTTON_DEPTH ); @@ -6658,9 +6074,9 @@ void CDXUTEditBox::Render( float fElapsedTime ) // // Compute the X coordinates of the selection rectangle // - hr = m_Buffer.CPtoX( m_nCaret, FALSE, &nCaretX ); + m_Buffer.CPtoX( m_nCaret, FALSE, &nCaretX ); if( m_nCaret != m_nSelStart ) - hr = m_Buffer.CPtoX( m_nSelStart, FALSE, &nSelStartX ); + m_Buffer.CPtoX( m_nSelStart, FALSE, &nSelStartX ); else nSelStartX = nCaretX; @@ -6681,29 +6097,23 @@ void CDXUTEditBox::Render( float fElapsedTime ) OffsetRect( &rcSelection, m_rcText.left - nXFirst, 0 ); IntersectRect( &rcSelection, &m_rcText, &rcSelection ); - IDirect3DDevice9* pd3dDevice = m_pDialog->GetManager()->GetD3D9Device(); - if( pd3dDevice ) - pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); m_pDialog->DrawRect( &rcSelection, m_SelBkColor ); - if( pd3dDevice ) - pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); } // // Render the text // // Element 0 for text - m_Elements.GetAt( 0 )->FontColor.Current = m_TextColor; - m_pDialog->DrawText( m_Buffer.GetBuffer() + m_nFirstVisible, m_Elements.GetAt( 0 ), &m_rcText ); + m_Elements[ 0 ]->FontColor.SetCurrent( m_TextColor ); + m_pDialog->DrawText( m_Buffer.GetBuffer() + m_nFirstVisible, m_Elements[ 0 ], &m_rcText ); // Render the selected text if( m_nCaret != m_nSelStart ) { - int nFirstToRender = __max( m_nFirstVisible, __min( m_nSelStart, m_nCaret ) ); - int nNumChatToRender = __max( m_nSelStart, m_nCaret ) - nFirstToRender; - m_Elements.GetAt( 0 )->FontColor.Current = m_SelTextColor; + int nFirstToRender = std::max( m_nFirstVisible, std::min( m_nSelStart, m_nCaret ) ); + m_Elements[ 0 ]->FontColor.SetCurrent( m_SelTextColor ); m_pDialog->DrawText( m_Buffer.GetBuffer() + nFirstToRender, - m_Elements.GetAt( 0 ), &rcSelection, false, nNumChatToRender ); + m_Elements[ 0 ], &rcSelection, false ); } // @@ -6745,6 +6155,7 @@ void CDXUTEditBox::Render( float fElapsedTime ) #define IN_FLOAT_CHARSET( c ) \ ( (c) == L'-' || (c) == L'.' || ( (c) >= L'0' && (c) <= L'9' ) ) +_Use_decl_annotations_ void CDXUTEditBox::ParseFloatArray( float* pNumbers, int nCount ) { int nWritten = 0; // Number of floats written @@ -6767,9 +6178,9 @@ void CDXUTEditBox::ParseFloatArray( float* pNumbers, int nCount ) ++pEnd; // Copy the token to our buffer - int nTokenLen = __min( sizeof( wszToken ) / sizeof( wszToken[0] ) - 1, int( pEnd - pToken ) ); + int nTokenLen = std::min( sizeof( wszToken ) / sizeof( wszToken[0] ) - 1, int( pEnd - pToken ) ); wcscpy_s( wszToken, nTokenLen, pToken ); - *pNumbers = ( float )wcstod( wszToken, NULL ); + *pNumbers = ( float )wcstod( wszToken, nullptr ); ++nWritten; ++pNumbers; pToken = pEnd; @@ -6777,6 +6188,8 @@ void CDXUTEditBox::ParseFloatArray( float* pNumbers, int nCount ) } +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTEditBox::SetTextFloatArray( const float* pNumbers, int nCount ) { WCHAR wszBuffer[512] = @@ -6785,7 +6198,7 @@ void CDXUTEditBox::SetTextFloatArray( const float* pNumbers, int nCount ) }; WCHAR wszTmp[64]; - if( pNumbers == NULL ) + if( !pNumbers ) return; for( int i = 0; i < nCount; ++i ) @@ -6802,54 +6215,24 @@ void CDXUTEditBox::SetTextFloatArray( const float* pNumbers, int nCount ) } - - //-------------------------------------------------------------------------------------- -void CUniBuffer::Initialize() +void CDXUTEditBox::ResetCaretBlink() { - if( s_hDll ) // Only need to do once - return; - - s_hDll = LoadLibrary( UNISCRIBE_DLLNAME ); - if( s_hDll ) - { - FARPROC Temp; - GETPROCADDRESS( s_hDll, ScriptApplyDigitSubstitution, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringAnalyse, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringCPtoX, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringXtoCP, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringFree, Temp ); - GETPROCADDRESS( s_hDll, ScriptString_pLogAttr, Temp ); - GETPROCADDRESS( s_hDll, ScriptString_pcOutChars, Temp ); - } + m_bCaretOn = true; + m_dfLastBlink = DXUTGetGlobalTimer()->GetAbsoluteTime(); } -//-------------------------------------------------------------------------------------- -void CUniBuffer::Uninitialize() -{ - if( s_hDll ) - { - PLACEHOLDERPROC( ScriptApplyDigitSubstitution ); - PLACEHOLDERPROC( ScriptStringAnalyse ); - PLACEHOLDERPROC( ScriptStringCPtoX ); - PLACEHOLDERPROC( ScriptStringXtoCP ); - PLACEHOLDERPROC( ScriptStringFree ); - PLACEHOLDERPROC( ScriptString_pLogAttr ); - PLACEHOLDERPROC( ScriptString_pcOutChars ); - - FreeLibrary( s_hDll ); - s_hDll = NULL; - } -} - +//====================================================================================== +// CUniBuffer +//====================================================================================== //-------------------------------------------------------------------------------------- -bool CUniBuffer::SetBufferSize( int nNewSize ) +bool CUniBuffer::SetBufferSize( _In_ int nNewSize ) { // If the current size is already the maximum allowed, // we can't possibly allocate more. - if( m_nBufferSize == DXUT_MAX_EDITBOXLENGTH ) + if( m_nBufferSize >= DXUT_MAX_EDITBOXLENGTH ) return false; int nAllocateSize = ( nNewSize == -1 || nNewSize < m_nBufferSize * 2 ) ? ( m_nBufferSize ? m_nBufferSize * @@ -6859,7 +6242,7 @@ bool CUniBuffer::SetBufferSize( int nNewSize ) if( nAllocateSize > DXUT_MAX_EDITBOXLENGTH ) nAllocateSize = DXUT_MAX_EDITBOXLENGTH; - WCHAR* pTempBuffer = new WCHAR[nAllocateSize]; + auto pTempBuffer = new (std::nothrow) WCHAR[nAllocateSize]; if( !pTempBuffer ) return false; @@ -6867,7 +6250,7 @@ bool CUniBuffer::SetBufferSize( int nNewSize ) if( m_pwszBuffer ) { - CopyMemory( pTempBuffer, m_pwszBuffer, m_nBufferSize * sizeof( WCHAR ) ); + memcpy( pTempBuffer, m_pwszBuffer, m_nBufferSize * sizeof( WCHAR ) ); delete[] m_pwszBuffer; } @@ -6883,32 +6266,35 @@ bool CUniBuffer::SetBufferSize( int nNewSize ) HRESULT CUniBuffer::Analyse() { if( m_Analysis ) - _ScriptStringFree( &m_Analysis ); + (void)ScriptStringFree( &m_Analysis ); + + SCRIPT_CONTROL ScriptControl = {}; // For uniscribe + SCRIPT_STATE ScriptState = {}; // For uniscribe - SCRIPT_CONTROL ScriptControl; // For uniscribe - SCRIPT_STATE ScriptState; // For uniscribe - ZeroMemory( &ScriptControl, sizeof( ScriptControl ) ); - ZeroMemory( &ScriptState, sizeof( ScriptState ) ); - _ScriptApplyDigitSubstitution( NULL, &ScriptControl, &ScriptState ); +#pragma warning(push) +#pragma warning(disable : 4616 6309 6387 ) + HRESULT hr = ScriptApplyDigitSubstitution( nullptr, &ScriptControl, &ScriptState ); + if ( FAILED(hr) ) + return hr; +#pragma warning(pop) if( !m_pFontNode ) return E_FAIL; - HDC hDC = - ( m_pFontNode->pFont9 ? m_pFontNode->pFont9->GetDC() : NULL ); - HRESULT hr = _ScriptStringAnalyse( hDC, - m_pwszBuffer, - lstrlenW( m_pwszBuffer ) + 1, // NULL is also analyzed. - lstrlenW( m_pwszBuffer ) * 3 / 2 + 16, - -1, - SSA_BREAK | SSA_GLYPHS | SSA_FALLBACK | SSA_LINK, - 0, - &ScriptControl, - &ScriptState, - NULL, - NULL, - NULL, - &m_Analysis ); + HDC hDC = nullptr; + hr = ScriptStringAnalyse( hDC, + m_pwszBuffer, + (int)wcslen( m_pwszBuffer ) + 1, // nul is also analyzed. + (int)wcslen( m_pwszBuffer ) * 3 / 2 + 16, + -1, + SSA_BREAK | SSA_GLYPHS | SSA_FALLBACK | SSA_LINK, + 0, + &ScriptControl, + &ScriptState, + nullptr, + nullptr, + nullptr, + &m_Analysis ); if( SUCCEEDED( hr ) ) m_bAnalyseRequired = false; // Analysis is up-to-date return hr; @@ -6916,15 +6302,13 @@ HRESULT CUniBuffer::Analyse() //-------------------------------------------------------------------------------------- -CUniBuffer::CUniBuffer( int nInitialSize ) +CUniBuffer::CUniBuffer( _In_ int nInitialSize ) noexcept { - CUniBuffer::Initialize(); // ensure static vars are properly init'ed first - m_nBufferSize = 0; - m_pwszBuffer = NULL; + m_pwszBuffer = nullptr; m_bAnalyseRequired = true; - m_Analysis = NULL; - m_pFontNode = NULL; + m_Analysis = nullptr; + m_pFontNode = nullptr; if( nInitialSize > 0 ) SetBufferSize( nInitialSize ); @@ -6936,12 +6320,12 @@ CUniBuffer::~CUniBuffer() { delete[] m_pwszBuffer; if( m_Analysis ) - _ScriptStringFree( &m_Analysis ); + (void)ScriptStringFree( &m_Analysis ); } //-------------------------------------------------------------------------------------- -WCHAR& CUniBuffer::operator[]( int n ) // No param checking +WCHAR& CUniBuffer::operator[]( _In_ int n ) // No param checking { // This version of operator[] is called only // if we are asking for write access, so @@ -6963,18 +6347,18 @@ void CUniBuffer::Clear() // Inserts the char at specified index. // If nIndex == -1, insert to the end. //-------------------------------------------------------------------------------------- -bool CUniBuffer::InsertChar( int nIndex, WCHAR wChar ) +bool CUniBuffer::InsertChar( _In_ int nIndex, _In_ WCHAR wChar ) { assert( nIndex >= 0 ); - if( nIndex < 0 || nIndex > lstrlenW( m_pwszBuffer ) ) + if( nIndex < 0 || nIndex > (int)wcslen( m_pwszBuffer ) ) return false; // invalid index // Check for maximum length allowed if( GetTextSize() + 1 >= DXUT_MAX_EDITBOXLENGTH ) return false; - if( lstrlenW( m_pwszBuffer ) + 1 >= m_nBufferSize ) + if( (int)wcslen( m_pwszBuffer ) + 1 >= m_nBufferSize ) { if( !SetBufferSize( -1 ) ) return false; // out of memory @@ -6983,7 +6367,7 @@ bool CUniBuffer::InsertChar( int nIndex, WCHAR wChar ) assert( m_nBufferSize >= 2 ); // Shift the characters after the index, start by copying the null terminator - WCHAR* dest = m_pwszBuffer + lstrlenW( m_pwszBuffer ) + 1; + WCHAR* dest = m_pwszBuffer + wcslen( m_pwszBuffer ) + 1; WCHAR* stop = m_pwszBuffer + nIndex; WCHAR* src = dest - 1; @@ -7004,13 +6388,13 @@ bool CUniBuffer::InsertChar( int nIndex, WCHAR wChar ) // Removes the char at specified index. // If nIndex == -1, remove the last char. //-------------------------------------------------------------------------------------- -bool CUniBuffer::RemoveChar( int nIndex ) +bool CUniBuffer::RemoveChar( _In_ int nIndex ) { - if( !lstrlenW( m_pwszBuffer ) || nIndex < 0 || nIndex >= lstrlenW( m_pwszBuffer ) ) + if( !wcslen( m_pwszBuffer ) || nIndex < 0 || nIndex >= (int)wcslen( m_pwszBuffer ) ) return false; // Invalid index MoveMemory( m_pwszBuffer + nIndex, m_pwszBuffer + nIndex + 1, sizeof( WCHAR ) * - ( lstrlenW( m_pwszBuffer ) - nIndex ) ); + ( wcslen( m_pwszBuffer ) - nIndex ) ); m_bAnalyseRequired = true; return true; } @@ -7021,31 +6405,32 @@ bool CUniBuffer::RemoveChar( int nIndex ) // If nCount == -1, the entire string is inserted. // If nIndex == -1, insert to the end. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CUniBuffer::InsertString( int nIndex, const WCHAR* pStr, int nCount ) { assert( nIndex >= 0 ); if( nIndex < 0 ) return false; - if( nIndex > lstrlenW( m_pwszBuffer ) ) + if( nIndex > (int)wcslen( m_pwszBuffer ) ) return false; // invalid index if( -1 == nCount ) - nCount = lstrlenW( pStr ); + nCount = (int)wcslen( pStr ); // Check for maximum length allowed if( GetTextSize() + nCount >= DXUT_MAX_EDITBOXLENGTH ) return false; - if( lstrlenW( m_pwszBuffer ) + nCount >= m_nBufferSize ) + if( (int)wcslen( m_pwszBuffer ) + nCount >= m_nBufferSize ) { - if( !SetBufferSize( lstrlenW( m_pwszBuffer ) + nCount + 1 ) ) + if( !SetBufferSize( (int)wcslen( m_pwszBuffer ) + nCount + 1 ) ) return false; // out of memory } MoveMemory( m_pwszBuffer + nIndex + nCount, m_pwszBuffer + nIndex, sizeof( WCHAR ) * - ( lstrlenW( m_pwszBuffer ) - nIndex + 1 ) ); - CopyMemory( m_pwszBuffer + nIndex, pStr, nCount * sizeof( WCHAR ) ); + ( wcslen( m_pwszBuffer ) - nIndex + 1 ) ); + memcpy( m_pwszBuffer + nIndex, pStr, nCount * sizeof( WCHAR ) ); m_bAnalyseRequired = true; return true; @@ -7053,11 +6438,11 @@ bool CUniBuffer::InsertString( int nIndex, const WCHAR* pStr, int nCount ) //-------------------------------------------------------------------------------------- -bool CUniBuffer::SetText( LPCWSTR wszText ) +bool CUniBuffer::SetText( _In_z_ LPCWSTR wszText ) { - assert( wszText != NULL ); + assert( wszText ); - int nRequired = int( wcslen( wszText ) + 1 ); + size_t nRequired = wcslen( wszText ) + 1; // Check for maximum length allowed if( nRequired >= DXUT_MAX_EDITBOXLENGTH ) @@ -7079,7 +6464,8 @@ bool CUniBuffer::SetText( LPCWSTR wszText ) //-------------------------------------------------------------------------------------- -HRESULT CUniBuffer::CPtoX( int nCP, BOOL bTrail, int* pX ) +_Use_decl_annotations_ +bool CUniBuffer::CPtoX( int nCP, bool bTrail, int* pX ) { assert( pX ); *pX = 0; // Default @@ -7089,14 +6475,21 @@ HRESULT CUniBuffer::CPtoX( int nCP, BOOL bTrail, int* pX ) hr = Analyse(); if( SUCCEEDED( hr ) ) - hr = _ScriptStringCPtoX( m_Analysis, nCP, bTrail, pX ); + hr = ScriptStringCPtoX( m_Analysis, nCP, bTrail, pX ); - return hr; + if ( FAILED(hr) ) + { + *pX = 0; + return false; + } + + return true; } //-------------------------------------------------------------------------------------- -HRESULT CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) +_Use_decl_annotations_ +bool CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) { assert( pCP && pnTrail ); *pCP = 0; *pnTrail = FALSE; // Default @@ -7105,8 +6498,15 @@ HRESULT CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) if( m_bAnalyseRequired ) hr = Analyse(); - if( SUCCEEDED( hr ) ) - hr = _ScriptStringXtoCP( m_Analysis, nX, pCP, pnTrail ); + if (SUCCEEDED(hr)) + { + hr = ScriptStringXtoCP( m_Analysis, nX, pCP, pnTrail ); + if (FAILED(hr)) + { + *pCP = 0; *pnTrail = FALSE; + return false; + } + } // If the coordinate falls outside the text region, we // can get character positions that don't exist. We must @@ -7115,16 +6515,22 @@ HRESULT CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) { *pCP = 0; *pnTrail = FALSE; } - else if( *pCP > lstrlenW( m_pwszBuffer ) && *pnTrail == FALSE ) + else if( *pCP > (int)wcslen( m_pwszBuffer ) && *pnTrail == FALSE ) { - *pCP = lstrlenW( m_pwszBuffer ); *pnTrail = TRUE; + *pCP = (int)wcslen( m_pwszBuffer ); *pnTrail = TRUE; } - return hr; + if (FAILED(hr)) + { + *pCP = 0; *pnTrail = FALSE; + return false; + } + return true; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CUniBuffer::GetPriorItemPos( int nCP, int* pPrior ) { *pPrior = nCP; // Default is the char itself @@ -7133,13 +6539,13 @@ void CUniBuffer::GetPriorItemPos( int nCP, int* pPrior ) if( FAILED( Analyse() ) ) return; - const SCRIPT_LOGATTR* pLogAttr = _ScriptString_pLogAttr( m_Analysis ); + const SCRIPT_LOGATTR* pLogAttr = ScriptString_pLogAttr( m_Analysis ); if( !pLogAttr ) return; - if( !_ScriptString_pcOutChars( m_Analysis ) ) + if( !ScriptString_pcOutChars( m_Analysis ) ) return; - int nInitial = *_ScriptString_pcOutChars( m_Analysis ); + int nInitial = *ScriptString_pcOutChars( m_Analysis ); if( nCP - 1 < nInitial ) nInitial = nCP - 1; for( int i = nInitial; i > 0; --i ) @@ -7156,6 +6562,7 @@ void CUniBuffer::GetPriorItemPos( int nCP, int* pPrior ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CUniBuffer::GetNextItemPos( int nCP, int* pPrior ) { *pPrior = nCP; // Default is the char itself @@ -7166,18 +6573,18 @@ void CUniBuffer::GetNextItemPos( int nCP, int* pPrior ) if( FAILED( hr ) ) return; - const SCRIPT_LOGATTR* pLogAttr = _ScriptString_pLogAttr( m_Analysis ); + const SCRIPT_LOGATTR* pLogAttr = ScriptString_pLogAttr( m_Analysis ); if( !pLogAttr ) return; - if( !_ScriptString_pcOutChars( m_Analysis ) ) + if( !ScriptString_pcOutChars( m_Analysis ) ) return; - int nInitial = *_ScriptString_pcOutChars( m_Analysis ); + int nInitial = *ScriptString_pcOutChars( m_Analysis ); if( nCP + 1 < nInitial ) nInitial = nCP + 1; int i = nInitial; - int limit = *_ScriptString_pcOutChars( m_Analysis ); + int limit = *ScriptString_pcOutChars( m_Analysis ); while( limit > 0 && i < limit - 1 ) { if( pLogAttr[i].fWordStop ) // Either the fWordStop flag is set @@ -7193,23 +6600,20 @@ void CUniBuffer::GetNextItemPos( int nCP, int* pPrior ) } ++i; - limit = *_ScriptString_pcOutChars( m_Analysis ); + limit = *ScriptString_pcOutChars( m_Analysis ); } // We have reached the end. It's always a word stop, so simply return it. - *pPrior = *_ScriptString_pcOutChars( m_Analysis ) - 1; + *pPrior = *ScriptString_pcOutChars( m_Analysis ) - 1; } -//-------------------------------------------------------------------------------------- -void CDXUTEditBox::ResetCaretBlink() -{ - m_bCaretOn = true; - m_dfLastBlink = DXUTGetGlobalTimer()->GetAbsoluteTime(); -} - +//====================================================================================== +// DXUTBlendColor +//====================================================================================== //-------------------------------------------------------------------------------------- -void DXUTBlendColor::Init( D3DCOLOR defaultColor, D3DCOLOR disabledColor, D3DCOLOR hiddenColor ) +_Use_decl_annotations_ +void DXUTBlendColor::Init( DWORD defaultColor, DWORD disabledColor, DWORD hiddenColor ) { for( int i = 0; i < MAX_CONTROL_STATES; i++ ) { @@ -7218,23 +6622,38 @@ void DXUTBlendColor::Init( D3DCOLOR defaultColor, D3DCOLOR disabledColor, D3DCOL States[ DXUT_STATE_DISABLED ] = disabledColor; States[ DXUT_STATE_HIDDEN ] = hiddenColor; - Current = hiddenColor; + SetCurrent( hiddenColor ); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void DXUTBlendColor::Blend( UINT iState, float fElapsedTime, float fRate ) { - D3DXCOLOR destColor = States[ iState ]; - D3DXColorLerp( &Current, &Current, &destColor, 1.0f - powf( fRate, 30 * fElapsedTime ) ); + DirectX::XMFLOAT4 destColor = D3DCOLOR_TO_D3DCOLORVALUE( States[ iState ] ); + XMVECTOR clr1 = XMLoadFloat4( &destColor ); + XMVECTOR clr = XMLoadFloat4( &Current ); + clr = XMVectorLerp( clr, clr1, 1.0f - powf( fRate, 30 * fElapsedTime ) ); + XMStoreFloat4( &Current, clr ); +} + + +//-------------------------------------------------------------------------------------- +void DXUTBlendColor::SetCurrent( DWORD color ) +{ + Current = D3DCOLOR_TO_D3DCOLORVALUE( color ); } +//====================================================================================== +// CDXUTElement +//====================================================================================== //-------------------------------------------------------------------------------------- -void CDXUTElement::SetTexture( UINT iTexture, RECT* prcTexture, D3DCOLOR defaultTextureColor ) +_Use_decl_annotations_ +void CDXUTElement::SetTexture( UINT texture, RECT* prcTexture, DWORD defaultTextureColor ) { - this->iTexture = iTexture; + iTexture = texture; if( prcTexture ) rcTexture = *prcTexture; @@ -7246,10 +6665,11 @@ void CDXUTElement::SetTexture( UINT iTexture, RECT* prcTexture, D3DCOLOR default //-------------------------------------------------------------------------------------- -void CDXUTElement::SetFont( UINT iFont, D3DCOLOR defaultFontColor, DWORD dwTextFormat ) +_Use_decl_annotations_ +void CDXUTElement::SetFont( UINT font, DWORD defaultFontColor, DWORD textFormat ) { - this->iFont = iFont; - this->dwTextFormat = dwTextFormat; + iFont = font; + dwTextFormat = textFormat; FontColor.Init( defaultFontColor ); } @@ -7258,8 +6678,6 @@ void CDXUTElement::SetFont( UINT iFont, D3DCOLOR defaultFontColor, DWORD dwTextF //-------------------------------------------------------------------------------------- void CDXUTElement::Refresh() { - TextureColor.Current = TextureColor.States[ DXUT_STATE_HIDDEN ]; - FontColor.Current = FontColor.States[ DXUT_STATE_HIDDEN ]; + TextureColor.SetCurrent( TextureColor.States[ DXUT_STATE_HIDDEN ] ); + FontColor.SetCurrent( FontColor.States[ DXUT_STATE_HIDDEN ] ); } - - diff --git a/FriedLiver/Source/DXUT/Optional/DXUTgui.h b/FriedLiver/Source/DXUT/Optional/DXUTgui.h index 765020b7..1ce4d530 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTgui.h +++ b/FriedLiver/Source/DXUT/Optional/DXUTgui.h @@ -2,14 +2,18 @@ // File: DXUTgui.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_GUI_H -#define DXUT_GUI_H #include #include +#ifdef DXUT_AUTOLIB +#pragma comment( lib, "usp10.lib" ) +#endif //-------------------------------------------------------------------------------------- // Defines and macros @@ -50,8 +54,8 @@ class CDXUTElement; struct DXUTElementHolder; struct DXUTTextureNode; struct DXUTFontNode; -typedef VOID ( CALLBACK*PCALLBACKDXUTGUIEVENT )( UINT nEvent, int nControlID, CDXUTControl* pControl, - void* pUserContext ); +typedef void ( CALLBACK*PCALLBACKDXUTGUIEVENT )( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl, + _In_opt_ void* pUserContext ); //-------------------------------------------------------------------------------------- @@ -85,12 +89,13 @@ enum DXUT_CONTROL_STATE struct DXUTBlendColor { - void Init( D3DCOLOR defaultColor, D3DCOLOR disabledColor = D3DCOLOR_ARGB( 200, 128, 128, 128 ), - D3DCOLOR hiddenColor = 0 ); - void Blend( UINT iState, float fElapsedTime, float fRate = 0.7f ); + void Init( _In_ DWORD defaultColor, _In_ DWORD disabledColor = D3DCOLOR_ARGB( 200, 128, 128, 128 ), _In_ DWORD hiddenColor = 0 ); + void Blend( _In_ UINT iState, _In_ float fElapsedTime, _In_ float fRate = 0.7f ); + + DWORD States[ MAX_CONTROL_STATES ]; // Modulate colors for all possible control states + DirectX::XMFLOAT4 Current; - D3DCOLOR States[ MAX_CONTROL_STATES ]; // Modulate colors for all possible control states - D3DXCOLOR Current; + void SetCurrent( DWORD color ); }; @@ -100,13 +105,10 @@ struct DXUTBlendColor class CDXUTElement { public: - void SetTexture( UINT iTexture, RECT* prcTexture, D3DCOLOR defaultTextureColor = D3DCOLOR_ARGB( 255, 255, 255, - 255 ) ); - void SetFont( UINT iFont, D3DCOLOR defaultFontColor = D3DCOLOR_ARGB( 255, 255, 255, - 255 ), DWORD dwTextFormat = DT_CENTER | - DT_VCENTER ); + void SetTexture( _In_ UINT texture, _In_ RECT* prcTexture, _In_ DWORD defaultTextureColor = D3DCOLOR_ARGB( 255, 255, 255, 255 ) ); + void SetFont( _In_ UINT font, _In_ DWORD defaultFontColor = D3DCOLOR_ARGB( 255, 255, 255, 255 ), DWORD textFormat = DT_CENTER | DT_VCENTER ); - void Refresh(); + void Refresh(); UINT iTexture; // Index of the texture for this Element UINT iFont; // Index of the font for this Element @@ -128,219 +130,162 @@ class CDXUTDialog friend class CDXUTDialogResourceManager; public: - CDXUTDialog(); - ~CDXUTDialog(); + CDXUTDialog() noexcept; + ~CDXUTDialog(); // Need to call this now - void Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog = true ); - void Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, - LPCWSTR pszControlTextureFilename ); - void Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, - LPCWSTR szControlTextureResourceName, HMODULE hControlTextureResourceModule ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog = true ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog, + _In_z_ LPCWSTR pszControlTextureFilename ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog, + _In_z_ LPCWSTR szControlTextureResourceName, _In_ HMODULE hControlTextureResourceModule ); // Windows message handler - bool MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); + bool MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); // Control creation - HRESULT AddStatic( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault=false, - CDXUTStatic** ppCreated=NULL ); - HRESULT AddButton( int ID, LPCWSTR strText, int x, int y, int width, int height, UINT nHotkey=0, - bool bIsDefault=false, CDXUTButton** ppCreated=NULL ); - HRESULT AddCheckBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bChecked=false, - UINT nHotkey=0, bool bIsDefault=false, CDXUTCheckBox** ppCreated=NULL ); - HRESULT AddRadioButton( int ID, UINT nButtonGroup, LPCWSTR strText, int x, int y, int width, - int height, bool bChecked=false, UINT nHotkey=0, bool bIsDefault=false, - CDXUTRadioButton** ppCreated=NULL ); - HRESULT AddComboBox( int ID, int x, int y, int width, int height, UINT nHotKey=0, bool bIsDefault= - false, CDXUTComboBox** ppCreated=NULL ); - HRESULT AddSlider( int ID, int x, int y, int width, int height, int min=0, int max=100, int value=50, - bool bIsDefault=false, CDXUTSlider** ppCreated=NULL ); + HRESULT AddStatic( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTStatic** ppCreated = nullptr ); + HRESULT AddButton( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ UINT nHotkey=0, + _In_ bool bIsDefault=false, _Out_opt_ CDXUTButton** ppCreated = nullptr ); + HRESULT AddCheckBox( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bChecked=false, + _In_ UINT nHotkey=0, _In_ bool bIsDefault=false, _Out_opt_ CDXUTCheckBox** ppCreated = nullptr ); + HRESULT AddRadioButton( _In_ int ID, _In_ UINT nButtonGroup, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, + _In_ int height, _In_ bool bChecked=false, _In_ UINT nHotkey=0, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTRadioButton** ppCreated = nullptr ); + HRESULT AddComboBox( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ UINT nHotKey=0, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTComboBox** ppCreated = nullptr ); + HRESULT AddSlider( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ int min=0, _In_ int max=100, _In_ int value=50, + _In_ bool bIsDefault=false, _Out_opt_ CDXUTSlider** ppCreated = nullptr ); // AddIMEEditBox has been renamed into DXUTguiIME.cpp as CDXUTIMEEditBox::CreateIMEEditBox - HRESULT AddEditBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault= - false, CDXUTEditBox** ppCreated=NULL ); - HRESULT AddListBox( int ID, int x, int y, int width, int height, DWORD dwStyle=0, - CDXUTListBox** ppCreated=NULL ); - HRESULT AddControl( CDXUTControl* pControl ); - HRESULT InitControl( CDXUTControl* pControl ); + HRESULT AddEditBox( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTEditBox** ppCreated = nullptr ); + HRESULT AddListBox( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ DWORD dwStyle=0, + _Out_opt_ CDXUTListBox** ppCreated = nullptr ); + HRESULT AddControl( _In_ CDXUTControl* pControl ); + HRESULT InitControl( _In_ CDXUTControl* pControl ); // Control retrieval - CDXUTStatic* GetStatic( int ID ) + CDXUTStatic* GetStatic( _In_ int ID ) const { - return ( CDXUTStatic* )GetControl( ID, DXUT_CONTROL_STATIC ); + return reinterpret_cast( GetControl( ID, DXUT_CONTROL_STATIC ) ); } - CDXUTButton* GetButton( int ID ) + CDXUTButton* GetButton( _In_ int ID ) const { - return ( CDXUTButton* )GetControl( ID, DXUT_CONTROL_BUTTON ); + return reinterpret_cast( GetControl(ID, DXUT_CONTROL_BUTTON) ); } - CDXUTCheckBox* GetCheckBox( int ID ) + CDXUTCheckBox* GetCheckBox( _In_ int ID ) const { - return ( CDXUTCheckBox* )GetControl( ID, DXUT_CONTROL_CHECKBOX ); + return reinterpret_cast( GetControl(ID, DXUT_CONTROL_CHECKBOX) ); } - CDXUTRadioButton* GetRadioButton( int ID ) + CDXUTRadioButton* GetRadioButton( _In_ int ID ) const { - return ( CDXUTRadioButton* )GetControl( ID, DXUT_CONTROL_RADIOBUTTON ); + return reinterpret_cast( GetControl(ID, DXUT_CONTROL_RADIOBUTTON) ); } - CDXUTComboBox* GetComboBox( int ID ) + CDXUTComboBox* GetComboBox( _In_ int ID ) const { - return ( CDXUTComboBox* )GetControl( ID, DXUT_CONTROL_COMBOBOX ); + return reinterpret_cast( GetControl(ID, DXUT_CONTROL_COMBOBOX) ); } - CDXUTSlider* GetSlider( int ID ) + CDXUTSlider* GetSlider( _In_ int ID ) const { - return ( CDXUTSlider* )GetControl( ID, DXUT_CONTROL_SLIDER ); + return reinterpret_cast( GetControl(ID, DXUT_CONTROL_SLIDER) ); } - CDXUTEditBox* GetEditBox( int ID ) + CDXUTEditBox* GetEditBox( _In_ int ID ) const { - return ( CDXUTEditBox* )GetControl( ID, DXUT_CONTROL_EDITBOX ); + return reinterpret_cast( GetControl(ID, DXUT_CONTROL_EDITBOX) ); } - CDXUTListBox* GetListBox( int ID ) + CDXUTListBox* GetListBox( _In_ int ID ) const { - return ( CDXUTListBox* )GetControl( ID, DXUT_CONTROL_LISTBOX ); + return reinterpret_cast( GetControl(ID, DXUT_CONTROL_LISTBOX) ); } - CDXUTControl* GetControl( int ID ); - CDXUTControl* GetControl( int ID, UINT nControlType ); - CDXUTControl* GetControlAtPoint( POINT pt ); + CDXUTControl* GetControl( _In_ int ID ) const; + CDXUTControl* GetControl( _In_ int ID, _In_ UINT nControlType ) const; + CDXUTControl* GetControlAtPoint( _In_ const POINT& pt ) const; - bool GetControlEnabled( int ID ); - void SetControlEnabled( int ID, bool bEnabled ); + bool GetControlEnabled( _In_ int ID ) const; + void SetControlEnabled( _In_ int ID, _In_ bool bEnabled ); - void ClearRadioButtonGroup( UINT nGroup ); - void ClearComboBox( int ID ); + void ClearRadioButtonGroup( _In_ UINT nGroup ); + void ClearComboBox( _In_ int ID ); // Access the default display Elements used when adding new controls - HRESULT SetDefaultElement( UINT nControlType, UINT iElement, CDXUTElement* pElement ); - CDXUTElement* GetDefaultElement( UINT nControlType, UINT iElement ); + HRESULT SetDefaultElement( _In_ UINT nControlType, _In_ UINT iElement, _In_ CDXUTElement* pElement ); + CDXUTElement* GetDefaultElement( _In_ UINT nControlType, _In_ UINT iElement ) const; // Methods called by controls - void SendEvent( UINT nEvent, bool bTriggeredByUser, CDXUTControl* pControl ); - void RequestFocus( CDXUTControl* pControl ); + void SendEvent( _In_ UINT nEvent, _In_ bool bTriggeredByUser, _In_ CDXUTControl* pControl ); + void RequestFocus( _In_ CDXUTControl* pControl ); // Render helpers - HRESULT DrawRect( RECT* pRect, D3DCOLOR color ); - HRESULT DrawRect9( RECT* pRect, D3DCOLOR color ); - HRESULT DrawPolyLine( POINT* apPoints, UINT nNumPoints, D3DCOLOR color ); - HRESULT DrawSprite( CDXUTElement* pElement, RECT* prcDest, float fDepth ); - HRESULT DrawSprite9( CDXUTElement* pElement, RECT* prcDest ); - HRESULT DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float fDepth ); - HRESULT CalcTextRect( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, int nCount = -1 ); - HRESULT DrawText( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow = false, - int nCount = -1, bool bCenter = false ); - HRESULT DrawText9( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow = false, - int nCount = -1 ); - HRESULT DrawText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow = false, - int nCount = -1, bool bCenter = false ); + HRESULT DrawRect( _In_ const RECT* pRect, _In_ DWORD color ); + HRESULT DrawSprite( _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ float fDepth ); + HRESULT DrawSprite11( _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ float fDepth ); + HRESULT CalcTextRect( _In_z_ LPCWSTR strText, _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ int nCount = -1 ); + HRESULT DrawText( _In_z_ LPCWSTR strText, _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ bool bShadow = false, + _In_ bool bCenter = false ); // Attributes - bool GetVisible() - { - return m_bVisible; - } - void SetVisible( bool bVisible ) - { - m_bVisible = bVisible; - } - bool GetMinimized() - { - return m_bMinimized; - } - void SetMinimized( bool bMinimized ) - { - m_bMinimized = bMinimized; - } - void SetBackgroundColors( D3DCOLOR colorAllCorners ) - { - SetBackgroundColors( colorAllCorners, colorAllCorners, colorAllCorners, colorAllCorners ); - } - void SetBackgroundColors( D3DCOLOR colorTopLeft, D3DCOLOR colorTopRight, D3DCOLOR colorBottomLeft, - D3DCOLOR colorBottomRight ); - void EnableCaption( bool bEnable ) - { - m_bCaption = bEnable; - } - int GetCaptionHeight() const - { - return m_nCaptionHeight; - } - void SetCaptionHeight( int nHeight ) - { - m_nCaptionHeight = nHeight; - } - void SetCaptionText( const WCHAR* pwszText ) - { - wcscpy_s( m_wszCaption, sizeof( m_wszCaption ) / sizeof( m_wszCaption[0] ), pwszText ); - } - void GetLocation( POINT& Pt ) const - { - Pt.x = m_x; Pt.y = m_y; - } - void SetLocation( int x, int y ) - { - m_x = x; m_y = y; - } - void SetSize( int width, int height ) + bool GetVisible() const { return m_bVisible; } + void SetVisible( _In_ bool bVisible ) { m_bVisible = bVisible; } + bool GetMinimized() const { return m_bMinimized; } + void SetMinimized( _In_ bool bMinimized ) {m_bMinimized = bMinimized; } + void SetBackgroundColors( _In_ DWORD colorAllCorners ) { SetBackgroundColors( colorAllCorners, colorAllCorners, colorAllCorners, colorAllCorners ); } + void SetBackgroundColors( _In_ DWORD colorTopLeft, _In_ DWORD colorTopRight, _In_ DWORD colorBottomLeft, _In_ DWORD colorBottomRight ); + void EnableCaption( _In_ bool bEnable ) { m_bCaption = bEnable; } + int GetCaptionHeight() const { return m_nCaptionHeight; } + void SetCaptionHeight( _In_ int nHeight ) { m_nCaptionHeight = nHeight; } + void SetCaptionText( _In_ const WCHAR* pwszText ) { wcscpy_s( m_wszCaption, sizeof( m_wszCaption ) / sizeof( m_wszCaption[0] ), pwszText ); } + void GetLocation( _Out_ POINT& Pt ) const { - m_width = width; m_height = height; + Pt.x = m_x; + Pt.y = m_y; } - int GetWidth() + void SetLocation( _In_ int x, _In_ int y ) { - return m_width; + m_x = x; + m_y = y; } - int GetHeight() + void SetSize( _In_ int width, _In_ int height ) { - return m_height; + m_width = width; + m_height = height; } + int GetWidth() const { return m_width; } + int GetHeight() const { return m_height; } - static void WINAPI SetRefreshTime( float fTime ) - { - s_fTimeRefresh = fTime; - } + static void WINAPI SetRefreshTime( _In_ float fTime ) { s_fTimeRefresh = fTime; } - static CDXUTControl* WINAPI GetNextControl( CDXUTControl* pControl ); - static CDXUTControl* WINAPI GetPrevControl( CDXUTControl* pControl ); + static CDXUTControl* WINAPI GetNextControl( _In_ CDXUTControl* pControl ); + static CDXUTControl* WINAPI GetPrevControl( _In_ CDXUTControl* pControl ); - void RemoveControl( int ID ); - void RemoveAllControls(); + void RemoveControl( _In_ int ID ); + void RemoveAllControls(); // Sets the callback used to notify the app of control events - void SetCallback( PCALLBACKDXUTGUIEVENT pCallback, void* pUserContext = NULL ); - void EnableNonUserEvents( bool bEnable ) - { - m_bNonUserEvents = bEnable; - } - void EnableKeyboardInput( bool bEnable ) - { - m_bKeyboardInput = bEnable; - } - void EnableMouseInput( bool bEnable ) - { - m_bMouseInput = bEnable; - } - bool IsKeyboardInputEnabled() const - { - return m_bKeyboardInput; - } + void SetCallback( _In_ PCALLBACKDXUTGUIEVENT pCallback, _In_opt_ void* pUserContext = nullptr ); + void EnableNonUserEvents( _In_ bool bEnable ) { m_bNonUserEvents = bEnable; } + void EnableKeyboardInput( _In_ bool bEnable ) { m_bKeyboardInput = bEnable; } + void EnableMouseInput( _In_ bool bEnable ) { m_bMouseInput = bEnable; } + bool IsKeyboardInputEnabled() const { return m_bKeyboardInput; } // Device state notification - void Refresh(); - HRESULT OnRender( float fElapsedTime ); + void Refresh(); + HRESULT OnRender( _In_ float fElapsedTime ); // Shared resource access. Indexed fonts and textures are shared among // all the controls. - HRESULT SetFont( UINT index, LPCWSTR strFaceName, LONG height, LONG weight ); - DXUTFontNode* GetFont( UINT index ); + HRESULT SetFont( _In_ UINT index, _In_z_ LPCWSTR strFaceName, _In_ LONG height, _In_ LONG weight ); + DXUTFontNode* GetFont( _In_ UINT index ) const; - HRESULT SetTexture( UINT index, LPCWSTR strFilename ); - HRESULT SetTexture( UINT index, LPCWSTR strResourceName, HMODULE hResourceModule ); - DXUTTextureNode* GetTexture( UINT index ); + HRESULT SetTexture( _In_ UINT index, _In_z_ LPCWSTR strFilename ); + HRESULT SetTexture( _In_ UINT index, _In_z_ LPCWSTR strResourceName, _In_ HMODULE hResourceModule ); + DXUTTextureNode* GetTexture( _In_ UINT index ) const; - CDXUTDialogResourceManager* GetManager() - { - return m_pManager; - } + CDXUTDialogResourceManager* GetManager() const { return m_pManager; } static void WINAPI ClearFocus(); - void FocusDefaultControl(); + void FocusDefaultControl(); bool m_bNonUserEvents; bool m_bKeyboardInput; @@ -349,24 +294,20 @@ class CDXUTDialog private: int m_nDefaultControlID; - HRESULT OnRender9( float fElapsedTime ); - HRESULT OnRender10( float fElapsedTime ); - HRESULT OnRender11( float fElapsedTime ); - static double s_fTimeRefresh; double m_fTimeLastRefresh; // Initialize default Elements - void InitDefaultElements(); + void InitDefaultElements(); // Windows message handlers - void OnMouseMove( POINT pt ); - void OnMouseUp( POINT pt ); + void OnMouseMove( _In_ const POINT& pt ); + void OnMouseUp( _In_ const POINT& pt ); - void SetNextDialog( CDXUTDialog* pNextDialog ); + void SetNextDialog( _In_ CDXUTDialog* pNextDialog ); // Control events - bool OnCycleFocus( bool bForward ); + bool OnCycleFocus( _In_ bool bForward ); static CDXUTControl* s_pControlFocus; // The control which has focus static CDXUTControl* s_pControlPressed; // The control currently pressed @@ -377,7 +318,7 @@ class CDXUTDialog bool m_bCaption; bool m_bMinimized; bool m_bDrag; - WCHAR m_wszCaption[256]; + WCHAR m_wszCaption[256]; int m_x; int m_y; @@ -385,20 +326,20 @@ class CDXUTDialog int m_height; int m_nCaptionHeight; - D3DCOLOR m_colorTopLeft; - D3DCOLOR m_colorTopRight; - D3DCOLOR m_colorBottomLeft; - D3DCOLOR m_colorBottomRight; + DWORD m_colorTopLeft; + DWORD m_colorTopRight; + DWORD m_colorBottomLeft; + DWORD m_colorBottomRight; CDXUTDialogResourceManager* m_pManager; PCALLBACKDXUTGUIEVENT m_pCallbackEvent; void* m_pCallbackEventUserContext; - CGrowableArray m_Textures; // Index into m_TextureCache; - CGrowableArray m_Fonts; // Index into m_FontCache; + std::vector m_Textures; // Index into m_TextureCache; + std::vector m_Fonts; // Index into m_FontCache; - CGrowableArray m_Controls; - CGrowableArray m_DefaultElements; + std::vector m_Controls; + std::vector m_DefaultElements; CDXUTElement m_CapElement; // Element for the caption @@ -418,7 +359,6 @@ struct DXUTTextureNode WCHAR strFilename[MAX_PATH]; DWORD dwWidth; DWORD dwHeight; - IDirect3DTexture9* pTexture9; ID3D11Texture2D* pTexture11; ID3D11ShaderResourceView* pTexResView11; }; @@ -428,80 +368,55 @@ struct DXUTFontNode WCHAR strFace[MAX_PATH]; LONG nHeight; LONG nWeight; - ID3DXFont* pFont9; }; struct DXUTSpriteVertex { - D3DXVECTOR3 vPos; - D3DXCOLOR vColor; - D3DXVECTOR2 vTex; + DirectX::XMFLOAT3 vPos; + DirectX::XMFLOAT4 vColor; + DirectX::XMFLOAT2 vTex; }; + //----------------------------------------------------------------------------- // Manages shared resources of dialogs //----------------------------------------------------------------------------- class CDXUTDialogResourceManager { public: - CDXUTDialogResourceManager(); - ~CDXUTDialogResourceManager(); + CDXUTDialogResourceManager() noexcept; + ~CDXUTDialogResourceManager(); - bool MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - - // D3D9 specific - HRESULT OnD3D9CreateDevice( LPDIRECT3DDEVICE9 pd3dDevice ); - HRESULT OnD3D9ResetDevice(); - void OnD3D9LostDevice(); - void OnD3D9DestroyDevice(); - IDirect3DDevice9* GetD3D9Device() - { - return m_pd3d9Device; - } + bool MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); // D3D11 specific - HRESULT OnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ); - HRESULT OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); - void OnD3D11ReleasingSwapChain(); - void OnD3D11DestroyDevice(); - void StoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ); - void RestoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ); - void ApplyRenderUI11( ID3D11DeviceContext* pd3dImmediateContext ); - void ApplyRenderUIUntex11( ID3D11DeviceContext* pd3dImmediateContext ); - void BeginSprites11( ); - void EndSprites11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ); - ID3D11Device* GetD3D11Device() - { - return m_pd3d11Device; - } - ID3D11DeviceContext* GetD3D11DeviceContext() - { - return m_pd3d11DeviceContext; - } - - DXUTFontNode* GetFontNode( int iIndex ) - { - return m_FontCache.GetAt( iIndex ); - }; - DXUTTextureNode* GetTextureNode( int iIndex ) - { - return m_TextureCache.GetAt( iIndex ); - }; - - int AddFont( LPCWSTR strFaceName, LONG height, LONG weight ); - int AddTexture( LPCWSTR strFilename ); - int AddTexture( LPCWSTR strResourceName, HMODULE hResourceModule ); - - bool RegisterDialog( CDXUTDialog* pDialog ); - void UnregisterDialog( CDXUTDialog* pDialog ); - void EnableKeyboardInputForAllDialogs(); + HRESULT OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext ); + HRESULT OnD3D11ResizedSwapChain( _In_ ID3D11Device* pd3dDevice, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); + void OnD3D11ReleasingSwapChain(); + void OnD3D11DestroyDevice(); + void StoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void RestoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void ApplyRenderUI11( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void ApplyRenderUIUntex11( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void BeginSprites11( ); + void EndSprites11( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext ); + + ID3D11Device* GetD3D11Device() const { return m_pd3d11Device; } + ID3D11DeviceContext* GetD3D11DeviceContext() const { return m_pd3d11DeviceContext; } + + DXUTFontNode* GetFontNode( _In_ size_t iIndex ) const { return m_FontCache[ iIndex ]; } + DXUTTextureNode* GetTextureNode( _In_ size_t iIndex ) const { return m_TextureCache[ iIndex ]; } + + int AddFont( _In_z_ LPCWSTR strFaceName, _In_ LONG height, _In_ LONG weight ); + int AddTexture( _In_z_ LPCWSTR strFilename ); + int AddTexture( _In_z_ LPCWSTR strResourceName, _In_ HMODULE hResourceModule ); + + bool RegisterDialog( _In_ CDXUTDialog* pDialog ); + void UnregisterDialog( _In_ CDXUTDialog* pDialog ); + void EnableKeyboardInputForAllDialogs(); // Shared between all dialogs - // D3D9 - IDirect3DStateBlock9* m_pStateBlock; - ID3DXSprite* m_pSprite; // Sprite used for drawing - // D3D11 // Shaders ID3D11VertexShader* m_pVSRenderUI11; @@ -529,34 +444,23 @@ class CDXUTDialogResourceManager // Sprite workaround ID3D11Buffer* m_pSpriteBuffer11; UINT m_SpriteBufferBytes11; - CGrowableArray m_SpriteVertices; + std::vector m_SpriteVertices; UINT m_nBackBufferWidth; UINT m_nBackBufferHeight; - CGrowableArray m_Dialogs; // Dialogs registered + std::vector m_Dialogs; // Dialogs registered protected: - // D3D9 specific - IDirect3DDevice9* m_pd3d9Device; - HRESULT CreateFont9( UINT index ); - HRESULT CreateTexture9( UINT index ); - // D3D11 specific ID3D11Device* m_pd3d11Device; ID3D11DeviceContext* m_pd3d11DeviceContext; - HRESULT CreateFont11( UINT index ); - HRESULT CreateTexture11( UINT index ); + HRESULT CreateTexture11( _In_ UINT index ); - CGrowableArray m_TextureCache; // Shared textures - CGrowableArray m_FontCache; // Shared fonts + std::vector m_TextureCache; // Shared textures + std::vector m_FontCache; // Shared fonts }; -void BeginText11(); -void DrawText11DXUT( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, RECT rcScreen, D3DXCOLOR vFontColor, - float fBBWidth, float fBBHeight, bool bCenter ); -void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ); //----------------------------------------------------------------------------- // Base class for controls @@ -564,126 +468,79 @@ void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceConte class CDXUTControl { public: - CDXUTControl( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTControl(); + CDXUTControl( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; + virtual ~CDXUTControl(); - virtual HRESULT OnInit() - { - return S_OK; - } - virtual void Refresh(); - virtual void Render( float fElapsedTime ) - { - }; + virtual HRESULT OnInit() { return S_OK; } + virtual void Refresh(); + virtual void Render( _In_ float fElapsedTime ) { UNREFERENCED_PARAMETER(fElapsedTime); } // Windows message handler - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(pt); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } - virtual bool CanHaveFocus() - { - return false; - } - virtual void OnFocusIn() - { - m_bHasFocus = true; - } - virtual void OnFocusOut() - { - m_bHasFocus = false; - } - virtual void OnMouseEnter() - { - m_bMouseOver = true; - } - virtual void OnMouseLeave() - { - m_bMouseOver = false; - } - virtual void OnHotkey() - { - } + virtual bool CanHaveFocus() { return false; } + virtual void OnFocusIn() { m_bHasFocus = true; } + virtual void OnFocusOut() { m_bHasFocus = false; } + virtual void OnMouseEnter() { m_bMouseOver = true; } + virtual void OnMouseLeave() { m_bMouseOver = false; } + virtual void OnHotkey() { } - virtual BOOL ContainsPoint( POINT pt ) - { - return PtInRect( &m_rcBoundingBox, pt ); - } + virtual bool ContainsPoint( _In_ const POINT& pt ) { return PtInRect( &m_rcBoundingBox, pt ) != 0; } - virtual void SetEnabled( bool bEnabled ) - { - m_bEnabled = bEnabled; - } - virtual bool GetEnabled() - { - return m_bEnabled; - } - virtual void SetVisible( bool bVisible ) - { - m_bVisible = bVisible; - } - virtual bool GetVisible() - { - return m_bVisible; - } + virtual void SetEnabled( _In_ bool bEnabled ) { m_bEnabled = bEnabled; } + virtual bool GetEnabled() const { return m_bEnabled; } + virtual void SetVisible( _In_ bool bVisible ) { m_bVisible = bVisible; } + virtual bool GetVisible() const { return m_bVisible; } - UINT GetType() const - { - return m_Type; - } + UINT GetType() const { return m_Type; } - int GetID() const - { - return m_ID; - } - void SetID( int ID ) - { - m_ID = ID; - } + int GetID() const { return m_ID; } + void SetID( _In_ int ID ) { m_ID = ID; } - void SetLocation( int x, int y ) + void SetLocation( _In_ int x, _In_ int y ) { - m_x = x; m_y = y; UpdateRects(); + m_x = x; + m_y = y; + UpdateRects(); } - void SetSize( int width, int height ) + void SetSize( int width, int height ) { - m_width = width; m_height = height; UpdateRects(); + m_width = width; + m_height = height; + UpdateRects(); } - void SetHotkey( UINT nHotkey ) - { - m_nHotkey = nHotkey; - } - UINT GetHotkey() - { - return m_nHotkey; - } + void SetHotkey( _In_ UINT nHotkey ) { m_nHotkey = nHotkey; } + UINT GetHotkey() const { return m_nHotkey; } - void SetUserData( void* pUserData ) - { - m_pUserData = pUserData; - } - void* GetUserData() const - { - return m_pUserData; - } + void SetUserData( _In_opt_ void* pUserData ) { m_pUserData = pUserData; } + void* GetUserData() const { return m_pUserData; } - virtual void SetTextColor( D3DCOLOR Color ); - CDXUTElement* GetElement( UINT iElement ) - { - return m_Elements.GetAt( iElement ); - } - HRESULT SetElement( UINT iElement, CDXUTElement* pElement ); + virtual void SetTextColor( _In_ DWORD Color ); + CDXUTElement* GetElement( _In_ UINT iElement ) const { return m_Elements[ iElement ]; } + HRESULT SetElement( _In_ UINT iElement, _In_ CDXUTElement* pElement ); bool m_bVisible; // Shown/hidden flag bool m_bMouseOver; // Mouse pointer is above control @@ -698,10 +555,10 @@ class CDXUTControl CDXUTDialog* m_pDialog; // Parent container UINT m_Index; // Index within the control list - CGrowableArray m_Elements; // All display elements + std::vector m_Elements; // All display elements protected: - virtual void UpdateRects(); + virtual void UpdateRects(); int m_ID; // ID number DXUT_CONTROL_TYPE m_Type; // Control type, set once in constructor @@ -732,25 +589,21 @@ struct DXUTElementHolder class CDXUTStatic : public CDXUTControl { public: - CDXUTStatic( CDXUTDialog* pDialog = NULL ); + CDXUTStatic( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; - virtual void Render( float fElapsedTime ); - virtual BOOL ContainsPoint( POINT pt ) + virtual void Render( _In_ float fElapsedTime ) override; + virtual bool ContainsPoint( _In_ const POINT& pt ) override { + UNREFERENCED_PARAMETER( pt ); return false; } - HRESULT GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ); - LPCWSTR GetText() - { - return m_strText; - } - HRESULT SetText( LPCWSTR strText ); - + HRESULT GetTextCopy( _Out_writes_(bufferCount) LPWSTR strDest, _In_ UINT bufferCount ) const; + LPCWSTR GetText() const { return m_strText; } + HRESULT SetText( _In_z_ LPCWSTR strText ); protected: - WCHAR m_strText[MAX_PATH]; // Window text + WCHAR m_strText[MAX_PATH]; // Window text }; @@ -760,26 +613,26 @@ class CDXUTStatic : public CDXUTControl class CDXUTButton : public CDXUTStatic { public: - CDXUTButton( CDXUTDialog* pDialog = NULL ); + CDXUTButton( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey() + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override { if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this ); m_pDialog->SendEvent( EVENT_BUTTON_CLICKED, true, this ); } - virtual BOOL ContainsPoint( POINT pt ) + virtual bool ContainsPoint( _In_ const POINT& pt ) override { - return PtInRect( &m_rcBoundingBox, pt ); + return PtInRect( &m_rcBoundingBox, pt ) != 0; } - virtual bool CanHaveFocus() + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual void Render( float fElapsedTime ); + virtual void Render( _In_ float fElapsedTime ) override; protected: bool m_bPressed; @@ -792,32 +645,26 @@ class CDXUTButton : public CDXUTStatic class CDXUTCheckBox : public CDXUTButton { public: - CDXUTCheckBox( CDXUTDialog* pDialog = NULL ); + CDXUTCheckBox( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey() + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override { if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this ); SetCheckedInternal( !m_bChecked, true ); } - virtual BOOL ContainsPoint( POINT pt ); - virtual void UpdateRects(); + virtual bool ContainsPoint( _In_ const POINT& pt ) override; + virtual void UpdateRects() override; - virtual void Render( float fElapsedTime ); + virtual void Render( _In_ float fElapsedTime ) override; - bool GetChecked() - { - return m_bChecked; - } - void SetChecked( bool bChecked ) - { - SetCheckedInternal( bChecked, false ); - } + bool GetChecked() const { return m_bChecked; } + void SetChecked( _In_ bool bChecked ) { SetCheckedInternal( bChecked, false ); } protected: - virtual void SetCheckedInternal( bool bChecked, bool bFromInput ); + virtual void SetCheckedInternal( _In_ bool bChecked, _In_ bool bFromInput ); bool m_bChecked; RECT m_rcButton; @@ -831,31 +678,22 @@ class CDXUTCheckBox : public CDXUTButton class CDXUTRadioButton : public CDXUTCheckBox { public: - CDXUTRadioButton( CDXUTDialog* pDialog = NULL ); + CDXUTRadioButton( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey() + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override { if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this ); SetCheckedInternal( true, true, true ); } - void SetChecked( bool bChecked, bool bClearGroup=true ) - { - SetCheckedInternal( bChecked, bClearGroup, false ); - } - void SetButtonGroup( UINT nButtonGroup ) - { - m_nButtonGroup = nButtonGroup; - } - UINT GetButtonGroup() - { - return m_nButtonGroup; - } + void SetChecked( _In_ bool bChecked, _In_ bool bClearGroup=true ) { SetCheckedInternal( bChecked, bClearGroup, false ); } + void SetButtonGroup( _In_ UINT nButtonGroup ) { m_nButtonGroup = nButtonGroup; } + UINT GetButtonGroup() const { return m_nButtonGroup; } protected: - virtual void SetCheckedInternal( bool bChecked, bool bClearGroup, bool bFromInput ); + virtual void SetCheckedInternal( _In_ bool bChecked, _In_ bool bClearGroup, _In_ bool bFromInput ); UINT m_nButtonGroup; }; @@ -866,36 +704,34 @@ class CDXUTRadioButton : public CDXUTCheckBox class CDXUTScrollBar : public CDXUTControl { public: - CDXUTScrollBar( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTScrollBar(); + CDXUTScrollBar( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; + virtual ~CDXUTScrollBar(); - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; - virtual void Render( float fElapsedTime ); - virtual void UpdateRects(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual void UpdateRects() override; - void SetTrackRange( int nStart, int nEnd ); - int GetTrackPos() - { - return m_nPosition; - } - void SetTrackPos( int nPosition ) - { - m_nPosition = nPosition; Cap(); UpdateThumbRect(); - } - int GetPageSize() + void SetTrackRange( _In_ int nStart, _In_ int nEnd ); + int GetTrackPos() const { return m_nPosition; } + void SetTrackPos( _In_ int nPosition ) { - return m_nPageSize; + m_nPosition = nPosition; + Cap(); + UpdateThumbRect(); } - void SetPageSize( int nPageSize ) + int GetPageSize() const { return m_nPageSize; } + void SetPageSize( _In_ int nPageSize ) { - m_nPageSize = nPageSize; Cap(); UpdateThumbRect(); + m_nPageSize = nPageSize; + Cap(); + UpdateThumbRect(); } - void Scroll( int nDelta ); // Scroll by nDelta items (plus or minus) - void ShowItem( int nIndex ); // Ensure that item nIndex is displayed, scroll if necessary + void Scroll( _In_ int nDelta ); // Scroll by nDelta items (plus or minus) + void ShowItem( _In_ int nIndex ); // Ensure that item nIndex is displayed, scroll if necessary protected: // ARROWSTATE indicates the state of the arrow buttons. @@ -947,60 +783,50 @@ struct DXUTListBoxItem class CDXUTListBox : public CDXUTControl { public: - CDXUTListBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTListBox(); + CDXUTListBox( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; + virtual ~CDXUTListBox(); - virtual HRESULT OnInit() + virtual HRESULT OnInit() override { return m_pDialog->InitControl( &m_ScrollBar ); } - virtual bool CanHaveFocus() + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; - virtual void Render( float fElapsedTime ); - virtual void UpdateRects(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual void UpdateRects() override; - DWORD GetStyle() const + DWORD GetStyle() const { return m_dwStyle; } + size_t GetSize() const { return m_Items.size(); } + void SetStyle( _In_ DWORD dwStyle ) { m_dwStyle = dwStyle; } + int GetScrollBarWidth() const{ return m_nSBWidth; } + void SetScrollBarWidth( _In_ int nWidth ) { - return m_dwStyle; + m_nSBWidth = nWidth; + UpdateRects(); } - int GetSize() const + void SetBorder( _In_ int nBorder, _In_ int nMargin ) { - return m_Items.GetSize(); + m_nBorder = nBorder; + m_nMargin = nMargin; } - void SetStyle( DWORD dwStyle ) - { - m_dwStyle = dwStyle; - } - int GetScrollBarWidth() const - { - return m_nSBWidth; - } - void SetScrollBarWidth( int nWidth ) - { - m_nSBWidth = nWidth; UpdateRects(); - } - void SetBorder( int nBorder, int nMargin ) - { - m_nBorder = nBorder; m_nMargin = nMargin; - } - HRESULT AddItem( const WCHAR* wszText, void* pData ); - HRESULT InsertItem( int nIndex, const WCHAR* wszText, void* pData ); - void RemoveItem( int nIndex ); - void RemoveAllItems(); - - DXUTListBoxItem* GetItem( int nIndex ); - int GetSelectedIndex( int nPreviousSelected = -1 ); - DXUTListBoxItem* GetSelectedItem( int nPreviousSelected = -1 ) + HRESULT AddItem( _In_z_ const WCHAR* wszText, _In_opt_ void* pData ); + HRESULT InsertItem( _In_ int nIndex, _In_z_ const WCHAR* wszText, _In_opt_ void* pData ); + void RemoveItem( _In_ int nIndex ); + void RemoveAllItems(); + + DXUTListBoxItem* GetItem( _In_ int nIndex ) const; + int GetSelectedIndex( _In_ int nPreviousSelected = -1 ) const; + DXUTListBoxItem* GetSelectedItem( _In_ int nPreviousSelected = -1 ) const { return GetItem( GetSelectedIndex( nPreviousSelected ) ); } - void SelectItem( int nNewIndex ); + void SelectItem( _In_ int nNewIndex ); enum STYLE { @@ -1020,7 +846,7 @@ class CDXUTListBox : public CDXUTControl int m_nSelStart; // Index of the item where selection starts (for handling multi-selection) bool m_bDrag; // Whether the user is dragging the mouse to select - CGrowableArray m_Items; + std::vector m_Items; }; @@ -1036,71 +862,60 @@ struct DXUTComboBoxItem bool bVisible; }; - class CDXUTComboBox : public CDXUTButton { public: - CDXUTComboBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTComboBox(); + CDXUTComboBox( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; + virtual ~CDXUTComboBox(); - virtual void SetTextColor( D3DCOLOR Color ); - virtual HRESULT OnInit() + virtual void SetTextColor( _In_ DWORD Color ) override; + virtual HRESULT OnInit() override { return m_pDialog->InitControl( &m_ScrollBar ); } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey(); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override; - virtual bool CanHaveFocus() + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual void OnFocusOut(); - virtual void Render( float fElapsedTime ); - - virtual void UpdateRects(); - - HRESULT AddItem( const WCHAR* strText, void* pData ); - void RemoveAllItems(); - void RemoveItem( UINT index ); - bool ContainsItem( const WCHAR* strText, UINT iStart=0 ); - int FindItem( const WCHAR* strText, UINT iStart=0 ); - void* GetItemData( const WCHAR* strText ); - void* GetItemData( int nIndex ); - void SetDropHeight( UINT nHeight ) - { - m_nDropHeight = nHeight; UpdateRects(); - } - int GetScrollBarWidth() const - { - return m_nSBWidth; - } - void SetScrollBarWidth( int nWidth ) - { - m_nSBWidth = nWidth; UpdateRects(); - } + virtual void OnFocusOut() override; + virtual void Render( _In_ float fElapsedTime ) override; - int GetSelectedIndex() const - { - return m_iSelected; - } - void* GetSelectedData(); - DXUTComboBoxItem* GetSelectedItem(); + virtual void UpdateRects() override; - UINT GetNumItems() + HRESULT AddItem( _In_z_ const WCHAR* strText, _In_opt_ void* pData ); + void RemoveAllItems(); + void RemoveItem( _In_ UINT index ); + bool ContainsItem( _In_z_ const WCHAR* strText, _In_ UINT iStart=0 ); + int FindItem( _In_z_ const WCHAR* strText, _In_ UINT iStart=0 ) const; + void* GetItemData( _In_z_ const WCHAR* strText ) const; + void* GetItemData( _In_ int nIndex ) const; + void SetDropHeight( _In_ UINT nHeight ) { - return m_Items.GetSize(); + m_nDropHeight = nHeight; + UpdateRects(); } - DXUTComboBoxItem* GetItem( UINT index ) + int GetScrollBarWidth() const { return m_nSBWidth; } + void SetScrollBarWidth( _In_ int nWidth ) { - return m_Items.GetAt( index ); + m_nSBWidth = nWidth; + UpdateRects(); } - HRESULT SetSelectedByIndex( UINT index ); - HRESULT SetSelectedByText( const WCHAR* strText ); - HRESULT SetSelectedByData( void* pData ); + int GetSelectedIndex() const { return m_iSelected; } + void* GetSelectedData() const; + DXUTComboBoxItem* GetSelectedItem() const; + + UINT GetNumItems() { return static_cast( m_Items.size() ); } + DXUTComboBoxItem* GetItem( _In_ UINT index ) { return m_Items[ index ]; } + + HRESULT SetSelectedByIndex( _In_ UINT index ); + HRESULT SetSelectedByText( _In_z_ const WCHAR* strText ); + HRESULT SetSelectedByData( _In_ void* pData ); protected: int m_iSelected; @@ -1116,8 +931,7 @@ class CDXUTComboBox : public CDXUTButton RECT m_rcDropdown; RECT m_rcDropdownText; - - CGrowableArray m_Items; + std::vector m_Items; }; @@ -1127,38 +941,33 @@ class CDXUTComboBox : public CDXUTButton class CDXUTSlider : public CDXUTControl { public: - CDXUTSlider( CDXUTDialog* pDialog = NULL ); + CDXUTSlider( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; - virtual BOOL ContainsPoint( POINT pt ); - virtual bool CanHaveFocus() + virtual bool ContainsPoint( _In_ const POINT& pt ) override; + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; - virtual void UpdateRects(); + virtual void UpdateRects() override; - virtual void Render( float fElapsedTime ); + virtual void Render( _In_ float fElapsedTime ) override; - void SetValue( int nValue ) - { - SetValueInternal( nValue, false ); - } - int GetValue() const - { - return m_nValue; - }; + void SetValue( int nValue ) { SetValueInternal( nValue, false ); } + int GetValue() const { return m_nValue; } - void GetRange( int& nMin, int& nMax ) const + void GetRange( _Out_ int& nMin, _Out_ int& nMax ) const { - nMin = m_nMin; nMax = m_nMax; + nMin = m_nMin; + nMax = m_nMax; } - void SetRange( int nMin, int nMax ); + void SetRange( _In_ int nMin, _In_ int nMax ); protected: - void SetValueInternal( int nValue, bool bFromInput ); - int ValueFromPos( int x ); + void SetValueInternal( _In_ int nValue, _In_ bool bFromInput ); + int ValueFromPos( _In_ int x ); int m_nValue; @@ -1180,53 +989,44 @@ class CDXUTSlider : public CDXUTControl class CUniBuffer { public: - CUniBuffer( int nInitialSize = 1 ); - ~CUniBuffer(); - - static void WINAPI Initialize(); - static void WINAPI Uninitialize(); + CUniBuffer( _In_ int nInitialSize = 1 ) noexcept; + ~CUniBuffer(); - int GetBufferSize() - { - return m_nBufferSize; - } - bool SetBufferSize( int nSize ); - int GetTextSize() - { - return lstrlenW( m_pwszBuffer ); - } - const WCHAR* GetBuffer() + size_t GetBufferSize() const { return m_nBufferSize; } + bool SetBufferSize( _In_ int nSize ); + int GetTextSize() const { return (int)wcslen( m_pwszBuffer ); } + const WCHAR* GetBuffer() const { return m_pwszBuffer; } - const WCHAR& operator[]( int n ) const + const WCHAR& operator[]( _In_ int n ) const { return m_pwszBuffer[n]; } - WCHAR& operator[]( int n ); - DXUTFontNode* GetFontNode() - { - return m_pFontNode; - } - void SetFontNode( DXUTFontNode* pFontNode ) - { - m_pFontNode = pFontNode; - } - void Clear(); + WCHAR& operator[]( _In_ int n ); + DXUTFontNode* GetFontNode() const { return m_pFontNode; } + void SetFontNode( _In_opt_ DXUTFontNode* pFontNode ) { m_pFontNode = pFontNode; } + void Clear(); + + bool InsertChar( _In_ int nIndex, _In_ WCHAR wChar ); + // Inserts the char at specified index. If nIndex == -1, insert to the end. - bool InsertChar( int nIndex, WCHAR wChar ); // Inserts the char at specified index. If nIndex == -1, insert to the end. - bool RemoveChar( int nIndex ); // Removes the char at specified index. If nIndex == -1, remove the last char. - bool InsertString( int nIndex, const WCHAR* pStr, int nCount = -1 ); // Inserts the first nCount characters of the string pStr at specified index. If nCount == -1, the entire string is inserted. If nIndex == -1, insert to the end. - bool SetText( LPCWSTR wszText ); + bool RemoveChar( _In_ int nIndex ); + // Removes the char at specified index. If nIndex == -1, remove the last char. + + bool InsertString( _In_ int nIndex, _In_z_ const WCHAR* pStr, _In_ int nCount = -1 ); + // Inserts the first nCount characters of the string pStr at specified index. If nCount == -1, the entire string is inserted. If nIndex == -1, insert to the end. + + bool SetText( _In_z_ LPCWSTR wszText ); // Uniscribe - HRESULT CPtoX( int nCP, BOOL bTrail, int* pX ); - HRESULT XtoCP( int nX, int* pCP, int* pnTrail ); - void GetPriorItemPos( int nCP, int* pPrior ); - void GetNextItemPos( int nCP, int* pPrior ); + bool CPtoX( _In_ int nCP, _In_ bool bTrail, _Out_ int* pX ); + bool XtoCP( _In_ int nX, _Out_ int* pCP, _Out_ int* pnTrail ); + void GetPriorItemPos( _In_ int nCP, _Out_ int* pPrior ); + void GetNextItemPos( _In_ int nCP, _Out_ int* pPrior ); private: - HRESULT Analyse(); // Uniscribe -- Analyse() analyses the string in the buffer + HRESULT Analyse(); // Uniscribe -- Analyse() analyses the string in the buffer WCHAR* m_pwszBuffer; // Buffer to hold text int m_nBufferSize; // Size of the buffer allocated, in characters @@ -1235,123 +1035,58 @@ class CUniBuffer DXUTFontNode* m_pFontNode; // Font node for the font that this buffer uses bool m_bAnalyseRequired; // True if the string has changed since last analysis. SCRIPT_STRING_ANALYSIS m_Analysis; // Analysis for the current string - -private: - // Empty implementation of the Uniscribe API - static HRESULT WINAPI Dummy_ScriptApplyDigitSubstitution( const SCRIPT_DIGITSUBSTITUTE*, SCRIPT_CONTROL*, - SCRIPT_STATE* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringAnalyse( HDC, const void*, int, int, int, DWORD, int, SCRIPT_CONTROL*, - SCRIPT_STATE*, const int*, SCRIPT_TABDEF*, const BYTE*, - SCRIPT_STRING_ANALYSIS* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringCPtoX( SCRIPT_STRING_ANALYSIS, int, BOOL, int* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringXtoCP( SCRIPT_STRING_ANALYSIS, int, int*, int* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringFree( SCRIPT_STRING_ANALYSIS* ) - { - return E_NOTIMPL; - } - static const SCRIPT_LOGATTR* WINAPI Dummy_ScriptString_pLogAttr( SCRIPT_STRING_ANALYSIS ) - { - return NULL; - } - static const int* WINAPI Dummy_ScriptString_pcOutChars( SCRIPT_STRING_ANALYSIS ) - { - return NULL; - } - - // Function pointers - static HRESULT( WINAPI* _ScriptApplyDigitSubstitution )( const SCRIPT_DIGITSUBSTITUTE*, - SCRIPT_CONTROL*, SCRIPT_STATE* ); - static HRESULT( WINAPI* _ScriptStringAnalyse )( HDC, const void*, int, int, int, DWORD, int, - SCRIPT_CONTROL*, SCRIPT_STATE*, const int*, - SCRIPT_TABDEF*, const BYTE*, - SCRIPT_STRING_ANALYSIS* ); - static HRESULT( WINAPI* _ScriptStringCPtoX )( SCRIPT_STRING_ANALYSIS, int, BOOL, int* ); - static HRESULT( WINAPI* _ScriptStringXtoCP )( SCRIPT_STRING_ANALYSIS, int, int*, int* ); - static HRESULT( WINAPI* _ScriptStringFree )( SCRIPT_STRING_ANALYSIS* ); - static const SCRIPT_LOGATTR* ( WINAPI*_ScriptString_pLogAttr )( SCRIPT_STRING_ANALYSIS ); - static const int* ( WINAPI*_ScriptString_pcOutChars )( SCRIPT_STRING_ANALYSIS ); - - static HINSTANCE s_hDll; // Uniscribe DLL handle - }; + //----------------------------------------------------------------------------- // EditBox control //----------------------------------------------------------------------------- class CDXUTEditBox : public CDXUTControl { public: - CDXUTEditBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTEditBox(); - - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual void UpdateRects(); - virtual bool CanHaveFocus() + CDXUTEditBox( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; + virtual ~CDXUTEditBox(); + + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void UpdateRects() override; + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual void Render( float fElapsedTime ); - virtual void OnFocusIn(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual void OnFocusIn() override; - void SetText( LPCWSTR wszText, bool bSelected = false ); - LPCWSTR GetText() - { - return m_Buffer.GetBuffer(); - } - int GetTextLength() - { - return m_Buffer.GetTextSize(); - } // Returns text length in chars excluding NULL. - HRESULT GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ); - void ClearText(); - virtual void SetTextColor( D3DCOLOR Color ) - { - m_TextColor = Color; - } // Text color - void SetSelectedTextColor( D3DCOLOR Color ) - { - m_SelTextColor = Color; - } // Selected text color - void SetSelectedBackColor( D3DCOLOR Color ) - { - m_SelBkColor = Color; - } // Selected background color - void SetCaretColor( D3DCOLOR Color ) - { - m_CaretColor = Color; - } // Caret color - void SetBorderWidth( int nBorder ) + void SetText( _In_z_ LPCWSTR wszText, _In_ bool bSelected = false ); + LPCWSTR GetText() const { return m_Buffer.GetBuffer(); } + size_t GetTextLength() const { return m_Buffer.GetTextSize(); } // Returns text length in chars excluding nul. + HRESULT GetTextCopy( _Out_writes_(bufferCount) LPWSTR strDest, _In_ UINT bufferCount ) const; + void ClearText(); + + virtual void SetTextColor( _In_ DWORD Color ) override { m_TextColor = Color; } // Text color + void SetSelectedTextColor( _In_ DWORD Color ) { m_SelTextColor = Color; } // Selected text color + void SetSelectedBackColor( _In_ DWORD Color ) { m_SelBkColor = Color; } // Selected background color + void SetCaretColor( _In_ DWORD Color ) { m_CaretColor = Color; } // Caret color + void SetBorderWidth( _In_ int nBorder ) { - m_nBorder = nBorder; UpdateRects(); + m_nBorder = nBorder; + UpdateRects(); } // Border of the window - void SetSpacing( int nSpacing ) + void SetSpacing( _In_ int nSpacing ) { - m_nSpacing = nSpacing; UpdateRects(); + m_nSpacing = nSpacing; + UpdateRects(); } - void ParseFloatArray( float* pNumbers, int nCount ); - void SetTextFloatArray( const float* pNumbers, int nCount ); + void ParseFloatArray( _In_reads_(nCount) float* pNumbers, _In_ int nCount ); + void SetTextFloatArray( _In_reads_(nCount) const float* pNumbers, _In_ int nCount ); protected: - void PlaceCaret( int nCP ); - void DeleteSelectionText(); - void ResetCaretBlink(); - void CopyToClipboard(); - void PasteFromClipboard(); + void PlaceCaret( _In_ int nCP ); + void DeleteSelectionText(); + void ResetCaretBlink(); + void CopyToClipboard(); + void PasteFromClipboard(); CUniBuffer m_Buffer; // Buffer to hold text int m_nBorder; // Border of the window @@ -1365,10 +1100,10 @@ class CDXUTEditBox : public CDXUTControl bool m_bInsertMode; // If true, control is in insert mode. Else, overwrite mode. int m_nSelStart; // Starting position of the selection. The caret marks the end. int m_nFirstVisible;// First visible character in the edit control - D3DCOLOR m_TextColor; // Text color - D3DCOLOR m_SelTextColor; // Selected text color - D3DCOLOR m_SelBkColor; // Selected background color - D3DCOLOR m_CaretColor; // Caret color + DWORD m_TextColor; // Text color + DWORD m_SelTextColor; // Selected text color + DWORD m_SelBkColor; // Selected background color + DWORD m_CaretColor; // Caret color // Mouse-specific bool m_bMouseDrag; // True to indicate drag in progress @@ -1378,6 +1113,9 @@ class CDXUTEditBox : public CDXUTControl }; - - -#endif // DXUT_GUI_H +//----------------------------------------------------------------------------- +void BeginText11(); +void DrawText11DXUT( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext, + _In_z_ LPCWSTR strText, _In_ const RECT& rcScreen, _In_ DirectX::XMFLOAT4 vFontColor, + _In_ float fBBWidth, _In_ float fBBHeight, _In_ bool bCenter ); +void EndText11( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext ); diff --git a/FriedLiver/Source/DXUT/Optional/DXUTguiIME.cpp b/FriedLiver/Source/DXUT/Optional/DXUTguiIME.cpp index 11961795..c73eb7a2 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTguiIME.cpp +++ b/FriedLiver/Source/DXUT/Optional/DXUTguiIME.cpp @@ -2,6 +2,9 @@ // File: DXUTguiIME.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTgui.h" @@ -10,8 +13,6 @@ #include "DXUTgui.h" #include "DXUTguiIME.h" -#undef min // use __min instead -#undef max // use __max instead #define DXUT_NEAR_BUTTON_DEPTH 0.6f @@ -35,15 +36,16 @@ bool CDXUTIMEEditBox::m_bIMEStaticMsgProcCalled = false; //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTIMEEditBox::CreateIMEEditBox( CDXUTDialog* pDialog, int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault, CDXUTIMEEditBox** ppCreated ) { - CDXUTIMEEditBox* pEditBox = new CDXUTIMEEditBox( pDialog ); + auto pEditBox = new (std::nothrow) CDXUTIMEEditBox( pDialog ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pEditBox; - if( pEditBox == NULL ) + if( !pEditBox ) return E_OUTOFMEMORY; // Set the ID and position @@ -60,7 +62,7 @@ HRESULT CDXUTIMEEditBox::CreateIMEEditBox( CDXUTDialog* pDialog, int ID, LPCWSTR //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::InitDefaultElements( CDXUTDialog* pDialog ) +void CDXUTIMEEditBox::InitDefaultElements( _In_ CDXUTDialog* pDialog ) { //------------------------------------- // CDXUTIMEEditBox @@ -108,12 +110,13 @@ void CDXUTIMEEditBox::InitDefaultElements( CDXUTDialog* pDialog ) //-------------------------------------------------------------------------------------- -CDXUTIMEEditBox::CDXUTIMEEditBox( CDXUTDialog* pDialog ) +CDXUTIMEEditBox::CDXUTIMEEditBox( _In_opt_ CDXUTDialog* pDialog ) noexcept : + m_nIndicatorWidth(0), + m_rcIndicator{} { m_Type = DXUT_CONTROL_IMEEDITBOX; m_pDialog = pDialog; - m_nIndicatorWidth = 0; m_ReadingColor = D3DCOLOR_ARGB( 188, 255, 255, 255 ); m_ReadingWinColor = D3DCOLOR_ARGB( 128, 0, 0, 0 ); m_ReadingSelColor = D3DCOLOR_ARGB( 255, 255, 0, 0 ); @@ -142,7 +145,7 @@ CDXUTIMEEditBox::~CDXUTIMEEditBox() //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::SendKey( BYTE nVirtKey ) +void CDXUTIMEEditBox::SendKey( _In_ BYTE nVirtKey ) { keybd_event( nVirtKey, 0, 0, 0 ); keybd_event( nVirtKey, 0, KEYEVENTF_KEYUP, 0 ); @@ -193,7 +196,7 @@ void CDXUTIMEEditBox::UpdateRects() //-------------------------------------------------------------------------------------- // Enable/disable the entire IME system. When disabled, the default IME handling // kicks in. -void CDXUTIMEEditBox::EnableImeSystem( bool bEnable ) +void CDXUTIMEEditBox::EnableImeSystem( _In_ bool bEnable ) { ImeUi_EnableIme( bEnable ); } @@ -214,9 +217,9 @@ void CDXUTIMEEditBox::PumpMessage() { MSG msg; - while( PeekMessageW( &msg, NULL, 0, 0, PM_NOREMOVE ) ) + while( PeekMessageW( &msg, nullptr, 0, 0, PM_NOREMOVE ) ) { - if( !GetMessageW( &msg, NULL, 0, 0 ) ) + if( !GetMessageW( &msg, nullptr, 0, 0 ) ) { PostQuitMessage( ( int )msg.wParam ); return; @@ -245,8 +248,11 @@ void CDXUTIMEEditBox::OnFocusOut() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTIMEEditBox::StaticMsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(hWnd); + UNREFERENCED_PARAMETER(wParam); if( !ImeUi_IsEnabled() ) return false; @@ -295,7 +301,8 @@ bool CDXUTIMEEditBox::StaticMsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM //-------------------------------------------------------------------------------------- -bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) return false; @@ -305,7 +312,7 @@ bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lP case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: { - DXUTFontNode* pFont = m_pDialog->GetFont( m_Elements.GetAt( 9 )->iFont ); + auto pFont = m_pDialog->GetFont( m_Elements[ 9 ]->iFont ); // Check if this click is on top of the composition string int nCompStrWidth; @@ -430,7 +437,7 @@ bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lP if( nCharHit >= nEntryStart ) { // Haven't found it. - nEntryStart += lstrlenW( ImeUi_GetCandidate( i ) ) + 1; // plus space separator + nEntryStart += (int)wcslen( ImeUi_GetCandidate( i ) ) + 1; // plus space separator } else { @@ -463,6 +470,7 @@ bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lP //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTIMEEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) @@ -497,15 +505,16 @@ bool CDXUTIMEEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bReading ) +_Use_decl_annotations_ +void CDXUTIMEEditBox::RenderCandidateReadingWindow( bool bReading ) { RECT rc; UINT nNumEntries = bReading ? 4 : MAX_CANDLIST; - D3DCOLOR TextColor, TextBkColor, SelTextColor, SelBkColor; int nX, nXFirst, nXComp; m_Buffer.CPtoX( m_nCaret, FALSE, &nX ); m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nXFirst ); + DWORD TextColor, TextBkColor, SelTextColor, SelBkColor; if( bReading ) { TextColor = m_ReadingColor; @@ -545,9 +554,9 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe if( *( ImeUi_GetCandidate( i ) ) == L'\0' ) break; SetRect( &rc, 0, 0, 0, 0 ); - m_pDialog->CalcTextRect( ImeUi_GetCandidate( i ), m_Elements.GetAt( 1 ), &rc ); - nWidthRequired = __max( nWidthRequired, rc.right - rc.left ); - nSingleLineHeight = __max( nSingleLineHeight, rc.bottom - rc.top ); + m_pDialog->CalcTextRect( ImeUi_GetCandidate( i ), m_Elements[ 1 ], &rc ); + nWidthRequired = std::max( nWidthRequired, rc.right - rc.left ); + nSingleLineHeight = std::max( nSingleLineHeight, rc.bottom - rc.top ); } nHeightRequired = nSingleLineHeight * nNumEntries; } @@ -556,7 +565,7 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe // Horizontal window SetRect( &rc, 0, 0, 0, 0 ); if( bReading ) - m_pDialog->CalcTextRect( s_wszReadingString, m_Elements.GetAt( 1 ), &rc ); + m_pDialog->CalcTextRect( s_wszReadingString, m_Elements[ 1 ], &rc ); else { @@ -570,19 +579,19 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe break; WCHAR wszEntry[32]; - swprintf_s( wszEntry, 32, L"%s ", ImeUi_GetCandidate( i ) ); + swprintf_s( wszEntry, 32, L"%ls ", ImeUi_GetCandidate( i ) ); // If this is the selected entry, mark its char position. if( ImeUi_GetCandidateSelection() == i ) { - s_CandList.nFirstSelected = lstrlen( wszCand ); - s_CandList.nHoriSelectedLen = lstrlen( wszEntry ) - 1; // Minus space + s_CandList.nFirstSelected = (int)wcslen( wszCand ); + s_CandList.nHoriSelectedLen = (int)wcslen( wszEntry ) - 1; // Minus space } wcscat_s( wszCand, 256, wszEntry ); } - wszCand[lstrlen( wszCand ) - 1] = L'\0'; // Remove the last space + wszCand[wcslen( wszCand ) - 1] = L'\0'; // Remove the last space s_CandList.HoriCand.SetText( wszCand ); - m_pDialog->CalcTextRect( s_CandList.HoriCand.GetBuffer(), m_Elements.GetAt( 1 ), &rc ); + m_pDialog->CalcTextRect( s_CandList.HoriCand.GetBuffer(), m_Elements[ 1 ], &rc ); } nWidthRequired = rc.right - rc.left; nSingleLineHeight = nHeightRequired = rc.bottom - rc.top; @@ -670,12 +679,12 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe if( ImeUi_GetCandidateSelection() == i ) { m_pDialog->DrawRect( &rc, SelBkColor ); - m_Elements.GetAt( 1 )->FontColor.Current = SelTextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( SelTextColor ); } else - m_Elements.GetAt( 1 )->FontColor.Current = TextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( TextColor ); - m_pDialog->DrawText( ImeUi_GetCandidate( i ), m_Elements.GetAt( 1 ), &rc ); + m_pDialog->DrawText( ImeUi_GetCandidate( i ), m_Elements[ 1 ], &rc ); rc.top += nSingleLineHeight; } @@ -683,11 +692,11 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe else { // Horizontal candidate window - m_Elements.GetAt( 1 )->FontColor.Current = TextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( TextColor ); if( bReading ) - m_pDialog->DrawText( s_wszReadingString, m_Elements.GetAt( 1 ), &rc ); + m_pDialog->DrawText( s_wszReadingString, m_Elements[ 1 ], &rc ); else - m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer(), m_Elements.GetAt( 1 ), &rc ); + m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer(), m_Elements[ 1 ], &rc ); // Render the selected entry differently if( !bReading ) @@ -699,16 +708,16 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe rc.right = rc.left + nXRight; rc.left += nXLeft; m_pDialog->DrawRect( &rc, SelBkColor ); - m_Elements.GetAt( 1 )->FontColor.Current = SelTextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( SelTextColor ); m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer() + s_CandList.nFirstSelected, - m_Elements.GetAt( 1 ), &rc, false, s_CandList.nHoriSelectedLen ); + m_Elements[ 1 ], &rc, false ); } } } //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) +void CDXUTIMEEditBox::RenderComposition() { s_CompString.SetText( ImeUi_GetCompositionString() ); @@ -720,7 +729,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) int nX, nXFirst; m_Buffer.CPtoX( m_nCaret, FALSE, &nX ); m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nXFirst ); - CDXUTElement* pElement = m_Elements.GetAt( 1 ); + auto pElement = m_Elements[ 1 ]; // Get the required width RECT rc = @@ -743,10 +752,10 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) s_ptCompString.x = rc.left; s_ptCompString.y = rc.top; - D3DCOLOR TextColor = m_CompColor; + DWORD TextColor = m_CompColor; // Render the window and string. // If the string is too long, we must wrap the line. - pElement->FontColor.Current = TextColor; + pElement->FontColor.SetCurrent( TextColor ); const WCHAR* pwszComp = s_CompString.GetBuffer(); int nCharLeft = s_CompString.GetTextSize(); for(; ; ) @@ -755,7 +764,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) int nLastInLine; int bTrail; s_CompString.XtoCP( m_rcText.right - rc.left, &nLastInLine, &bTrail ); - int nNumCharToDraw = __min( nCharLeft, nLastInLine ); + int nNumCharToDraw = std::min( nCharLeft, nLastInLine ); m_pDialog->CalcTextRect( pwszComp, pElement, &rc, nNumCharToDraw ); // Draw the background @@ -772,7 +781,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) // Not drawing composition string background. We // use the editbox's text color for composition // string text. - TextColor = m_Elements.GetAt( 0 )->FontColor.States[DXUT_STATE_NORMAL]; + TextColor = m_Elements[ 0 ]->FontColor.States[DXUT_STATE_NORMAL]; } } else @@ -782,8 +791,8 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) } // Draw the text - pElement->FontColor.Current = TextColor; - m_pDialog->DrawText( pwszComp, pElement, &rc, false, nNumCharToDraw ); + pElement->FontColor.SetCurrent( TextColor ); + m_pDialog->DrawText( pwszComp, pElement, &rc, false ); // Advance pointer and counter nCharLeft -= nNumCharToDraw; @@ -809,7 +818,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) for( pcComp = s_CompString.GetBuffer(), pAttr = ImeUi_GetCompStringAttr(); *pcComp != L'\0'; ++pcComp, ++pAttr ) { - D3DCOLOR bkColor; + DWORD bkColor; // Render a different background for this character int nXLeft, nXRight; @@ -840,12 +849,12 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) // Set up color based on the character attribute if( *pAttr == ATTR_TARGET_CONVERTED ) { - pElement->FontColor.Current = m_CompTargetColor; + pElement->FontColor.SetCurrent( m_CompTargetColor ); bkColor = m_CompTargetBkColor; } else if( *pAttr == ATTR_TARGET_NOTCONVERTED ) { - pElement->FontColor.Current = m_CompTargetNonColor; + pElement->FontColor.SetCurrent( m_CompTargetNonColor ); bkColor = m_CompTargetNonBkColor; } else @@ -884,22 +893,22 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::RenderIndicator( float fElapsedTime ) +void CDXUTIMEEditBox::RenderIndicator( _In_ float fElapsedTime ) { - CDXUTElement* pElement = m_Elements.GetAt( 9 ); + auto pElement = m_Elements[ 9 ]; pElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); m_pDialog->DrawSprite( pElement, &m_rcIndicator, DXUT_NEAR_BUTTON_DEPTH ); RECT rc = m_rcIndicator; InflateRect( &rc, -m_nSpacing, -m_nSpacing ); - pElement->FontColor.Current = m_IndicatorImeColor; + pElement->FontColor.SetCurrent( m_IndicatorImeColor ); RECT rcCalc = { 0, 0, 0, 0 }; // If IME system is off, draw English indicator. - WCHAR* pwszIndicator = ImeUi_IsEnabled() ? ImeUi_GetIndicatior() : L"En"; + const WCHAR* pwszIndicator = ImeUi_IsEnabled() ? ImeUi_GetIndicatior() : L"En"; m_pDialog->CalcTextRect( pwszIndicator, pElement, &rcCalc ); m_pDialog->DrawText( pwszIndicator, pElement, &rc ); @@ -907,7 +916,7 @@ void CDXUTIMEEditBox::RenderIndicator( float fElapsedTime ) //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::Render( float fElapsedTime ) +void CDXUTIMEEditBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -920,7 +929,7 @@ void CDXUTIMEEditBox::Render( float fElapsedTime ) { 0, 0, 0, 0 }; - m_pDialog->CalcTextRect( L"En", m_Elements.GetAt( 9 ), &rc ); + m_pDialog->CalcTextRect( L"En", m_Elements[ 9 ], &rc ); m_nIndicatorWidth = rc.right - rc.left; // Update the rectangles now that we have the indicator's width @@ -930,7 +939,7 @@ void CDXUTIMEEditBox::Render( float fElapsedTime ) // Let the parent render first (edit control) CDXUTEditBox::Render( fElapsedTime ); - CDXUTElement* pElement = GetElement( 1 ); + auto pElement = GetElement( 1 ); if( pElement ) { s_CompString.SetFontNode( m_pDialog->GetFont( pElement->iFont ) ); @@ -951,35 +960,35 @@ void CDXUTIMEEditBox::Render( float fElapsedTime ) // Display the composition string. // This method should also update s_ptCompString // for RenderCandidateReadingWindow. - RenderComposition( fElapsedTime ); + RenderComposition(); // Display the reading/candidate window. RenderCandidateReadingWindow() // uses s_ptCompString to position itself. s_ptCompString must have // been filled in by RenderComposition(). if( ImeUi_IsShowReadingWindow() ) // Reading window - RenderCandidateReadingWindow( fElapsedTime, true ); + RenderCandidateReadingWindow( true ); else if( ImeUi_IsShowCandListWindow() ) // Candidate list window - RenderCandidateReadingWindow( fElapsedTime, false ); + RenderCandidateReadingWindow( false ); } } //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::SetImeEnableFlag( bool bFlag ) +void CDXUTIMEEditBox::SetImeEnableFlag( _In_ bool bFlag ) { s_bImeFlag = bFlag; } //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::Initialize( HWND hWnd ) +void CDXUTIMEEditBox::Initialize( _In_ HWND hWnd ) { - ImeUiCallback_DrawRect = NULL; + ImeUiCallback_DrawRect = nullptr; ImeUiCallback_Malloc = malloc; ImeUiCallback_Free = free; - ImeUiCallback_DrawFans = NULL; + ImeUiCallback_DrawFans = nullptr; ImeUi_Initialize( hWnd ); diff --git a/FriedLiver/Source/DXUT/Optional/DXUTguiIME.h b/FriedLiver/Source/DXUT/Optional/DXUTguiIME.h index d5a35a5b..aaa9a323 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTguiIME.h +++ b/FriedLiver/Source/DXUT/Optional/DXUTguiIME.h @@ -2,16 +2,16 @@ // File: DXUTguiIME.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_IME_H -#define DXUT_IME_H #include #include #include "ImeUi.h" - //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- @@ -28,37 +28,37 @@ class CDXUTIMEEditBox : public CDXUTEditBox { public: - static HRESULT CreateIMEEditBox( CDXUTDialog* pDialog, int ID, LPCWSTR strText, int x, int y, int width, - int height, bool bIsDefault=false, CDXUTIMEEditBox** ppCreated=NULL ); + static HRESULT CreateIMEEditBox( _In_ CDXUTDialog* pDialog, _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, + _In_ int height, _In_ bool bIsDefault=false, _Outptr_opt_ CDXUTIMEEditBox** ppCreated=nullptr ); - CDXUTIMEEditBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTIMEEditBox(); + CDXUTIMEEditBox( _In_opt_ CDXUTDialog* pDialog = nullptr ) noexcept; + virtual ~CDXUTIMEEditBox(); - static void InitDefaultElements( CDXUTDialog* pDialog ); + static void InitDefaultElements( _In_ CDXUTDialog* pDialog ); - static void WINAPI Initialize( HWND hWnd ); - static void WINAPI Uninitialize(); + static void WINAPI Initialize( _In_ HWND hWnd ); + static void WINAPI Uninitialize(); static HRESULT WINAPI StaticOnCreateDevice(); - static bool WINAPI StaticMsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); + static bool WINAPI StaticMsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); - static void WINAPI SetImeEnableFlag( bool bFlag ); + static void WINAPI SetImeEnableFlag( _In_ bool bFlag ); - virtual void Render( float fElapsedTime ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void UpdateRects(); - virtual void OnFocusIn(); - virtual void OnFocusOut(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void UpdateRects() override; + virtual void OnFocusIn() override; + virtual void OnFocusOut() override; - void PumpMessage(); + void PumpMessage(); - virtual void RenderCandidateReadingWindow( float fElapsedTime, bool bReading ); - virtual void RenderComposition( float fElapsedTime ); - virtual void RenderIndicator( float fElapsedTime ); + virtual void RenderCandidateReadingWindow( _In_ bool bReading ); + virtual void RenderComposition(); + virtual void RenderIndicator( _In_ float fElapsedTime ); protected: - static void WINAPI EnableImeSystem( bool bEnable ); + static void WINAPI EnableImeSystem( _In_ bool bEnable ); static WORD WINAPI GetLanguage() { @@ -68,8 +68,8 @@ class CDXUTIMEEditBox : public CDXUTEditBox { return ImeUi_GetPrimaryLanguage(); } - static void WINAPI SendKey( BYTE nVirtKey ); - static DWORD WINAPI GetImeId( UINT uIndex = 0 ) + static void WINAPI SendKey( _In_ BYTE nVirtKey ); + static DWORD WINAPI GetImeId( _In_ UINT uIndex = 0 ) { return ImeUi_GetImeId( uIndex ); }; @@ -97,6 +97,12 @@ class CDXUTIMEEditBox : public CDXUTEditBox int nFirstSelected; // First character position of the selected string in HoriCand int nHoriSelectedLen; // Length of the selected string in HoriCand RECT rcCandidate; // Candidate rectangle computed and filled each time before rendered + + CCandList() noexcept : + nFirstSelected(0), + nHoriSelectedLen(0), + rcCandidate{} + {} }; static POINT s_ptCompString; // Composition string position. Updated every frame. @@ -108,24 +114,24 @@ class CDXUTIMEEditBox : public CDXUTEditBox static bool s_bImeFlag; // Is ime enabled // Color of various IME elements - D3DCOLOR m_ReadingColor; // Reading string color - D3DCOLOR m_ReadingWinColor; // Reading window color - D3DCOLOR m_ReadingSelColor; // Selected character in reading string - D3DCOLOR m_ReadingSelBkColor; // Background color for selected char in reading str - D3DCOLOR m_CandidateColor; // Candidate string color - D3DCOLOR m_CandidateWinColor; // Candidate window color - D3DCOLOR m_CandidateSelColor; // Selected candidate string color - D3DCOLOR m_CandidateSelBkColor; // Selected candidate background color - D3DCOLOR m_CompColor; // Composition string color - D3DCOLOR m_CompWinColor; // Composition string window color - D3DCOLOR m_CompCaretColor; // Composition string caret color - D3DCOLOR m_CompTargetColor; // Composition string target converted color - D3DCOLOR m_CompTargetBkColor; // Composition string target converted background - D3DCOLOR m_CompTargetNonColor; // Composition string target non-converted color - D3DCOLOR m_CompTargetNonBkColor;// Composition string target non-converted background - D3DCOLOR m_IndicatorImeColor; // Indicator text color for IME - D3DCOLOR m_IndicatorEngColor; // Indicator text color for English - D3DCOLOR m_IndicatorBkColor; // Indicator text background color + DWORD m_ReadingColor; // Reading string color + DWORD m_ReadingWinColor; // Reading window color + DWORD m_ReadingSelColor; // Selected character in reading string + DWORD m_ReadingSelBkColor; // Background color for selected char in reading str + DWORD m_CandidateColor; // Candidate string color + DWORD m_CandidateWinColor; // Candidate window color + DWORD m_CandidateSelColor; // Selected candidate string color + DWORD m_CandidateSelBkColor; // Selected candidate background color + DWORD m_CompColor; // Composition string color + DWORD m_CompWinColor; // Composition string window color + DWORD m_CompCaretColor; // Composition string caret color + DWORD m_CompTargetColor; // Composition string target converted color + DWORD m_CompTargetBkColor; // Composition string target converted background + DWORD m_CompTargetNonColor; // Composition string target non-converted color + DWORD m_CompTargetNonBkColor;// Composition string target non-converted background + DWORD m_IndicatorImeColor; // Indicator text color for IME + DWORD m_IndicatorEngColor; // Indicator text color for English + DWORD m_IndicatorBkColor; // Indicator text background color // Edit-control-specific data int m_nIndicatorWidth; // Width of the indicator symbol @@ -135,7 +141,3 @@ class CDXUTIMEEditBox : public CDXUTEditBox static bool m_bIMEStaticMsgProcCalled; #endif }; - - - -#endif // DXUT_IME_H diff --git a/FriedLiver/Source/DXUT/Optional/DXUTres.cpp b/FriedLiver/Source/DXUT/Optional/DXUTres.cpp index 95bc43ac..9b00bd14 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTres.cpp +++ b/FriedLiver/Source/DXUT/Optional/DXUTres.cpp @@ -1,11 +1,16 @@ //---------------------------------------------------------------------------- // File: DXUTRes.cpp // -// Copyright (c) Microsoft Corp. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //----------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTres.h" +#include "DDSTextureLoader.h" + static const DWORD g_DXUTGUITextureSrcData[] = { 0x20534444, 0x0000007c, 0x00001007, 0x00000100, 0x00000100, 0x00000000, 0x00000000, 0x00000000, @@ -8283,57 +8288,24 @@ static const DWORD g_DXUTArrowMeshSrcData[] = static const UINT g_DXUTArrowMeshSrcDataSizeInBytes = 2193; -//----------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray9( LPDIRECT3DDEVICE9 pd3dDevice, IDirect3DTexture9** ppTexture, D3DXIMAGE_INFO* pInfo ) -{ - return D3DXCreateTextureFromFileInMemoryEx( pd3dDevice, g_DXUTGUITextureSrcData, g_DXUTGUITextureSrcDataSizeInBytes, - D3DX_DEFAULT, D3DX_DEFAULT, 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, pInfo, NULL, ppTexture ); -} - //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray11(ID3D11Device* pd3dDevice, ID3D11Texture2D** ppTexture, D3DX11_IMAGE_INFO* pInfo) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateGUITextureFromInternalArray(ID3D11Device* pd3dDevice, ID3D11Texture2D** ppTexture) { - HRESULT hr; - - D3DX11_IMAGE_INFO SrcInfo; - if( !pInfo ) - { - D3DX11GetImageInfoFromMemory( g_DXUTGUITextureSrcData, g_DXUTGUITextureSrcDataSizeInBytes, NULL, &SrcInfo, NULL ); - pInfo = &SrcInfo; - } - - ID3D11Resource *pRes; - D3DX11_IMAGE_LOAD_INFO loadInfo; - loadInfo.Width = D3DX11_DEFAULT; - loadInfo.Height = D3DX11_DEFAULT; - loadInfo.Depth = D3DX11_DEFAULT; - loadInfo.FirstMipLevel = 0; - loadInfo.MipLevels = 1; - loadInfo.Usage = D3D11_USAGE_DEFAULT; - loadInfo.BindFlags = D3D11_BIND_SHADER_RESOURCE; - loadInfo.CpuAccessFlags = 0; - loadInfo.MiscFlags = 0; - //loadInfo.Format = MAKE_TYPELESS( pInfo->Format ); - loadInfo.Format = MAKE_SRGB( pInfo->Format ); - loadInfo.Filter = D3DX11_FILTER_NONE; - loadInfo.MipFilter = D3DX11_FILTER_NONE; - loadInfo.pSrcInfo = pInfo; + if ( !ppTexture ) + return E_INVALIDARG; - hr = D3DX11CreateTextureFromMemory( pd3dDevice, g_DXUTGUITextureSrcData, g_DXUTGUITextureSrcDataSizeInBytes, &loadInfo, NULL, &pRes, NULL ); - if( FAILED( hr ) ) + ID3D11Resource *pRes = nullptr; + HRESULT hr = DirectX::CreateDDSTextureFromMemory( pd3dDevice, + reinterpret_cast(g_DXUTGUITextureSrcData), g_DXUTGUITextureSrcDataSizeInBytes, + &pRes, nullptr ); + if ( FAILED(hr) ) return hr; + DXUT_SetDebugName( pRes, "DXUT" ); + hr = pRes->QueryInterface( __uuidof( ID3D11Texture2D ), (LPVOID*)ppTexture ); SAFE_RELEASE( pRes ); - return S_OK; + return hr; } - -//----------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateArrowMeshFromInternalArray( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh** ppMesh ) -{ - return D3DXLoadMeshFromXInMemory( g_DXUTArrowMeshSrcData, g_DXUTArrowMeshSrcDataSizeInBytes, - D3DXMESH_MANAGED, pd3dDevice, NULL, NULL, NULL, NULL, ppMesh ); -} - diff --git a/FriedLiver/Source/DXUT/Optional/DXUTres.h b/FriedLiver/Source/DXUT/Optional/DXUTres.h index beab017d..3259f67b 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTres.h +++ b/FriedLiver/Source/DXUT/Optional/DXUTres.h @@ -3,16 +3,11 @@ // // Functions to create DXUT media from arrays in memory // -// Copyright (c) Microsoft Corp. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //----------------------------------------------------------------------------- #pragma once -#ifndef DXUT_RES_H -#define DXUT_RES_H - -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray9( LPDIRECT3DDEVICE9 pd3dDevice, IDirect3DTexture9** ppTexture, - D3DXIMAGE_INFO* pInfo ); -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray11( ID3D11Device* pd3dDevice, ID3D11Texture2D** ppTexture, - D3DX11_IMAGE_INFO* pInfo ); -HRESULT WINAPI DXUTCreateArrowMeshFromInternalArray( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh** ppMesh ); -#endif +HRESULT WINAPI DXUTCreateGUITextureFromInternalArray( _In_ ID3D11Device* pd3dDevice, _Outptr_ ID3D11Texture2D** ppTexture ); diff --git a/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.cpp b/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.cpp index 334fa26b..d438b361 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.cpp +++ b/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.cpp @@ -3,24 +3,21 @@ // // Dialog for selection of device settings // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTgui.h" #include "DXUTsettingsDlg.h" -#undef min // use __min instead -#undef max // use __max instead - //-------------------------------------------------------------------------------------- // Internal functions forward declarations //-------------------------------------------------------------------------------------- -WCHAR* DXUTAPIVersionToString( DXUTDeviceVersion version ); -WCHAR* DXUTPresentIntervalToString( UINT pi ); -WCHAR* DXUTMultisampleTypeToString( D3DMULTISAMPLE_TYPE MultiSampleType ); -WCHAR* DXUTD3DDeviceTypeToString( D3DDEVTYPE devType ); -WCHAR* DXUTD3DX11DeviceTypeToString( D3D_DRIVER_TYPE devType ); -WCHAR* DXUTVertexProcessingTypeToString( DWORD vpt ); +const WCHAR* DXUTPresentIntervalToString( _In_ UINT pi ); +const WCHAR* DXUTDeviceTypeToString( _In_ D3D_DRIVER_TYPE devType ); +const WCHAR* DXUTVertexProcessingTypeToString( _In_ DWORD vpt ); HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL = D3D_FEATURE_LEVEL(0) ); @@ -39,19 +36,28 @@ CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog() //-------------------------------------------------------------------------------------- -CD3DSettingsDlg::CD3DSettingsDlg() +CD3DSettingsDlg::CD3DSettingsDlg() noexcept : + m_pActiveDialog(nullptr), + m_Dialog{}, + m_nRevertModeTimeout(0), + m_nIDEvent(0), + m_bActive( false ), + m_Levels{} { - m_pStateBlock = NULL; - m_bActive = false; - m_pActiveDialog = NULL; - m_Levels[0] = D3D_FEATURE_LEVEL_9_1; m_Levels[1] = D3D_FEATURE_LEVEL_9_2; m_Levels[2] = D3D_FEATURE_LEVEL_9_3; m_Levels[3] = D3D_FEATURE_LEVEL_10_0; m_Levels[4] = D3D_FEATURE_LEVEL_10_1; m_Levels[5] = D3D_FEATURE_LEVEL_11_0; - + m_Levels[6] = D3D_FEATURE_LEVEL_11_1; +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + m_Levels[7] = D3D_FEATURE_LEVEL_12_0; + m_Levels[8] = D3D_FEATURE_LEVEL_12_1; +#else + m_Levels[7] = static_cast(0xc000); + m_Levels[8] = static_cast(0xc100); +#endif } @@ -59,18 +65,18 @@ CD3DSettingsDlg::CD3DSettingsDlg() CD3DSettingsDlg::~CD3DSettingsDlg() { // Release the memory used to hold the D3D11 refresh data in the combo box - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); if( pComboBox ) for( UINT i = 0; i < pComboBox->GetNumItems(); ++i ) { - DXGI_RATIONAL* pRate = reinterpret_cast( pComboBox->GetItemData( i ) ); + auto pRate = reinterpret_cast( pComboBox->GetItemData( i ) ); delete pRate; } } //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager ) +void CD3DSettingsDlg::Init( _In_ CDXUTDialogResourceManager* pManager ) { assert( pManager ); m_Dialog.Init( pManager, false ); // Don't register this dialog. @@ -80,6 +86,7 @@ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager ) } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager, LPCWSTR szControlTextureFileName ) { assert( pManager ); @@ -91,6 +98,7 @@ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager, LPCWSTR szCont //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager, LPCWSTR pszControlTextureResourcename, HMODULE hModule ) { @@ -111,89 +119,44 @@ void CD3DSettingsDlg::CreateControls() m_Dialog.SetFont( 1, L"Arial", 28, FW_BOLD ); // Right-justify static controls - CDXUTElement* pElement = m_Dialog.GetDefaultElement( DXUT_CONTROL_STATIC, 0 ); + auto pElement = m_Dialog.GetDefaultElement( DXUT_CONTROL_STATIC, 0 ); if( pElement ) { pElement->dwTextFormat = DT_VCENTER | DT_RIGHT; // Title - CDXUTStatic* pStatic = NULL; + CDXUTStatic* pStatic = nullptr; m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Direct3D Settings", 10, 5, 400, 50, false, &pStatic ); pElement = pStatic->GetElement( 0 ); pElement->iFont = 1; pElement->dwTextFormat = DT_TOP | DT_LEFT; } - // DXUTSETTINGSDLG_API_VERSION - m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"API Version", 10, 35, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_API_VERSION, 200, 35, 300, 23 ); - - //DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL, L"Feature Level", 10, 60, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL, 200, 60, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL, 200, 60, 400, 23 ); m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL )->SetDropHeight( 106 ); - // DXUTSETTINGSDLG_ADAPTER m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Display Adapter", 10, 85, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_ADAPTER, 200, 85, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_ADAPTER, 200, 85, 400, 23 ); // DXUTSETTINGSDLG_DEVICE_TYPE m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Render Device", 10, 110, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_DEVICE_TYPE, 200, 110, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_DEVICE_TYPE, 200, 110, 400, 23 ); // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN - m_Dialog.AddCheckBox( DXUTSETTINGSDLG_DEVICECLIP, L"Clip to device when window spans across multiple monitors", - 250, 136, 500, 16 ); m_Dialog.AddRadioButton( DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_WINDOWED_GROUP, L"Windowed", 360, 157, 100, 16 ); m_Dialog.AddRadioButton( DXUTSETTINGSDLG_FULLSCREEN, DXUTSETTINGSDLG_WINDOWED_GROUP, L"Full Screen", 220, 157, 100, 16 ); - // DXUTSETTINGSDLG_ADAPTER_FORMAT - m_Dialog.AddStatic( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL, L"Adapter Format", 10, 175, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT, 200, 175, 300, 23 ); - - // DXUTSETTINGSDLG_RESOLUTION - m_Dialog.AddStatic( DXUTSETTINGSDLG_RESOLUTION_LABEL, L"Resolution", 10, 200, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_RESOLUTION, 200, 200, 200, 23 ); - m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION )->SetDropHeight( 106 ); - // DXUTSETTINGSDLG_RES_SHOW_ALL m_Dialog.AddCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL, L"Show All Aspect Ratios", 420, 200, 200, 23, false ); - // DXUTSETTINGSDLG_REFRESH_RATE - m_Dialog.AddStatic( DXUTSETTINGSDLG_REFRESH_RATE_LABEL, L"Refresh Rate", 10, 225, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_REFRESH_RATE, 200, 225, 300, 23 ); - - // DXUTSETTINGSDLG_BACK_BUFFER_FORMAT - m_Dialog.AddStatic( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL, L"Back Buffer Format", 10, 260, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT, 200, 260, 300, 23 ); - - // DXUTSETTINGSDLG_DEPTH_STENCIL - m_Dialog.AddStatic( DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL, L"Depth/Stencil Format", 10, 285, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL, 200, 285, 300, 23 ); - - // DXUTSETTINGSDLG_MULTISAMPLE_TYPE - m_Dialog.AddStatic( DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL, L"Multisample Type", 10, 310, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE, 200, 310, 300, 23 ); - - // DXUTSETTINGSDLG_MULTISAMPLE_QUALITY - m_Dialog.AddStatic( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL, L"Multisample Quality", 10, 335, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY, 200, 335, 300, 23 ); - - // DXUTSETTINGSDLG_VERTEX_PROCESSING - m_Dialog.AddStatic( DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL, L"Vertex Processing", 10, 360, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING, 200, 360, 300, 23 ); - - // DXUTSETTINGSDLG_PRESENT_INTERVAL - m_Dialog.AddStatic( DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL, L"Vertical Sync", 10, 385, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL, 200, 385, 300, 23 ); - // DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL, L"Adapter Output", 10, 175, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, 200, 175, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, 200, 175, 400, 23 ); // DXUTSETTINGSDLG_D3D11_RESOLUTION m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL, L"Resolution", 10, 200, 180, 23 ); @@ -202,23 +165,30 @@ void CD3DSettingsDlg::CreateControls() // DXUTSETTINGSDLG_D3D11_REFRESH_RATE m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL, L"Refresh Rate", 10, 225, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE, 200, 225, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE, 200, 225, 400, 23 ); // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL, L"Back Buffer Format", 10, 260, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT, 200, 260, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT, 200, 260, 400, 23 ); // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL, L"Multisample Count", 10, 285, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT, 200, 285, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT, 200, 285, 400, 23 ); // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL, L"Multisample Quality", 10, 310, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY, 200, 310, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY, 200, 310, 400, 23 ); // DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL, L"Vertical Sync", 10, 335, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL, 200, 335, 300, 23 ); + m_Dialog.AddComboBox(DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL, 200, 335, 400, 23); + + auto pPresentIntervalComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL); + if (pPresentIntervalComboBox) + { + pPresentIntervalComboBox->AddItem(L"On", ULongToPtr(1)); + pPresentIntervalComboBox->AddItem(L"Off", ULongToPtr(0)); + } // DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE m_Dialog.AddCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE, L"Create Debug Device", 200, 365, 180, 23 ); @@ -239,17 +209,17 @@ void CD3DSettingsDlg::CreateControls() pElement->dwTextFormat = DT_VCENTER | DT_RIGHT; // Title - CDXUTStatic* pStatic = NULL; - m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Do you want to keep these display settings?", 10, 5, - 640, 50, false, &pStatic ); - pElement = pStatic->GetElement( 0 ); + CDXUTStatic* pStatic = nullptr; + if ( SUCCEEDED(m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Do you want to keep these display settings?", 10, 5, + 640, 50, false, &pStatic ) ) ) + pElement = pStatic->GetElement( 0 ); pElement->iFont = 1; pElement->dwTextFormat = DT_TOP | DT_LEFT; // Timeout static text control - m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT, L"", 10, 90, 640, 30, - false, &pStatic ); - pElement = pStatic->GetElement( 0 ); + if ( SUCCEEDED(m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT, L"", 10, 90, 640, 30, + false, &pStatic ) ) ) + pElement = pStatic->GetElement( 0 ); pElement->iFont = 0; pElement->dwTextFormat = DT_TOP | DT_LEFT; } @@ -261,224 +231,180 @@ void CD3DSettingsDlg::CreateControls() //-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ) +// Changes the UI defaults to the current device settings +//-------------------------------------------------------------------------------------- +HRESULT CD3DSettingsDlg::Refresh() { - if( pd3dDevice == NULL ) - return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", E_INVALIDARG ); + g_DeviceSettings = DXUTGetDeviceSettings(); - // Create the fonts/textures - m_Dialog.SetCallback( StaticOnEvent, ( void* )this ); - m_RevertModeDialog.SetCallback( StaticOnEvent, ( void* )this ); + auto pD3DEnum = DXUTGetD3D11Enumeration(); - return S_OK; -} + // Fill the UI with the current settings + AddD3D11DeviceType( g_DeviceSettings.d3d11.DriverType ); + m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, true ); + m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_FULLSCREEN, (g_DeviceSettings.d3d11.DriverType != D3D_DRIVER_TYPE_WARP) ); -//-------------------------------------------------------------------------------------- -// Changes the UI defaults to the current device settings -//-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::Refresh() -{ - HRESULT hr = S_OK; + SetWindowed( FALSE != g_DeviceSettings.d3d11.sd.Windowed ); + auto pOutputInfo = GetCurrentD3D11OutputInfo(); + AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, g_DeviceSettings.d3d11.Output ); + + AddD3D11Resolution( g_DeviceSettings.d3d11.sd.BufferDesc.Width, + g_DeviceSettings.d3d11.sd.BufferDesc.Height ); + AddD3D11RefreshRate( g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate ); + AddD3D11BackBufferFormat( g_DeviceSettings.d3d11.sd.BufferDesc.Format ); + AddD3D11MultisampleCount( g_DeviceSettings.d3d11.sd.SampleDesc.Count ); + AddD3D11MultisampleQuality( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ); + + auto pBestDeviceSettingsCombo = pD3DEnum->GetDeviceSettingsCombo( + g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.sd.BufferDesc.Format, + ( g_DeviceSettings.d3d11.sd.Windowed != 0 ) ); - g_DeviceSettings = DXUTGetDeviceSettings(); + if( !pBestDeviceSettingsCombo ) + return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); - CDXUTComboBox* pAPIComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_API_VERSION ); - pAPIComboBox->RemoveAllItems(); - if( DXUTDoesAppSupportD3D9() ) - { - // Ensure that at least one adapter got enumerated. - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - if( pD3DEnum->GetAdapterInfoList()->GetSize() > 0 ) - AddAPIVersion( DXUT_D3D9_DEVICE ); - } - if( DXUTDoesAppSupportD3D11() && DXUTIsD3D11Available() ) - { - // Ensure that at least one adapter got enumerated. - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - if( pD3DEnum->GetAdapterInfoList()->GetSize() > 0 ) - AddAPIVersion( DXUT_D3D11_DEVICE ); - } + CDXUTComboBox *pFeatureLevelBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); + pFeatureLevelBox->RemoveAllItems(); - // If no API has been added, something has gone wrong. Exit the dialog. - if( pAPIComboBox->GetNumItems() == 0 ) + D3D_FEATURE_LEVEL clampFL; + if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + clampFL = DXUTGetD3D11Enumeration()->GetWARPFeaturevel(); + else if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) + clampFL = DXUTGetD3D11Enumeration()->GetREFFeaturevel(); + else + clampFL = pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel; + + for (int fli = 0; fli < TOTAL_FEATURE_LEVELS; fli++) { - SetActive( false ); - return S_OK; - } + if (m_Levels[fli] >= g_DeviceSettings.MinimumFeatureLevel + && m_Levels[fli] <= clampFL) + { + AddD3D11FeatureLevel( m_Levels[fli] ); + } + } + pFeatureLevelBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DeviceFeatureLevel ) ); + + // Get the adapters list from CD3D11Enumeration object + auto pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); + + if( pAdapterInfoList->empty() ) + return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", DXUTERR_NOCOMPATIBLEDEVICES ); - pAPIComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.ver ) ); + auto pAdapterCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + pAdapterCombo->RemoveAllItems(); - switch( g_DeviceSettings.ver ) + // Add adapters + for( auto it = pAdapterInfoList->cbegin(); it != pAdapterInfoList->cend(); ++it ) { - case DXUT_D3D9_DEVICE: - { - // Show all D3D9-specific controls and hide controls for all other D3D versions. - ShowControlSet( DXUT_D3D9_DEVICE ); - - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - - // Fill the UI with the current settings - AddDeviceType( g_DeviceSettings.d3d9.DeviceType ); - SetWindowed( FALSE != g_DeviceSettings.d3d9.pp.Windowed ); - SetDeviceClip( 0 != ( g_DeviceSettings.d3d9.pp.Flags & D3DPRESENTFLAG_DEVICECLIP ) ); - AddAdapterFormat( g_DeviceSettings.d3d9.AdapterFormat ); - AddResolution( g_DeviceSettings.d3d9.pp.BackBufferWidth, g_DeviceSettings.d3d9.pp.BackBufferHeight ); - AddRefreshRate( g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz ); - AddBackBufferFormat( g_DeviceSettings.d3d9.pp.BackBufferFormat ); - AddDepthStencilBufferFormat( g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat ); - AddMultisampleType( g_DeviceSettings.d3d9.pp.MultiSampleType ); - AddMultisampleQuality( g_DeviceSettings.d3d9.pp.MultiSampleQuality ); - - if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_PUREDEVICE ) - AddVertexProcessingType( D3DCREATE_PUREDEVICE ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING ) - AddVertexProcessingType( D3DCREATE_HARDWARE_VERTEXPROCESSING ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING ) - AddVertexProcessingType( D3DCREATE_SOFTWARE_VERTEXPROCESSING ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING ) - AddVertexProcessingType( D3DCREATE_MIXED_VERTEXPROCESSING ); - - CD3D9EnumDeviceSettingsCombo* pBestDeviceSettingsCombo = pD3DEnum->GetDeviceSettingsCombo( - g_DeviceSettings.d3d9.AdapterOrdinal, g_DeviceSettings.d3d9.DeviceType, - g_DeviceSettings.d3d9.AdapterFormat, g_DeviceSettings.d3d9.pp.BackBufferFormat, - ( g_DeviceSettings.d3d9.pp.Windowed != 0 ) ); - if( NULL == pBestDeviceSettingsCombo ) - return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); - - // Get the adapters list from CD3D9Enumeration object - CGrowableArray * pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - - if( pAdapterInfoList->GetSize() == 0 ) - return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", DXUTERR_NOCOMPATIBLEDEVICES ); - - CDXUTComboBox* pAdapterCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterCombo->RemoveAllItems(); - - // Add adapters - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); iAdapter++ ) - { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } + AddAdapter( (*it)->szUniqueDescription, (*it)->AdapterOrdinal ); + } - pAdapterCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.AdapterOrdinal ) ); + pAdapterCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - hr = OnAPIVersionChanged( true ); - if( FAILED( hr ) ) - return hr; + // DXUTSETTINGSDLG_D3D11_RESOLUTION + HRESULT hr = UpdateD3D11Resolutions(); + if ( FAILED(hr) ) + return hr; - //m_Dialog.Refresh(); - CDXUTDialog::SetRefreshTime( ( float )DXUTGetTime() ); - break; - } - case DXUT_D3D11_DEVICE: - { - // Show all D3D11-specific controls and hide controls for all other D3D versions. - ShowControlSet( DXUT_D3D11_DEVICE ); + // DXUTSETTINGSDLG_D3D11_REFRESH_RATE + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + // Windowed mode + bool bWindowed = IsWindowed(); - // Fill the UI with the current settings - AddD3D11DeviceType( g_DeviceSettings.d3d11.DriverType ); - SetWindowed( FALSE != g_DeviceSettings.d3d11.sd.Windowed ); - CD3D11EnumOutputInfo* pOutputInfo = GetCurrentD3D11OutputInfo(); - AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, g_DeviceSettings.d3d11.Output ); - + // Backbuffer Format/Driver Type + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if (pAdapterInfo) + { + auto pBackBufferFormatComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT); + pBackBufferFormatComboBox->RemoveAllItems(); + for (size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++) + { + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[idc]; + if ((pDeviceCombo->Windowed == TRUE) == bWindowed) + { + AddD3D11BackBufferFormat(pDeviceCombo->BackBufferFormat); + } + } - AddD3D11Resolution( g_DeviceSettings.d3d11.sd.BufferDesc.Width, - g_DeviceSettings.d3d11.sd.BufferDesc.Height ); - AddD3D11RefreshRate( g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate ); - AddD3D11BackBufferFormat( g_DeviceSettings.d3d11.sd.BufferDesc.Format ); - AddD3D11MultisampleCount( g_DeviceSettings.d3d11.sd.SampleDesc.Count ); - AddD3D11MultisampleQuality( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ); + pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.sd.BufferDesc.Format) ); - CD3D11EnumDeviceSettingsCombo* pBestDeviceSettingsCombo = pD3DEnum->GetDeviceSettingsCombo( - g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.DriverType, - g_DeviceSettings.d3d11.Output, g_DeviceSettings.d3d11.sd.BufferDesc.Format, - ( g_DeviceSettings.d3d11.sd.Windowed != 0 ) ); + auto pDeviceTypeComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_DEVICE_TYPE); + pDeviceTypeComboBox->RemoveAllItems(); - if( NULL == pBestDeviceSettingsCombo ) - return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); + for (size_t iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.size(); iDeviceInfo++) + { + auto pDeviceInfo = pAdapterInfo->deviceInfoList[iDeviceInfo]; + AddD3D11DeviceType(pDeviceInfo->DeviceType); + } - CDXUTComboBox *pFeatureLevelBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); - pFeatureLevelBox->RemoveAllItems(); - for (int fli = 0; fli < TOTAL_FEATURE_LEVLES; fli++) { - if (m_Levels[fli] >= g_DeviceSettings.MinimumFeatureLevel - && m_Levels[fli] <=pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel) { - AddD3D11FeatureLevel( m_Levels[fli] ); - } - } - pFeatureLevelBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DeviceFeatureLevel ) ); + pDeviceTypeComboBox->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.DriverType) ); + } - - // Get the adapters list from CD3D11Enumeration object - CGrowableArray * pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); + // MSAA settings + auto pDeviceSettingsCombo = GetCurrentD3D11DeviceSettingsCombo(); + if ( pDeviceSettingsCombo ) + { + auto pMultisampleCountCombo = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT); + pMultisampleCountCombo->RemoveAllItems(); - if( pAdapterInfoList->GetSize() == 0 ) - return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", DXUTERR_NOCOMPATIBLEDEVICES ); + for (auto it = pDeviceSettingsCombo->multiSampleCountList.cbegin(); it != pDeviceSettingsCombo->multiSampleCountList.cend(); ++it) + AddD3D11MultisampleCount(*it); - CDXUTComboBox* pAdapterCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterCombo->RemoveAllItems(); + pMultisampleCountCombo->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.sd.SampleDesc.Count) ); - // Add adapters - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); iAdapter++ ) + UINT MaxQuality = 0; + for (size_t iCount = 0; iCount < pDeviceSettingsCombo->multiSampleCountList.size(); iCount++) + { + UINT Count = pDeviceSettingsCombo->multiSampleCountList[iCount]; + if ( Count == g_DeviceSettings.d3d11.sd.SampleDesc.Count ) { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); + MaxQuality = pDeviceSettingsCombo->multiSampleQualityList[iCount]; + break; } + } - pAdapterCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - - hr = OnAPIVersionChanged( true ); - if( FAILED( hr ) ) - return hr; + auto pMultisampleQualityCombo = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY); + pMultisampleQualityCombo->RemoveAllItems(); - //m_Dialog.Refresh(); - CDXUTDialog::SetRefreshTime( ( float )DXUTGetTime() ); - break; + for (UINT iQuality = 0; iQuality < MaxQuality; iQuality++) + { + AddD3D11MultisampleQuality(iQuality); } - } - - return S_OK; -} + pMultisampleQualityCombo->SetSelectedByData(ULongToPtr(g_DeviceSettings.d3d11.sd.SampleDesc.Quality)); + } -//-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D9ResetDevice() -{ - const D3DSURFACE_DESC* pDesc = DXUTGetD3D9BackBufferSurfaceDesc(); - m_Dialog.SetLocation( 0, 0 ); - m_Dialog.SetSize( pDesc->Width, pDesc->Height ); - m_Dialog.SetBackgroundColors( D3DCOLOR_ARGB( 255, 98, 138, 206 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 10, 73, 179 ) ); + // Misc settings + auto pDebugCheckBox = m_Dialog.GetCheckBox(DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE); + if ( pDebugCheckBox ) + { + pDebugCheckBox->SetChecked(0 != (g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG)); + } - m_RevertModeDialog.SetLocation( 0, 0 ); - m_RevertModeDialog.SetSize( pDesc->Width, pDesc->Height ); - m_RevertModeDialog.SetBackgroundColors( D3DCOLOR_ARGB( 255, 98, 138, 206 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 10, 73, 179 ) ); + auto pPresentIntervalComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL); + if ( pPresentIntervalComboBox ) + { + pPresentIntervalComboBox->SetSelectedByData(ULongToPtr(g_DeviceSettings.d3d11.SyncInterval) ); + } - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - pd3dDevice->BeginStateBlock(); - pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); - pd3dDevice->EndStateBlock( &m_pStateBlock ); + CDXUTDialog::SetRefreshTime( ( float )DXUTGetTime() ); return S_OK; } + //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::SetSelectedD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) +void CD3DSettingsDlg::SetSelectedD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ) { - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + auto pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); for( UINT i = 0; i < pRefreshRateComboBox->GetNumItems(); ++i ) { - DXGI_RATIONAL* pRate = ( DXGI_RATIONAL* )pRefreshRateComboBox->GetItemData( i ); + auto pRate = reinterpret_cast( pRefreshRateComboBox->GetItemData( i ) ); if( pRate && pRate->Numerator == RefreshRate.Numerator && pRate->Denominator == RefreshRate.Denominator ) { @@ -489,38 +415,7 @@ void CD3DSettingsDlg::SetSelectedD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) } //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnRender( float fElapsedTime ) -{ - if( DXUTGetD3D11Device() ) - OnRender11( fElapsedTime ); - else - OnRender9( fElapsedTime ); -} - - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnRender9( float fElapsedTime ) -{ - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - - // Clear the render target and the zbuffer - pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0x00003F3F, 1.0f, 0 ); - - // Render the scene - if( SUCCEEDED( pd3dDevice->BeginScene() ) ) - { - m_pStateBlock->Capture(); - pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); - m_pActiveDialog->OnRender( fElapsedTime ); - m_pStateBlock->Apply(); - pd3dDevice->EndScene(); - } -} - - - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnRender11( float fElapsedTime ) +void CD3DSettingsDlg::OnRender( _In_ float fElapsedTime ) { // Render the scene m_pActiveDialog->OnRender( fElapsedTime ); @@ -528,6 +423,7 @@ void CD3DSettingsDlg::OnRender11( float fElapsedTime ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CD3DSettingsDlg::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { m_pActiveDialog->MsgProc( hWnd, uMsg, wParam, lParam ); @@ -536,27 +432,10 @@ LRESULT CD3DSettingsDlg::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lP return 0; } - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnD3D9LostDevice() -{ - SAFE_RELEASE( m_pStateBlock ); -} - - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnD3D9DestroyDevice() -{ -} - - - //-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D11CreateDevice( ID3D11Device* pd3dDevice ) +HRESULT CD3DSettingsDlg::OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice ) { - //HRESULT hr; - - if( pd3dDevice == NULL ) + if( !pd3dDevice ) return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", E_INVALIDARG ); // Create the fonts/textures @@ -568,9 +447,11 @@ HRESULT CD3DSettingsDlg::OnD3D11CreateDevice( ID3D11Device* pd3dDevice ) //-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) +_Use_decl_annotations_ +HRESULT CD3DSettingsDlg::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) { + UNREFERENCED_PARAMETER(pd3dDevice); + m_Dialog.SetLocation( 0, 0 ); m_Dialog.SetSize( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); m_Dialog.SetBackgroundColors( D3DCOLOR_ARGB( 255, 98, 138, 206 ), @@ -596,101 +477,13 @@ void CD3DSettingsDlg::OnD3D11DestroyDevice() } -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::ShowControlSet( DXUTDeviceVersion ver ) -{ - switch( ver ) - { - case DXUT_D3D9_DEVICE: - - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEVICECLIP )->SetVisible( true ); - - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE )->SetVisible( false ); - - break; - - case DXUT_D3D11_DEVICE: - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEVICECLIP )->SetVisible( false ); - - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE )->SetVisible( true ); - break; - } -} - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI CD3DSettingsDlg::StaticOnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserData ) { - CD3DSettingsDlg* pD3DSettings = ( CD3DSettingsDlg* )pUserData; + auto pD3DSettings = reinterpret_cast( pUserData ); if( pD3DSettings ) pD3DSettings->OnEvent( nEvent, nControlID, pControl ); } @@ -700,26 +493,34 @@ void WINAPI CD3DSettingsDlg::StaticOnEvent( UINT nEvent, int nControlID, // Desc: Timer callback registered by a call to DXUTSetTimer. It is called each second // until mode change timeout limit. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI CD3DSettingsDlg::StaticOnModeChangeTimer( UINT nIDEvent, void* pUserContext ) { - CD3DSettingsDlg* pD3DSettings = ( CD3DSettingsDlg* )pUserContext; + UNREFERENCED_PARAMETER(nIDEvent); + + auto pD3DSettings = reinterpret_cast( pUserContext ); assert( pD3DSettings ); + _Analysis_assume_( pD3DSettings ); assert( pD3DSettings->m_pActiveDialog == &pD3DSettings->m_RevertModeDialog ); assert( pD3DSettings->m_nIDEvent == nIDEvent ); if( 0 == --pD3DSettings->m_nRevertModeTimeout ) { - CDXUTControl* pControl = pD3DSettings->m_RevertModeDialog.GetControl( DXUTSETTINGSDLG_MODE_CHANGE_REVERT ); + auto pControl = pD3DSettings->m_RevertModeDialog.GetControl( DXUTSETTINGSDLG_MODE_CHANGE_REVERT ); assert( pControl ); + _Analysis_assume_( pControl ); pD3DSettings->m_RevertModeDialog.SendEvent( EVENT_BUTTON_CLICKED, false, pControl ); } pD3DSettings->UpdateModeChangeTimeoutText( pD3DSettings->m_nRevertModeTimeout ); } //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, - CDXUTControl* pControl ) +_Use_decl_annotations_ +void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl ) { + UNREFERENCED_PARAMETER(nEvent); + UNREFERENCED_PARAMETER(pControl); + switch( nControlID ) { case DXUTSETTINGSDLG_ADAPTER: @@ -730,42 +531,10 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, OnWindowedFullScreenChanged(); break; case DXUTSETTINGSDLG_FULLSCREEN: OnWindowedFullScreenChanged(); break; - case DXUTSETTINGSDLG_ADAPTER_FORMAT: - OnAdapterFormatChanged(); break; case DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL: - { - if( g_DeviceSettings.ver == DXUT_D3D9_DEVICE ) - { - OnAdapterFormatChanged(); - } - else - { - OnBackBufferFormatChanged(); - } - break; - } + OnBackBufferFormatChanged(); break; case DXUTSETTINGSDLG_D3D11_RESOLUTION: OnD3D11ResolutionChanged(); break; - case DXUTSETTINGSDLG_RESOLUTION: - OnResolutionChanged(); break; - case DXUTSETTINGSDLG_REFRESH_RATE: - OnRefreshRateChanged(); break; - case DXUTSETTINGSDLG_BACK_BUFFER_FORMAT: - OnBackBufferFormatChanged(); break; - case DXUTSETTINGSDLG_DEPTH_STENCIL: - OnDepthStencilBufferFormatChanged(); break; - case DXUTSETTINGSDLG_MULTISAMPLE_TYPE: - OnMultisampleTypeChanged(); break; - case DXUTSETTINGSDLG_MULTISAMPLE_QUALITY: - OnMultisampleQualityChanged(); break; - case DXUTSETTINGSDLG_VERTEX_PROCESSING: - OnVertexProcessingChanged(); break; - case DXUTSETTINGSDLG_PRESENT_INTERVAL: - OnPresentIntervalChanged(); break; - case DXUTSETTINGSDLG_DEVICECLIP: - OnDeviceClipChanged(); break; - case DXUTSETTINGSDLG_API_VERSION: - OnAPIVersionChanged(); break; case DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL: OnFeatureLevelChanged(); break; case DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT: @@ -786,69 +555,34 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, case DXUTSETTINGSDLG_OK: { bool bFullScreenModeChange = false; - DXUTDeviceSettings currentSettings = DXUTGetDeviceSettings(); + auto currentSettings = DXUTGetDeviceSettings(); g_DeviceSettings.MinimumFeatureLevel = currentSettings.MinimumFeatureLevel; - if( g_DeviceSettings.ver == DXUT_D3D9_DEVICE ) + if( g_DeviceSettings.d3d11.sd.Windowed ) { - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = 0; - - RECT rcClient; - if( DXUTIsWindowed() ) - GetClientRect( DXUTGetHWND(), &rcClient ); - else - rcClient = DXUTGetWindowClientRectAtModeChange(); - DWORD dwWindowWidth = rcClient.right - rcClient.left; - DWORD dwWindowHeight = rcClient.bottom - rcClient.top; - - g_DeviceSettings.d3d9.pp.BackBufferWidth = dwWindowWidth; - g_DeviceSettings.d3d9.pp.BackBufferHeight = dwWindowHeight; - } + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator = + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = 0; + + RECT rcClient; + if( DXUTIsWindowed() ) + GetClientRect( DXUTGetHWND(), &rcClient ); else - { - // Check for fullscreen mode change - bFullScreenModeChange = g_DeviceSettings.d3d9.pp.BackBufferWidth != - currentSettings.d3d9.pp.BackBufferWidth || - g_DeviceSettings.d3d9.pp.BackBufferHeight != currentSettings.d3d9.pp.BackBufferHeight || - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz != - currentSettings.d3d9.pp.FullScreen_RefreshRateInHz; - } + rcClient = DXUTGetWindowClientRectAtModeChange(); + DWORD dwWindowWidth = rcClient.right - rcClient.left; + DWORD dwWindowHeight = rcClient.bottom - rcClient.top; - if( g_DeviceSettings.d3d9.pp.MultiSampleType != D3DMULTISAMPLE_NONE ) - { - g_DeviceSettings.d3d9.pp.Flags &= ~D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; - } + g_DeviceSettings.d3d11.sd.BufferDesc.Width = dwWindowWidth; + g_DeviceSettings.d3d11.sd.BufferDesc.Height = dwWindowHeight; } - else // D3D11 + else { - if( g_DeviceSettings.d3d11.sd.Windowed ) - { - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator = - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = 0; - - RECT rcClient; - if( DXUTIsWindowed() ) - GetClientRect( DXUTGetHWND(), &rcClient ); - else - rcClient = DXUTGetWindowClientRectAtModeChange(); - DWORD dwWindowWidth = rcClient.right - rcClient.left; - DWORD dwWindowHeight = rcClient.bottom - rcClient.top; - - g_DeviceSettings.d3d11.sd.BufferDesc.Width = dwWindowWidth; - g_DeviceSettings.d3d11.sd.BufferDesc.Height = dwWindowHeight; - } - else - { - // Check for fullscreen mode change - bFullScreenModeChange = g_DeviceSettings.d3d11.sd.BufferDesc.Width != - currentSettings.d3d11.sd.BufferDesc.Width || - g_DeviceSettings.d3d11.sd.BufferDesc.Height != currentSettings.d3d11.sd.BufferDesc.Height || - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator != - currentSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator || - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator != - currentSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator; - } + // Check for fullscreen mode change + bFullScreenModeChange = g_DeviceSettings.d3d11.sd.BufferDesc.Width != + currentSettings.d3d11.sd.BufferDesc.Width || + g_DeviceSettings.d3d11.sd.BufferDesc.Height != currentSettings.d3d11.sd.BufferDesc.Height || + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator != + currentSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator || + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator != + currentSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator; } if( bFullScreenModeChange ) @@ -857,20 +591,6 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, // settings. These will get set to the user-defined settings once the // user accepts the mode change DXUTDeviceSettings tSettings = g_DeviceSettings; - if( g_DeviceSettings.ver == DXUT_D3D9_DEVICE ) - { - g_DeviceSettings.d3d9.pp.BackBufferWidth = - currentSettings.d3d9.pp.BackBufferWidth; - g_DeviceSettings.d3d9.pp.BackBufferHeight = - currentSettings.d3d9.pp.BackBufferHeight; - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = - currentSettings.d3d9.pp.FullScreen_RefreshRateInHz; - g_DeviceSettings.d3d9.pp.Windowed = - currentSettings.d3d9.pp.Windowed; - } - else - { - g_DeviceSettings.d3d11.sd.BufferDesc.Width = currentSettings.d3d11.sd.BufferDesc.Width; g_DeviceSettings.d3d11.sd.BufferDesc.Height = @@ -880,8 +600,6 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = currentSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator; g_DeviceSettings.d3d11.sd.Windowed = currentSettings.d3d11.sd.Windowed; - - } // apply the user-defined settings DXUTCreateDeviceFromSettings( &tSettings ); @@ -930,324 +648,154 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, //------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::SetDeviceSettingsFromUI() -{ - CDXUTComboBox* pComboBox; - CDXUTRadioButton* pRadioButton; - - // DXUTSETTINGSDLG_DEVICE_TYPE - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - g_DeviceSettings.d3d9.DeviceType = ( D3DDEVTYPE )PtrToUlong( pComboBox->GetSelectedData() ); - - // DXUTSETTINGSDLG_WINDOWED - pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); - g_DeviceSettings.d3d9.pp.Windowed = pRadioButton->GetChecked(); - - // DXUTSETTINGSDLG_ADAPTER_FORMAT - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - g_DeviceSettings.d3d9.AdapterFormat = ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); - - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - g_DeviceSettings.d3d9.pp.BackBufferFormat = D3DFMT_UNKNOWN; - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = 0; - } - else - { - // DXUTSETTINGSDLG_BACK_BUFFER_FORMAT - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - g_DeviceSettings.d3d9.pp.BackBufferFormat = ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); - - // DXUTSETTINGSDLG_RESOLUTION - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); - DWORD dwResolution = PtrToUlong( pComboBox->GetSelectedData() ); - g_DeviceSettings.d3d9.pp.BackBufferWidth = HIWORD( dwResolution ); - g_DeviceSettings.d3d9.pp.BackBufferHeight = LOWORD( dwResolution ); - - // DXUTSETTINGSDLG_REFRESH_RATE - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = PtrToUlong( pComboBox->GetSelectedData() ); - } - - // DXUTSETTINGSDLG_DEPTH_STENCIL - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat = ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -CD3D9EnumAdapterInfo* CD3DSettingsDlg::GetCurrentAdapterInfo() -{ - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - return pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d9.AdapterOrdinal ); -} - - -//------------------------------------------------------------------------------------- -CD3D9EnumDeviceInfo* CD3DSettingsDlg::GetCurrentDeviceInfo() -{ - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - return pD3DEnum->GetDeviceInfo( g_DeviceSettings.d3d9.AdapterOrdinal, - g_DeviceSettings.d3d9.DeviceType ); -} - -//------------------------------------------------------------------------------------- -CD3D11EnumAdapterInfo* CD3DSettingsDlg::GetCurrentD3D11AdapterInfo() +CD3D11EnumAdapterInfo* CD3DSettingsDlg::GetCurrentD3D11AdapterInfo() const { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d11.AdapterOrdinal ); } //------------------------------------------------------------------------------------- -CD3D11EnumDeviceInfo* CD3DSettingsDlg::GetCurrentD3D11DeviceInfo() +CD3D11EnumDeviceInfo* CD3DSettingsDlg::GetCurrentD3D11DeviceInfo() const { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetDeviceInfo( g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.DriverType ); } //------------------------------------------------------------------------------------- -CD3D11EnumOutputInfo* CD3DSettingsDlg::GetCurrentD3D11OutputInfo() +CD3D11EnumOutputInfo* CD3DSettingsDlg::GetCurrentD3D11OutputInfo() const { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetOutputInfo( g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.Output ); } - -//------------------------------------------------------------------------------------- -CD3D9EnumDeviceSettingsCombo* CD3DSettingsDlg::GetCurrentDeviceSettingsCombo() -{ - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - return pD3DEnum->GetDeviceSettingsCombo( g_DeviceSettings.d3d9.AdapterOrdinal, - g_DeviceSettings.d3d9.DeviceType, - g_DeviceSettings.d3d9.AdapterFormat, - g_DeviceSettings.d3d9.pp.BackBufferFormat, - ( g_DeviceSettings.d3d9.pp.Windowed == TRUE ) ); -} - //------------------------------------------------------------------------------------- -CD3D11EnumDeviceSettingsCombo* CD3DSettingsDlg::GetCurrentD3D11DeviceSettingsCombo() +CD3D11EnumDeviceSettingsCombo* CD3DSettingsDlg::GetCurrentD3D11DeviceSettingsCombo() const { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetDeviceSettingsCombo( g_DeviceSettings.d3d11.AdapterOrdinal, - g_DeviceSettings.d3d11.DriverType, - g_DeviceSettings.d3d11.Output, g_DeviceSettings.d3d11.sd.BufferDesc.Format, ( g_DeviceSettings.d3d11.sd.Windowed == TRUE ) ); } -HRESULT CD3DSettingsDlg::OnD3D11ResolutionChanged () { +HRESULT CD3DSettingsDlg::OnD3D11ResolutionChanged () +{ + if ( g_DeviceSettings.d3d11.sd.Windowed ) + return S_OK; + DWORD dwWidth, dwHeight; GetSelectedD3D11Resolution( &dwWidth, &dwHeight ); - g_DeviceSettings.d3d11.sd.BufferDesc.Width= dwWidth; + g_DeviceSettings.d3d11.sd.BufferDesc.Width = dwWidth; g_DeviceSettings.d3d11.sd.BufferDesc.Height = dwHeight; - + + // DXUTSETTINGSDLG_D3D11_REFRESH_RATE + HRESULT hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; + return S_OK; } -HRESULT CD3DSettingsDlg::OnFeatureLevelChanged () { +HRESULT CD3DSettingsDlg::OnFeatureLevelChanged () +{ HRESULT hr = E_FAIL; - if (g_DeviceSettings.ver == DXUT_D3D11_DEVICE) { - if (g_DeviceSettings.d3d11.DeviceFeatureLevel == GetSelectedFeatureLevel()) return S_OK; - //if( !bRefresh ) - //{ - // Obtain a set of valid D3D10 device settings. - UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; - ZeroMemory( &g_DeviceSettings, sizeof( g_DeviceSettings ) ); - - DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); - g_DeviceSettings.d3d11.CreateFlags = CreateFlags; - g_DeviceSettings.ver = DXUT_D3D11_DEVICE; - //g_DeviceSettings.d3d11.fl = GetSelectedFeatureLevel(); - hr = DXUTSnapDeviceSettingsToEnumDevice(&g_DeviceSettings, true, GetSelectedFeatureLevel()); - - //} - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - CGrowableArray * pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); + if (g_DeviceSettings.d3d11.DeviceFeatureLevel == GetSelectedFeatureLevel()) return S_OK; - CDXUTComboBox* pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterComboBox->RemoveAllItems(); + // Obtain a set of valid D3D11 device settings. + UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; + DXGI_FORMAT BackBufferFormat = g_DeviceSettings.d3d11.sd.BufferDesc.Format; + UINT Count = g_DeviceSettings.d3d11.sd.SampleDesc.Count; + UINT Quality = g_DeviceSettings.d3d11.sd.SampleDesc.Quality; + DXGI_RATIONAL RefreshRate = g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate; + ZeroMemory(&g_DeviceSettings, sizeof(g_DeviceSettings)); - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); ++iAdapter ) - { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } + DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); + g_DeviceSettings.d3d11.CreateFlags = CreateFlags; + hr = DXUTSnapDeviceSettingsToEnumDevice(&g_DeviceSettings, true, GetSelectedFeatureLevel()); + g_DeviceSettings.d3d11.sd.BufferDesc.Format = BackBufferFormat; + g_DeviceSettings.d3d11.sd.SampleDesc.Count = Count; + g_DeviceSettings.d3d11.sd.SampleDesc.Quality = Quality; + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = RefreshRate; - pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); + auto pD3DEnum = DXUTGetD3D11Enumeration(); + auto pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); - pCheckBox->SetChecked( 0 != ( g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG ) ); + // DXUTSETTINGSDLG_ADAPTER + auto pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + pAdapterComboBox->RemoveAllItems(); - hr = OnAdapterChanged(); - if( FAILED( hr ) ) - return hr; + for( auto it = pAdapterInfoList->cbegin(); it != pAdapterInfoList->cend(); ++it ) + { + AddAdapter( (*it)->szUniqueDescription, (*it)->AdapterOrdinal ); } - - return hr; -} -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnAPIVersionChanged( bool bRefresh ) -{ - HRESULT hr; + pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - // Store the API version - g_DeviceSettings.ver = GetSelectedAPIVersion(); + // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT + auto pBackBufferFormatComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT); + pBackBufferFormatComboBox->RemoveAllItems(); + + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if (!pAdapterInfo) + return E_FAIL; - // Show/hide appropriate dialog controls based on version. - ShowControlSet( g_DeviceSettings.ver ); + bool bWindowed = IsWindowed(); - switch( g_DeviceSettings.ver ) + for (size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++) { - case DXUT_D3D9_DEVICE: + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[idc]; + if ((pDeviceCombo->Windowed == TRUE) == bWindowed) { - if( !bRefresh ) - { - // Obtain a set of valid D3D9 device settings. - UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; - ZeroMemory( &g_DeviceSettings, sizeof( g_DeviceSettings ) ); - // We want a specific API version, so set up match option to preserve it. - DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); - g_DeviceSettings.d3d11.CreateFlags = CreateFlags; - g_DeviceSettings.ver = DXUT_D3D9_DEVICE; - DXUTSnapDeviceSettingsToEnumDevice ( &g_DeviceSettings, true); - } - - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - CGrowableArray * pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); + AddD3D11BackBufferFormat(pDeviceCombo->BackBufferFormat); + } + } - CDXUTComboBox* pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterComboBox->RemoveAllItems(); + pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.sd.BufferDesc.Format) ); - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); ++iAdapter ) - { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } + hr = OnBackBufferFormatChanged(); + if (FAILED(hr)) + return hr; - pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.AdapterOrdinal ) ); + auto pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); + pCheckBox->SetChecked( 0 != ( g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG ) ); - hr = OnAdapterChanged(); - if( FAILED( hr ) ) - return hr; - - break; - } - - case DXUT_D3D11_DEVICE: - { - if( !bRefresh ) - { - // Obtain a set of valid D3D10 device settings. - UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; - ZeroMemory( &g_DeviceSettings, sizeof( g_DeviceSettings ) ); - // We want a specific API version, so set up match option to preserve it. - DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); - g_DeviceSettings.d3d11.CreateFlags = CreateFlags; - g_DeviceSettings.ver = DXUT_D3D11_DEVICE; - DXUTSnapDeviceSettingsToEnumDevice(&g_DeviceSettings, true); - - } - - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - CGrowableArray * pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - - CDXUTComboBox* pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterComboBox->RemoveAllItems(); - - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); ++iAdapter ) - { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } - - pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); - pCheckBox->SetChecked( 0 != ( g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG ) ); - - hr = OnAdapterChanged(); - if( FAILED( hr ) ) - return hr; - - break; - } - } - - return S_OK; + hr = OnAdapterChanged(); + if( FAILED( hr ) ) + return hr; + + return hr; } //------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::OnAdapterChanged() { - HRESULT hr = S_OK; - - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - // Store the adapter index - g_DeviceSettings.d3d9.AdapterOrdinal = GetSelectedAdapter(); - - // DXUTSETTINGSDLG_DEVICE_TYPE - CDXUTComboBox* pDeviceTypeComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - pDeviceTypeComboBox->RemoveAllItems(); - - CD3D9EnumAdapterInfo* pAdapterInfo = GetCurrentAdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; - - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) - { - CD3D9EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); - AddDeviceType( pDeviceInfo->DeviceType ); - } + // Store the adapter index + g_DeviceSettings.d3d11.AdapterOrdinal = GetSelectedAdapter(); - pDeviceTypeComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.DeviceType ) ); - - hr = OnDeviceTypeChanged(); - if( FAILED( hr ) ) - return hr; - - break; - } - - case DXUT_D3D11_DEVICE: - { - // Store the adapter index - g_DeviceSettings.d3d11.AdapterOrdinal = GetSelectedAdapter(); - - // DXUTSETTINGSDLG_DEVICE_TYPE - CDXUTComboBox* pDeviceTypeComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - pDeviceTypeComboBox->RemoveAllItems(); - - CD3D11EnumAdapterInfo* pAdapterInfo = GetCurrentD3D11AdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; + // DXUTSETTINGSDLG_DEVICE_TYPE + auto pDeviceTypeComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + pDeviceTypeComboBox->RemoveAllItems(); - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) - { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); - AddD3D11DeviceType( pDeviceInfo->DeviceType ); - } + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if( !pAdapterInfo ) + return E_FAIL; - pDeviceTypeComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DriverType ) ); + for( size_t iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.size(); iDeviceInfo++ ) + { + auto pDeviceInfo = pAdapterInfo->deviceInfoList[ iDeviceInfo ]; + AddD3D11DeviceType( pDeviceInfo->DeviceType ); + } - hr = OnDeviceTypeChanged(); - if( FAILED( hr ) ) - return hr; + pDeviceTypeComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DriverType ) ); - break; - } - } + HRESULT hr = OnDeviceTypeChanged(); + if( FAILED( hr ) ) + return hr; return S_OK; } @@ -1259,60 +807,64 @@ HRESULT CD3DSettingsDlg::OnDeviceTypeChanged() { HRESULT hr = S_OK; - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - g_DeviceSettings.d3d9.DeviceType = GetSelectedDeviceType(); - - // Update windowed/full screen radio buttons - bool bHasWindowedDeviceCombo = false; - bool bHasFullScreenDeviceCombo = false; + g_DeviceSettings.d3d11.DriverType = GetSelectedD3D11DeviceType(); - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; - - for( int idc = 0; idc < pDeviceInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( idc ); + // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN + m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, true ); + if (g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_FULLSCREEN, false ); + g_DeviceSettings.d3d11.sd.Windowed = TRUE; + } + else + { + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_FULLSCREEN, true ); + } - if( pDeviceSettingsCombo->Windowed ) - bHasWindowedDeviceCombo = true; - else - bHasFullScreenDeviceCombo = true; - } + SetWindowed( g_DeviceSettings.d3d11.sd.Windowed != 0 ); - // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, bHasWindowedDeviceCombo ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_FULLSCREEN, bHasFullScreenDeviceCombo ); + auto pBestDeviceSettingsCombo = DXUTGetD3D11Enumeration()->GetDeviceSettingsCombo( + g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.sd.BufferDesc.Format, + ( g_DeviceSettings.d3d11.sd.Windowed != 0 ) ); - SetWindowed( g_DeviceSettings.d3d9.pp.Windowed && bHasWindowedDeviceCombo ); + if( !pBestDeviceSettingsCombo ) + return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); - hr = OnWindowedFullScreenChanged(); - if( FAILED( hr ) ) - return hr; + D3D_FEATURE_LEVEL clampFL; + if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + clampFL = DXUTGetD3D11Enumeration()->GetWARPFeaturevel(); + else if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) + clampFL = DXUTGetD3D11Enumeration()->GetREFFeaturevel(); + else + clampFL = pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel; - break; - } - case DXUT_D3D11_DEVICE: + if ( g_DeviceSettings.d3d11.DeviceFeatureLevel > clampFL + || clampFL > pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel ) + { + g_DeviceSettings.d3d11.DeviceFeatureLevel = std::min( g_DeviceSettings.d3d11.DeviceFeatureLevel, + clampFL ); + + CDXUTComboBox *pFeatureLevelBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); + pFeatureLevelBox->RemoveAllItems(); + for (int fli = 0; fli < TOTAL_FEATURE_LEVELS; fli++) { - g_DeviceSettings.d3d11.DriverType = GetSelectedD3D11DeviceType(); - - // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, true ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_FULLSCREEN, true ); - - SetWindowed( g_DeviceSettings.d3d11.sd.Windowed != 0 ); - - hr = OnWindowedFullScreenChanged(); - if( FAILED( hr ) ) - return hr; + if (m_Levels[fli] >= g_DeviceSettings.MinimumFeatureLevel + && m_Levels[fli] <= clampFL) + { + AddD3D11FeatureLevel( m_Levels[fli] ); + } + } + pFeatureLevelBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DeviceFeatureLevel ) ); - break; - } + hr = OnFeatureLevelChanged(); + if( FAILED( hr ) ) + return hr; } + hr = OnWindowedFullScreenChanged(); + if( FAILED( hr ) ) + return hr; + return S_OK; } @@ -1324,157 +876,43 @@ HRESULT CD3DSettingsDlg::OnWindowedFullScreenChanged() HRESULT hr = S_OK; bool bWindowed = IsWindowed(); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_RESOLUTION_LABEL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_REFRESH_RATE_LABEL, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_ADAPTER_FORMAT, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_RESOLUTION, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_REFRESH_RATE, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_DEVICECLIP, bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_RESOLUTION, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_REFRESH_RATE, !bWindowed ); - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - g_DeviceSettings.d3d9.pp.Windowed = bWindowed; - bool bDeviceClip = ( 0x0 != ( g_DeviceSettings.d3d9.pp.Flags & D3DPRESENTFLAG_DEVICECLIP ) ); + g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - // If windowed, get the appropriate adapter format from Direct3D - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - IDirect3D9* pD3D = DXUTGetD3D9Object(); - if( pD3D == NULL ) - return DXTRACE_ERR( L"DXUTGetD3DObject", E_FAIL ); - - D3DDISPLAYMODE mode; - hr = pD3D->GetAdapterDisplayMode( g_DeviceSettings.d3d9.AdapterOrdinal, &mode ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"GetAdapterDisplayMode", hr ); - - // Default resolution to the fullscreen res that was last used - RECT rc = DXUTGetFullsceenClientRectAtModeChange(); - if( rc.right == 0 || rc.bottom == 0 ) - { - // If nothing last used, then default to the adapter desktop res - g_DeviceSettings.d3d9.pp.BackBufferWidth = mode.Width; - g_DeviceSettings.d3d9.pp.BackBufferHeight = mode.Height; - } - else - { - g_DeviceSettings.d3d9.pp.BackBufferWidth = rc.right; - g_DeviceSettings.d3d9.pp.BackBufferHeight = rc.bottom; - } + // Get available adapter output + auto pD3DEnum = DXUTGetD3D11Enumeration(); - g_DeviceSettings.d3d9.AdapterFormat = mode.Format; - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = mode.RefreshRate; - } - - const D3DFORMAT adapterFormat = g_DeviceSettings.d3d9.AdapterFormat; - const DWORD dwWidth = g_DeviceSettings.d3d9.pp.BackBufferWidth; - const DWORD dwHeight = g_DeviceSettings.d3d9.pp.BackBufferHeight; - const DWORD dwRefreshRate = g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz; - - // DXUTSETTINGSDLG_DEVICECLIP - SetDeviceClip( bDeviceClip ); - - // DXUTSETTINGSDLG_ADAPTER_FORMAT - CDXUTComboBox* pAdapterFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - if( pAdapterFormatComboBox == NULL ) - return E_FAIL; - pAdapterFormatComboBox->RemoveAllItems(); - - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; - - if( bWindowed ) - { - AddAdapterFormat( adapterFormat ); - } - else - { - for( int iSettingsCombo = 0; iSettingsCombo < pDeviceInfo->deviceSettingsComboList.GetSize(); - iSettingsCombo++ ) - { - CD3D9EnumDeviceSettingsCombo* pSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( - iSettingsCombo ); - AddAdapterFormat( pSettingsCombo->AdapterFormat ); - } - } - - pAdapterFormatComboBox->SetSelectedByData( ULongToPtr( adapterFormat ) ); - - hr = OnAdapterFormatChanged(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_RESOLUTION - CDXUTComboBox* pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); - - if( bWindowed ) - { - pResolutionComboBox->RemoveAllItems(); - AddResolution( dwWidth, dwHeight ); - } - - pResolutionComboBox->SetSelectedByData( ULongToPtr( MAKELONG( dwWidth, dwHeight ) ) ); - - hr = OnResolutionChanged(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_REFRESH_RATE - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); + auto pOutputComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); + pOutputComboBox->RemoveAllItems(); - if( bWindowed ) - { - pRefreshRateComboBox->RemoveAllItems(); - AddRefreshRate( dwRefreshRate ); - } - - pRefreshRateComboBox->SetSelectedByData( ULongToPtr( dwRefreshRate ) ); - - hr = OnRefreshRateChanged(); - if( FAILED( hr ) ) - return hr; - - break; - } - - case DXUT_D3D11_DEVICE: - { - g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - - // Get available adapter output - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - - CDXUTComboBox* pOutputComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); - pOutputComboBox->RemoveAllItems(); + auto pAdapterInfo = pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d11.AdapterOrdinal ); + for( size_t ioutput = 0; ioutput < pAdapterInfo->outputInfoList.size(); ++ioutput ) + { + auto pOutputInfo = pAdapterInfo->outputInfoList[ ioutput ]; + AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, pOutputInfo->Output ); + } - CD3D11EnumAdapterInfo* pAdapterInfo = pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d11.AdapterOrdinal ); - for( int ioutput = 0; ioutput < pAdapterInfo->outputInfoList.GetSize(); ++ioutput ) - { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( ioutput ); - AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, pOutputInfo->Output ); - } + pOutputComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.Output ) ); - pOutputComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.Output ) ); + hr = OnAdapterOutputChanged(); + if( FAILED( hr ) ) + return hr; - hr = OnAdapterOutputChanged(); - if( FAILED( hr ) ) - return hr; + hr = UpdateD3D11Resolutions(); + if (FAILED(hr)) + return hr; - break; - } - } + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; return S_OK; } @@ -1485,235 +923,68 @@ HRESULT CD3DSettingsDlg::OnAdapterOutputChanged() { HRESULT hr; - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D11_DEVICE: - { - bool bWindowed = IsWindowed(); - g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - - // If windowed, get the appropriate adapter format from Direct3D - if( g_DeviceSettings.d3d11.sd.Windowed ) - { - DXGI_MODE_DESC mode; - hr = DXUTGetD3D11AdapterDisplayMode( g_DeviceSettings.d3d11.AdapterOrdinal, - g_DeviceSettings.d3d11.Output, &mode ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"GetD3D11AdapterDisplayMode", hr ); - - // Default resolution to the fullscreen res that was last used - RECT rc = DXUTGetFullsceenClientRectAtModeChange(); - if( rc.right == 0 || rc.bottom == 0 ) - { - // If nothing last used, then default to the adapter desktop res - g_DeviceSettings.d3d11.sd.BufferDesc.Width = mode.Width; - g_DeviceSettings.d3d11.sd.BufferDesc.Height = mode.Height; - } - else - { - g_DeviceSettings.d3d11.sd.BufferDesc.Width = rc.right; - g_DeviceSettings.d3d11.sd.BufferDesc.Height = rc.bottom; - } - - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = mode.RefreshRate; - } - - const DXGI_RATIONAL RefreshRate = g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate; - - CD3D11EnumAdapterInfo* pAdapterInfo = GetCurrentD3D11AdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; - - // DXUTSETTINGSDLG_D3D11_RESOLUTION - hr = UpdateD3D11Resolutions(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT - CDXUTComboBox* pBackBufferFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT - ); - pBackBufferFormatComboBox->RemoveAllItems(); - - for( int idc = 0; idc < pAdapterInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = pAdapterInfo->deviceSettingsComboList.GetAt( idc ); - if( ( pDeviceCombo->Windowed == TRUE ) == bWindowed ) - { - AddD3D11BackBufferFormat( pDeviceCombo->BackBufferFormat ); - } - } - - pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.BufferDesc.Format ) ); - - hr = OnBackBufferFormatChanged(); - if( FAILED( hr ) ) - return hr; + bool bWindowed = IsWindowed(); + g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - // DXUTSETTINGSDLG_D3D11_REFRESH_RATE - if( bWindowed ) - { - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); - for( UINT i = 0; i < pRefreshRateComboBox->GetNumItems(); ++i ) - { - DXGI_RATIONAL* pRefreshRate = reinterpret_cast( - pRefreshRateComboBox->GetItemData( i ) ); - delete pRefreshRate; - } - pRefreshRateComboBox->RemoveAllItems(); - AddD3D11RefreshRate( RefreshRate ); - } + // If windowed, get the appropriate adapter format from Direct3D + if( g_DeviceSettings.d3d11.sd.Windowed ) + { + DXGI_MODE_DESC mode; + hr = DXUTGetD3D11AdapterDisplayMode( g_DeviceSettings.d3d11.AdapterOrdinal, + g_DeviceSettings.d3d11.Output, &mode ); + if( FAILED( hr ) ) + return DXTRACE_ERR( L"GetD3D11AdapterDisplayMode", hr ); - SetSelectedD3D11RefreshRate( RefreshRate ); - break; + // Default resolution to the fullscreen res that was last used + RECT rc = DXUTGetFullsceenClientRectAtModeChange(); + if( rc.right == 0 || rc.bottom == 0 ) + { + // If nothing last used, then default to the adapter desktop res + g_DeviceSettings.d3d11.sd.BufferDesc.Width = mode.Width; + g_DeviceSettings.d3d11.sd.BufferDesc.Height = mode.Height; } - }; - - hr = OnRefreshRateChanged(); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnAdapterFormatChanged() -{ - HRESULT hr = S_OK; - - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: + else { - // DXUTSETTINGSDLG_ADAPTER_FORMAT - D3DFORMAT adapterFormat = GetSelectedAdapterFormat(); - g_DeviceSettings.d3d9.AdapterFormat = adapterFormat; - - // DXUTSETTINGSDLG_RESOLUTION - CDXUTComboBox* pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); - pResolutionComboBox->RemoveAllItems(); - - CD3D9EnumAdapterInfo* pAdapterInfo = GetCurrentAdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; - - bool bShowAll = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL )->GetChecked(); - - // Get the desktop aspect ratio - D3DDISPLAYMODE dmDesktop; - DXUTGetDesktopResolution( g_DeviceSettings.d3d9.AdapterOrdinal, &dmDesktop.Width, &dmDesktop.Height ); - float fDesktopAspectRatio = dmDesktop.Width / ( float )dmDesktop.Height; - - for( int idm = 0; idm < pAdapterInfo->displayModeList.GetSize(); idm++ ) - { - D3DDISPLAYMODE DisplayMode = pAdapterInfo->displayModeList.GetAt( idm ); - float fAspect = ( float )DisplayMode.Width / ( float )DisplayMode.Height; - - if( DisplayMode.Format == g_DeviceSettings.d3d9.AdapterFormat ) - { - // If "Show All" is not checked, then hide all resolutions - // that don't match the aspect ratio of the desktop resolution - if( bShowAll || ( !bShowAll && fabsf( fDesktopAspectRatio - fAspect ) < 0.05f ) ) - { - AddResolution( DisplayMode.Width, DisplayMode.Height ); - } - } - } - - const DWORD dwCurResolution = MAKELONG( g_DeviceSettings.d3d9.pp.BackBufferWidth, - g_DeviceSettings.d3d9.pp.BackBufferHeight ); - - pResolutionComboBox->SetSelectedByData( ULongToPtr( dwCurResolution ) ); - - hr = OnResolutionChanged(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_BACK_BUFFER_FORMAT - CDXUTComboBox* pBackBufferFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - pBackBufferFormatComboBox->RemoveAllItems(); - - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; - - const BOOL bWindowed = IsWindowed(); - bool bHasWindowedBackBuffer = false; - - for( int idc = 0; idc < pDeviceInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceCombo = pDeviceInfo->deviceSettingsComboList.GetAt( idc ); - if( pDeviceCombo->Windowed == bWindowed && - pDeviceCombo->AdapterFormat == g_DeviceSettings.d3d9.AdapterFormat ) - { - AddBackBufferFormat( pDeviceCombo->BackBufferFormat ); - bHasWindowedBackBuffer = true; - } - } - - pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.pp.BackBufferFormat ) ); - - hr = OnBackBufferFormatChanged(); - if( FAILED( hr ) ) - return hr; - - if( !bHasWindowedBackBuffer ) - { - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, false ); - - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - SetWindowed( false ); - - hr = OnWindowedFullScreenChanged(); - if( FAILED( hr ) ) - return hr; - } - } - - break; + g_DeviceSettings.d3d11.sd.BufferDesc.Width = rc.right; + g_DeviceSettings.d3d11.sd.BufferDesc.Height = rc.bottom; } - } - - return S_OK; -} - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnResolutionChanged() -{ - HRESULT hr = S_OK; + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator = 0; + } - CD3D9EnumAdapterInfo* pAdapterInfo = GetCurrentAdapterInfo(); - if( pAdapterInfo == NULL ) + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if( !pAdapterInfo ) return E_FAIL; - // Set resolution - DWORD dwWidth, dwHeight; - GetSelectedResolution( &dwWidth, &dwHeight ); - g_DeviceSettings.d3d9.pp.BackBufferWidth = dwWidth; - g_DeviceSettings.d3d9.pp.BackBufferHeight = dwHeight; + // DXUTSETTINGSDLG_D3D11_RESOLUTION + hr = UpdateD3D11Resolutions(); + if( FAILED( hr ) ) + return hr; - DWORD dwRefreshRate = g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz; + // DXUTSETTINGSDLG_D3D11_REFRESH_RATE + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; - // Update the refresh rate list - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); - pRefreshRateComboBox->RemoveAllItems(); + // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT + auto pBackBufferFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); + pBackBufferFormatComboBox->RemoveAllItems(); - D3DFORMAT adapterFormat = g_DeviceSettings.d3d9.AdapterFormat; - for( int idm = 0; idm < pAdapterInfo->displayModeList.GetSize(); idm++ ) + for( size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++ ) { - D3DDISPLAYMODE displayMode = pAdapterInfo->displayModeList.GetAt( idm ); - - if( displayMode.Format == adapterFormat && - displayMode.Width == dwWidth && - displayMode.Height == dwHeight ) + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[ idc ]; + if( ( pDeviceCombo->Windowed == TRUE ) == bWindowed ) { - AddRefreshRate( displayMode.RefreshRate ); + AddD3D11BackBufferFormat( pDeviceCombo->BackBufferFormat ); } } - pRefreshRateComboBox->SetSelectedByData( ULongToPtr( dwRefreshRate ) ); + pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.BufferDesc.Format ) ); + + hr = OnBackBufferFormatChanged(); + if( FAILED( hr ) ) + return hr; hr = OnRefreshRateChanged(); if( FAILED( hr ) ) @@ -1723,21 +994,11 @@ HRESULT CD3DSettingsDlg::OnResolutionChanged() } - //------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::OnRefreshRateChanged() { // Set refresh rate - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = GetSelectedRefreshRate(); - break; - - case DXUT_D3D11_DEVICE: - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = GetSelectedD3D11RefreshRate(); - break; - } + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = GetSelectedD3D11RefreshRate(); return S_OK; } @@ -1748,310 +1009,50 @@ HRESULT CD3DSettingsDlg::OnBackBufferFormatChanged() { HRESULT hr = S_OK; - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - g_DeviceSettings.d3d9.pp.BackBufferFormat = GetSelectedBackBufferFormat(); - - D3DFORMAT adapterFormat = g_DeviceSettings.d3d9.AdapterFormat; - D3DFORMAT backBufferFormat = g_DeviceSettings.d3d9.pp.BackBufferFormat; - - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; + g_DeviceSettings.d3d11.sd.BufferDesc.Format = GetSelectedD3D11BackBufferFormat(); - bool bAllowSoftwareVP, bAllowHardwareVP, bAllowPureHardwareVP, bAllowMixedVP; - DXUTGetD3D9Enumeration()->GetPossibleVertexProcessingList( &bAllowSoftwareVP, &bAllowHardwareVP, - &bAllowPureHardwareVP, &bAllowMixedVP ); - - for( int idc = 0; idc < pDeviceInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceCombo = pDeviceInfo->deviceSettingsComboList.GetAt( idc ); - - if( pDeviceCombo->Windowed == ( g_DeviceSettings.d3d9.pp.Windowed == TRUE ) && - pDeviceCombo->AdapterFormat == adapterFormat && - pDeviceCombo->BackBufferFormat == backBufferFormat ) - { - CDXUTComboBox* pDepthStencilComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - pDepthStencilComboBox->RemoveAllItems(); - pDepthStencilComboBox->SetEnabled( ( g_DeviceSettings.d3d9.pp.EnableAutoDepthStencil == TRUE ) ); - - if( g_DeviceSettings.d3d9.pp.EnableAutoDepthStencil ) - { - for( int ifmt = 0; ifmt < pDeviceCombo->depthStencilFormatList.GetSize(); ifmt++ ) - { - D3DFORMAT fmt = pDeviceCombo->depthStencilFormatList.GetAt( ifmt ); - - AddDepthStencilBufferFormat( fmt ); - } - - pDepthStencilComboBox->SetSelectedByData( ULongToPtr( - g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat ) ); - } - else - { - if( !pDepthStencilComboBox->ContainsItem( L"(not used)" ) ) - pDepthStencilComboBox->AddItem( L"(not used)", NULL ); - } - - hr = OnDepthStencilBufferFormatChanged(); - if( FAILED( hr ) ) - return hr; - - CDXUTComboBox* pVertexProcessingComboBox = - m_Dialog.GetComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING ); - pVertexProcessingComboBox->RemoveAllItems(); - - // Add valid vertex processing types - if( bAllowSoftwareVP ) - AddVertexProcessingType( D3DCREATE_SOFTWARE_VERTEXPROCESSING ); - - if( bAllowHardwareVP && pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) - AddVertexProcessingType( D3DCREATE_HARDWARE_VERTEXPROCESSING ); - - if( bAllowPureHardwareVP && pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_PUREDEVICE ) - AddVertexProcessingType( D3DCREATE_PUREDEVICE ); - - if( bAllowMixedVP && pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) - AddVertexProcessingType( D3DCREATE_MIXED_VERTEXPROCESSING ); - - if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_PUREDEVICE ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( D3DCREATE_PUREDEVICE ) ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( - D3DCREATE_SOFTWARE_VERTEXPROCESSING ) ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( - D3DCREATE_HARDWARE_VERTEXPROCESSING ) ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( D3DCREATE_MIXED_VERTEXPROCESSING ) ); - - hr = OnVertexProcessingChanged(); - if( FAILED( hr ) ) - return hr; - - CDXUTComboBox* pPresentIntervalComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL ); - pPresentIntervalComboBox->RemoveAllItems(); - pPresentIntervalComboBox->AddItem( L"On", ULongToPtr( D3DPRESENT_INTERVAL_DEFAULT ) ); - pPresentIntervalComboBox->AddItem( L"Off", ULongToPtr( D3DPRESENT_INTERVAL_IMMEDIATE ) ); - - pPresentIntervalComboBox->SetSelectedByData( ULongToPtr( - g_DeviceSettings.d3d9.pp.PresentationInterval ) ); - - hr = OnPresentIntervalChanged(); - if( FAILED( hr ) ) - return hr; - } - } - - break; - } - - case DXUT_D3D11_DEVICE: - { - g_DeviceSettings.d3d11.sd.BufferDesc.Format = GetSelectedD3D11BackBufferFormat(); + DXGI_FORMAT backBufferFormat = g_DeviceSettings.d3d11.sd.BufferDesc.Format; - DXGI_FORMAT backBufferFormat = g_DeviceSettings.d3d11.sd.BufferDesc.Format; - - CD3D11EnumAdapterInfo* pAdapterInfo = GetCurrentD3D11AdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; - - for( int idc = 0; idc < pAdapterInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = pAdapterInfo->deviceSettingsComboList.GetAt( idc ); - - if( pDeviceCombo->Windowed == ( g_DeviceSettings.d3d11.sd.Windowed == TRUE ) && - pDeviceCombo->BackBufferFormat == backBufferFormat && - pDeviceCombo->DeviceType == g_DeviceSettings.d3d11.DriverType ) - { - CDXUTComboBox* pMultisampleCountCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT - ); - pMultisampleCountCombo->RemoveAllItems(); - for( int i = 0; i < pDeviceCombo->multiSampleCountList.GetSize(); ++i ) - AddD3D11MultisampleCount( pDeviceCombo->multiSampleCountList.GetAt( i ) ); - pMultisampleCountCombo->SetSelectedByData( ULongToPtr( - g_DeviceSettings.d3d11.sd.SampleDesc.Count ) ); - - hr = OnMultisampleTypeChanged(); - if( FAILED( hr ) ) - return hr; - - CDXUTComboBox* pPresentIntervalComboBox = - m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); - pPresentIntervalComboBox->RemoveAllItems(); - pPresentIntervalComboBox->AddItem( L"On", ULongToPtr( 1 ) ); - pPresentIntervalComboBox->AddItem( L"Off", ULongToPtr( 0 ) ); - - pPresentIntervalComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.SyncInterval ) ); - - hr = OnPresentIntervalChanged(); - if( FAILED( hr ) ) - return hr; - - hr = UpdateD3D11Resolutions(); - if( FAILED( hr ) ) - return hr; - } - } - - break; - } - } - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnDepthStencilBufferFormatChanged() -{ - HRESULT hr = S_OK; - - D3DFORMAT depthStencilBufferFormat = GetSelectedDepthStencilBufferFormat(); - - if( g_DeviceSettings.d3d9.pp.EnableAutoDepthStencil ) - g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat = depthStencilBufferFormat; - - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = GetCurrentDeviceSettingsCombo(); - if( pDeviceSettingsCombo == NULL ) + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if( !pAdapterInfo ) return E_FAIL; - CDXUTComboBox* pMultisampleTypeCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - pMultisampleTypeCombo->RemoveAllItems(); - - for( int ims = 0; ims < pDeviceSettingsCombo->multiSampleTypeList.GetSize(); ims++ ) + for( size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++ ) { - D3DMULTISAMPLE_TYPE msType = pDeviceSettingsCombo->multiSampleTypeList.GetAt( ims ); - - bool bConflictFound = false; - for( int iConf = 0; iConf < pDeviceSettingsCombo->DSMSConflictList.GetSize(); iConf++ ) - { - CD3D9EnumDSMSConflict DSMSConf = pDeviceSettingsCombo->DSMSConflictList.GetAt( iConf ); - if( DSMSConf.DSFormat == depthStencilBufferFormat && - DSMSConf.MSType == msType ) - { - bConflictFound = true; - break; - } - } - - if( !bConflictFound ) - AddMultisampleType( msType ); - } - - CDXUTComboBox* pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.pp.MultiSampleType ) ); - - hr = OnMultisampleTypeChanged(); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[ idc ]; - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnMultisampleTypeChanged() -{ - HRESULT hr = S_OK; - - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: + if( pDeviceCombo->Windowed == ( g_DeviceSettings.d3d11.sd.Windowed == TRUE ) && + pDeviceCombo->BackBufferFormat == backBufferFormat && + pDeviceCombo->DeviceType == g_DeviceSettings.d3d11.DriverType ) { - D3DMULTISAMPLE_TYPE multisampleType = GetSelectedMultisampleType(); - g_DeviceSettings.d3d9.pp.MultiSampleType = multisampleType; - - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = GetCurrentDeviceSettingsCombo(); - if( pDeviceSettingsCombo == NULL ) - return E_FAIL; - - DWORD dwMaxQuality = 0; - for( int iType = 0; iType < pDeviceSettingsCombo->multiSampleTypeList.GetSize(); iType++ ) - { - D3DMULTISAMPLE_TYPE msType = pDeviceSettingsCombo->multiSampleTypeList.GetAt( iType ); - if( msType == multisampleType ) - { - dwMaxQuality = pDeviceSettingsCombo->multiSampleQualityList.GetAt( iType ); - break; - } - } + auto pMultisampleCountCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); + pMultisampleCountCombo->RemoveAllItems(); - // DXUTSETTINGSDLG_MULTISAMPLE_QUALITY - CDXUTComboBox* pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY ); - pMultisampleQualityCombo->RemoveAllItems(); + for( auto it = pDeviceCombo->multiSampleCountList.cbegin(); it != pDeviceCombo->multiSampleCountList.cend(); ++it ) + AddD3D11MultisampleCount( *it ); + pMultisampleCountCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.SampleDesc.Count ) ); - for( UINT iQuality = 0; iQuality < dwMaxQuality; iQuality++ ) - { - AddMultisampleQuality( iQuality ); - } - - pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.pp.MultiSampleQuality ) ); - - hr = OnMultisampleQualityChanged(); + hr = OnMultisampleTypeChanged(); if( FAILED( hr ) ) return hr; - break; - } - case DXUT_D3D11_DEVICE: - { - UINT multisampleCount = GetSelectedD3D11MultisampleCount(); - g_DeviceSettings.d3d11.sd.SampleDesc.Count = multisampleCount; - - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = GetCurrentD3D11DeviceSettingsCombo(); - if( pDeviceSettingsCombo == NULL ) - return E_FAIL; - - UINT MaxQuality = 0; - for( int iCount = 0; iCount < pDeviceSettingsCombo->multiSampleCountList.GetSize(); iCount++ ) - { - UINT Count = pDeviceSettingsCombo->multiSampleCountList.GetAt( iCount ); - if( Count == multisampleCount ) - { - MaxQuality = pDeviceSettingsCombo->multiSampleQualityList.GetAt( iCount ); - break; - } - } - - // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY - CDXUTComboBox* pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY - ); - pMultisampleQualityCombo->RemoveAllItems(); - - for( UINT iQuality = 0; iQuality < MaxQuality; iQuality++ ) - { - AddD3D11MultisampleQuality( iQuality ); - } + auto pPresentIntervalComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); + pPresentIntervalComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.SyncInterval ) ); - pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ) ); - - hr = OnMultisampleQualityChanged(); + hr = OnPresentIntervalChanged(); if( FAILED( hr ) ) return hr; - break; - } - } - - return S_OK; -} - + hr = UpdateD3D11Resolutions(); + if( FAILED( hr ) ) + return hr; -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnMultisampleQualityChanged() -{ - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - g_DeviceSettings.d3d9.pp.MultiSampleQuality = GetSelectedMultisampleQuality(); - break; + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; - case DXUT_D3D11_DEVICE: - g_DeviceSettings.d3d11.sd.SampleDesc.Quality = GetSelectedD3D11MultisampleQuality(); break; + } } return S_OK; @@ -2059,170 +1060,130 @@ HRESULT CD3DSettingsDlg::OnMultisampleQualityChanged() //------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnVertexProcessingChanged() +HRESULT CD3DSettingsDlg::OnMultisampleTypeChanged() { - DWORD dwBehavior = g_DeviceSettings.d3d9.BehaviorFlags; - - // Clear vertex processing flags - dwBehavior &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; - dwBehavior &= ~D3DCREATE_SOFTWARE_VERTEXPROCESSING; - dwBehavior &= ~D3DCREATE_MIXED_VERTEXPROCESSING; - dwBehavior &= ~D3DCREATE_PUREDEVICE; - - // Determine new flags - DWORD dwNewFlags = GetSelectedVertexProcessingType(); - if( dwNewFlags & D3DCREATE_PUREDEVICE ) - dwNewFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; - - // Make changes - g_DeviceSettings.d3d9.BehaviorFlags = dwBehavior | dwNewFlags; + HRESULT hr = S_OK; - return S_OK; -} + UINT multisampleCount = GetSelectedD3D11MultisampleCount(); + g_DeviceSettings.d3d11.sd.SampleDesc.Count = multisampleCount; + auto pDeviceSettingsCombo = GetCurrentD3D11DeviceSettingsCombo(); + if( !pDeviceSettingsCombo ) + return E_FAIL; -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnPresentIntervalChanged() -{ - switch( g_DeviceSettings.ver ) + UINT MaxQuality = 0; + for( size_t iCount = 0; iCount < pDeviceSettingsCombo->multiSampleCountList.size(); iCount++ ) { - case DXUT_D3D9_DEVICE: - g_DeviceSettings.d3d9.pp.PresentationInterval = GetSelectedPresentInterval(); - break; - - case DXUT_D3D11_DEVICE: - g_DeviceSettings.d3d11.SyncInterval = GetSelectedD3D11PresentInterval(); + UINT Count = pDeviceSettingsCombo->multiSampleCountList[ iCount ]; + if( Count == multisampleCount ) + { + MaxQuality = pDeviceSettingsCombo->multiSampleQualityList[ iCount ]; break; + } } - return S_OK; -} - - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnDebugDeviceChanged() -{ - bool bDebugDevice = GetSelectedDebugDeviceValue(); - - if( bDebugDevice ) - g_DeviceSettings.d3d11.CreateFlags |= D3D11_CREATE_DEVICE_DEBUG; - else - g_DeviceSettings.d3d11.CreateFlags &= ~D3D11_CREATE_DEVICE_DEBUG; - - return S_OK; -} - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnDeviceClipChanged() -{ - if( IsDeviceClip() ) - g_DeviceSettings.d3d9.pp.Flags |= D3DPRESENTFLAG_DEVICECLIP; - else - g_DeviceSettings.d3d9.pp.Flags &= ~D3DPRESENTFLAG_DEVICECLIP; + // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY + auto pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); + pMultisampleQualityCombo->RemoveAllItems(); - return S_OK; -} + for( UINT iQuality = 0; iQuality < MaxQuality; iQuality++ ) + { + AddD3D11MultisampleQuality( iQuality ); + } + pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ) ); -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddAPIVersion( DXUTDeviceVersion version ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_API_VERSION ); + hr = OnMultisampleQualityChanged(); + if( FAILED( hr ) ) + return hr; - if( !pComboBox->ContainsItem( DXUTAPIVersionToString( version ) ) ) - pComboBox->AddItem( DXUTAPIVersionToString( version ), ULongToPtr( version ) ); + return S_OK; } //------------------------------------------------------------------------------------- -DXUTDeviceVersion CD3DSettingsDlg::GetSelectedAPIVersion() +HRESULT CD3DSettingsDlg::OnMultisampleQualityChanged() { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_API_VERSION ); + g_DeviceSettings.d3d11.sd.SampleDesc.Quality = GetSelectedD3D11MultisampleQuality(); - return ( DXUTDeviceVersion )PtrToUlong( pComboBox->GetSelectedData() ); + return S_OK; } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddAdapter( const WCHAR* strDescription, UINT iAdapter ) +HRESULT CD3DSettingsDlg::OnPresentIntervalChanged() { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + g_DeviceSettings.d3d11.SyncInterval = GetSelectedD3D11PresentInterval(); - if( !pComboBox->ContainsItem( strDescription ) ) - pComboBox->AddItem( strDescription, ULongToPtr( iAdapter ) ); + return S_OK; } //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedAdapter() +HRESULT CD3DSettingsDlg::OnDebugDeviceChanged() { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + bool bDebugDevice = GetSelectedDebugDeviceValue(); - return PtrToUlong( pComboBox->GetSelectedData() ); + if( bDebugDevice ) + g_DeviceSettings.d3d11.CreateFlags |= D3D11_CREATE_DEVICE_DEBUG; + else + g_DeviceSettings.d3d11.CreateFlags &= ~D3D11_CREATE_DEVICE_DEBUG; + + return S_OK; } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddDeviceType( D3DDEVTYPE devType ) +void CD3DSettingsDlg::AddAdapter( _In_z_ const WCHAR* strDescription, _In_ UINT iAdapter ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - if( !pComboBox->ContainsItem( DXUTD3DDeviceTypeToString( devType ) ) ) - pComboBox->AddItem( DXUTD3DDeviceTypeToString( devType ), ULongToPtr( devType ) ); + if( !pComboBox->ContainsItem( strDescription ) ) + pComboBox->AddItem( strDescription, ULongToPtr( iAdapter ) ); } //------------------------------------------------------------------------------------- -D3DDEVTYPE CD3DSettingsDlg::GetSelectedDeviceType() +UINT CD3DSettingsDlg::GetSelectedAdapter() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - return ( D3DDEVTYPE )PtrToUlong( pComboBox->GetSelectedData() ); + return PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::SetWindowed( bool bWindowed ) +void CD3DSettingsDlg::SetWindowed( _In_ bool bWindowed ) { - CDXUTRadioButton* pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); + auto pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); pRadioButton->SetChecked( bWindowed ); pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_FULLSCREEN ); pRadioButton->SetChecked( !bWindowed ); -} - - -//------------------------------------------------------------------------------------- -bool CD3DSettingsDlg::IsWindowed() -{ - CDXUTRadioButton* pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); - return pRadioButton->GetChecked(); -} + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL, !bWindowed); -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddAdapterFormat( D3DFORMAT format ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - - if( !pComboBox->ContainsItem( DXUTD3DFormatToString( format, TRUE ) ) ) - pComboBox->AddItem( DXUTD3DFormatToString( format, TRUE ), ULongToPtr( format ) ); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_RESOLUTION, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_REFRESH_RATE, !bWindowed); } //------------------------------------------------------------------------------------- -D3DFORMAT CD3DSettingsDlg::GetSelectedAdapterFormat() +bool CD3DSettingsDlg::IsWindowed() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - - return ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); + auto pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); + return pRadioButton->GetChecked(); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11AdapterOutput( const WCHAR* strName, UINT Output ) +void CD3DSettingsDlg::AddD3D11AdapterOutput( _In_z_ const WCHAR* strName, _In_ UINT Output ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); if( !pComboBox->ContainsItem( strName ) ) pComboBox->AddItem( strName, ULongToPtr( Output ) ); @@ -2230,23 +1191,24 @@ void CD3DSettingsDlg::AddD3D11AdapterOutput( const WCHAR* strName, UINT Output ) //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedD3D11AdapterOutput() +UINT CD3DSettingsDlg::GetSelectedD3D11AdapterOutput() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); return PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddResolution( DWORD dwWidth, DWORD dwHeight ) +_Use_decl_annotations_ +void CD3DSettingsDlg::AddD3D11Resolution( DWORD dwWidth, DWORD dwHeight ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); DWORD dwResolutionData; WCHAR strResolution[50]; dwResolutionData = MAKELONG( dwWidth, dwHeight ); - swprintf_s( strResolution, 50, L"%d by %d", dwWidth, dwHeight ); + swprintf_s( strResolution, 50, L"%u by %u", dwWidth, dwHeight ); if( !pComboBox->ContainsItem( strResolution ) ) pComboBox->AddItem( strResolution, ULongToPtr( dwResolutionData ) ); @@ -2254,9 +1216,10 @@ void CD3DSettingsDlg::AddResolution( DWORD dwWidth, DWORD dwHeight ) //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::GetSelectedResolution( DWORD* pdwWidth, DWORD* pdwHeight ) +_Use_decl_annotations_ +void CD3DSettingsDlg::GetSelectedD3D11Resolution( DWORD* pdwWidth, DWORD* pdwHeight ) const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); DWORD dwResolution = PtrToUlong( pComboBox->GetSelectedData() ); @@ -2266,33 +1229,9 @@ void CD3DSettingsDlg::GetSelectedResolution( DWORD* pdwWidth, DWORD* pdwHeight ) //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11Resolution( DWORD dwWidth, DWORD dwHeight ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); - - DWORD dwResolutionData; - WCHAR strResolution[50]; - dwResolutionData = MAKELONG( dwWidth, dwHeight ); - swprintf_s( strResolution, 50, L"%d by %d", dwWidth, dwHeight ); - - if( !pComboBox->ContainsItem( strResolution ) ) - pComboBox->AddItem( strResolution, ULongToPtr( dwResolutionData ) ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::GetSelectedD3D11Resolution( DWORD* pdwWidth, DWORD* pdwHeight ) +void CD3DSettingsDlg::AddD3D11FeatureLevel( _In_ D3D_FEATURE_LEVEL fl) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); - - DWORD dwResolution = PtrToUlong( pComboBox->GetSelectedData() ); - - *pdwWidth = LOWORD( dwResolution ); - *pdwHeight = HIWORD( dwResolution ); -} - -void CD3DSettingsDlg::AddD3D11FeatureLevel(D3D_FEATURE_LEVEL fl) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); switch( fl ) { case D3D_FEATURE_LEVEL_9_1: @@ -2331,56 +1270,53 @@ void CD3DSettingsDlg::AddD3D11FeatureLevel(D3D_FEATURE_LEVEL fl) { pComboBox->AddItem( L"D3D_FEATURE_LEVEL_11_0", ULongToPtr( D3D_FEATURE_LEVEL_11_0 ) ); } break; + case D3D_FEATURE_LEVEL_11_1: + { + if( !pComboBox->ContainsItem( L"D3D_FEATURE_LEVEL_11_1" ) ) + pComboBox->AddItem( L"D3D_FEATURE_LEVEL_11_1", ULongToPtr( D3D_FEATURE_LEVEL_11_1 ) ); + } + break; +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + case D3D_FEATURE_LEVEL_12_0: + { + if (!pComboBox->ContainsItem(L"D3D_FEATURE_LEVEL_12_0")) + pComboBox->AddItem(L"D3D_FEATURE_LEVEL_12_0", ULongToPtr(D3D_FEATURE_LEVEL_12_0)); + } + break; + case D3D_FEATURE_LEVEL_12_1: + { + if (!pComboBox->ContainsItem(L"D3D_FEATURE_LEVEL_12_1")) + pComboBox->AddItem(L"D3D_FEATURE_LEVEL_12_1", ULongToPtr(D3D_FEATURE_LEVEL_12_1)); + } + break; +#endif } } -D3D_FEATURE_LEVEL CD3DSettingsDlg::GetSelectedFeatureLevel() { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); - - return (D3D_FEATURE_LEVEL)PtrToUlong( pComboBox->GetSelectedData() ); -} -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddRefreshRate( DWORD dwRate ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); - - WCHAR strRefreshRate[50]; - - if( dwRate == 0 ) - wcscpy_s( strRefreshRate, 50, L"Default Rate" ); - else - swprintf_s( strRefreshRate, 50, L"%d Hz", dwRate ); - - if( !pComboBox->ContainsItem( strRefreshRate ) ) - pComboBox->AddItem( strRefreshRate, ULongToPtr( dwRate ) ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedRefreshRate() +D3D_FEATURE_LEVEL CD3DSettingsDlg::GetSelectedFeatureLevel() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); - return PtrToUlong( pComboBox->GetSelectedData() ); + return (D3D_FEATURE_LEVEL)PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) +void CD3DSettingsDlg::AddD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); WCHAR strRefreshRate[50]; if( RefreshRate.Numerator == 0 && RefreshRate.Denominator == 0 ) wcscpy_s( strRefreshRate, 50, L"Default Rate" ); else - swprintf_s( strRefreshRate, 50, L"%d Hz", RefreshRate.Numerator / RefreshRate.Denominator ); + swprintf_s( strRefreshRate, 50, L"%u Hz", RefreshRate.Numerator / RefreshRate.Denominator ); if( !pComboBox->ContainsItem( strRefreshRate ) ) { - DXGI_RATIONAL* pNewRate = new DXGI_RATIONAL; + auto pNewRate = new (std::nothrow) DXGI_RATIONAL; if( pNewRate ) { *pNewRate = RefreshRate; @@ -2391,42 +1327,23 @@ void CD3DSettingsDlg::AddD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) //------------------------------------------------------------------------------------- -DXGI_RATIONAL CD3DSettingsDlg::GetSelectedD3D11RefreshRate() +DXGI_RATIONAL CD3DSettingsDlg::GetSelectedD3D11RefreshRate() const { - DXGI_RATIONAL dxgiR; - dxgiR.Numerator = 0; - dxgiR.Denominator = 1; - - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); - + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); return *reinterpret_cast( pComboBox->GetSelectedData() ); - -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddBackBufferFormat( D3DFORMAT format ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - - if( !pComboBox->ContainsItem( DXUTD3DFormatToString( format, TRUE ) ) ) - pComboBox->AddItem( DXUTD3DFormatToString( format, TRUE ), ULongToPtr( format ) ); } //------------------------------------------------------------------------------------- -D3DFORMAT CD3DSettingsDlg::GetSelectedBackBufferFormat() +void CD3DSettingsDlg::AddD3D11BackBufferFormat( _In_ DXGI_FORMAT format ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - - return ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); -} - + if ( g_DeviceSettings.d3d11.DeviceFeatureLevel < D3D_FEATURE_LEVEL_10_0 ) + { + if ( (format == DXGI_FORMAT_R16G16B16A16_FLOAT) || (format == DXGI_FORMAT_R10G10B10A2_UNORM) ) + return; + } -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11BackBufferFormat( DXGI_FORMAT format ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); if( !pComboBox->ContainsItem( DXUTDXGIFormatToString( format, TRUE ) ) ) pComboBox->AddItem( DXUTDXGIFormatToString( format, TRUE ), ULongToPtr( format ) ); @@ -2434,78 +1351,18 @@ void CD3DSettingsDlg::AddD3D11BackBufferFormat( DXGI_FORMAT format ) //------------------------------------------------------------------------------------- -DXGI_FORMAT CD3DSettingsDlg::GetSelectedD3D11BackBufferFormat() +DXGI_FORMAT CD3DSettingsDlg::GetSelectedD3D11BackBufferFormat() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); return ( DXGI_FORMAT )PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddDepthStencilBufferFormat( D3DFORMAT format ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - - if( !pComboBox->ContainsItem( DXUTD3DFormatToString( format, TRUE ) ) ) - pComboBox->AddItem( DXUTD3DFormatToString( format, TRUE ), ULongToPtr( format ) ); -} - - -//------------------------------------------------------------------------------------- -D3DFORMAT CD3DSettingsDlg::GetSelectedDepthStencilBufferFormat() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - - return ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddMultisampleType( D3DMULTISAMPLE_TYPE type ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - - if( !pComboBox->ContainsItem( DXUTMultisampleTypeToString( type ) ) ) - pComboBox->AddItem( DXUTMultisampleTypeToString( type ), ULongToPtr( type ) ); -} - - -//------------------------------------------------------------------------------------- -D3DMULTISAMPLE_TYPE CD3DSettingsDlg::GetSelectedMultisampleType() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - - return ( D3DMULTISAMPLE_TYPE )PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddMultisampleQuality( DWORD dwQuality ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY ); - - WCHAR strQuality[50]; - swprintf_s( strQuality, 50, L"%d", dwQuality ); - - if( !pComboBox->ContainsItem( strQuality ) ) - pComboBox->AddItem( strQuality, ULongToPtr( dwQuality ) ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedMultisampleQuality() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY ); - - return PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11MultisampleCount( UINT Count ) +void CD3DSettingsDlg::AddD3D11MultisampleCount( _In_ UINT Count ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); WCHAR str[50]; swprintf_s( str, 50, L"%u", Count ); @@ -2516,21 +1373,21 @@ void CD3DSettingsDlg::AddD3D11MultisampleCount( UINT Count ) //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleCount() +UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleCount() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); return ( UINT )PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11MultisampleQuality( UINT Quality ) +void CD3DSettingsDlg::AddD3D11MultisampleQuality( _In_ UINT Quality ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); WCHAR strQuality[50]; - swprintf_s( strQuality, 50, L"%d", Quality ); + swprintf_s( strQuality, 50, L"%u", Quality ); if( !pComboBox->ContainsItem( strQuality ) ) pComboBox->AddItem( strQuality, ULongToPtr( Quality ) ); @@ -2538,129 +1395,140 @@ void CD3DSettingsDlg::AddD3D11MultisampleQuality( UINT Quality ) //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleQuality() +UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleQuality() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); return ( UINT )PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddVertexProcessingType( DWORD dwType ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING ); - - if( !pComboBox->ContainsItem( DXUTVertexProcessingTypeToString( dwType ) ) ) - pComboBox->AddItem( DXUTVertexProcessingTypeToString( dwType ), ULongToPtr( dwType ) ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedVertexProcessingType() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING ); - - return PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedPresentInterval() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL ); - - return PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedD3D11PresentInterval() +DWORD CD3DSettingsDlg::GetSelectedD3D11PresentInterval() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); return PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -bool CD3DSettingsDlg::GetSelectedDebugDeviceValue() +bool CD3DSettingsDlg::GetSelectedDebugDeviceValue() const { - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); + auto pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); return pCheckBox->GetChecked(); } -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::SetDeviceClip( bool bDeviceClip ) -{ - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_DEVICECLIP ); - pCheckBox->SetChecked( bDeviceClip ); -} - - -//------------------------------------------------------------------------------------- -bool CD3DSettingsDlg::IsDeviceClip() -{ - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_DEVICECLIP ); - return pCheckBox->GetChecked(); -} - //-------------------------------------------------------------------------------------- // Updates the resolution list for D3D11 //-------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::UpdateD3D11Resolutions() { - const DWORD dwWidth = g_DeviceSettings.d3d11.sd.BufferDesc.Width; const DWORD dwHeight = g_DeviceSettings.d3d11.sd.BufferDesc.Height; // DXUTSETTINGSDLG_D3D11_RESOLUTION - CDXUTComboBox* pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); + auto pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); pResolutionComboBox->RemoveAllItems(); - CD3D11EnumOutputInfo* pOutputInfo = GetCurrentD3D11OutputInfo(); - if( pOutputInfo == NULL ) + auto pOutputInfo = GetCurrentD3D11OutputInfo(); + if( !pOutputInfo ) return E_FAIL; - bool bShowAll = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL )->GetChecked(); + bool bWindowed = IsWindowed(); + if ( !bWindowed ) + { + auto pShowAllCB = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL ); + bool bShowAll = pShowAllCB->GetChecked(); - // Get the desktop aspect ratio - DXGI_MODE_DESC dmDesktop; - DXUTGetDesktopResolution( g_DeviceSettings.d3d11.AdapterOrdinal, &dmDesktop.Width, &dmDesktop.Height ); - float fDesktopAspectRatio = dmDesktop.Width / ( float )dmDesktop.Height; + // Get the desktop aspect ratio + DXGI_MODE_DESC dmDesktop; + DXUTGetDesktopResolution(g_DeviceSettings.d3d11.AdapterOrdinal, &dmDesktop.Width, &dmDesktop.Height); + float fDesktopAspectRatio = dmDesktop.Width / (float) dmDesktop.Height; - for( int idm = 0; idm < pOutputInfo->displayModeList.GetSize(); idm++ ) - { - DXGI_MODE_DESC DisplayMode = pOutputInfo->displayModeList.GetAt( idm ); - float fAspect = ( float )DisplayMode.Width / ( float )DisplayMode.Height; + if ( !bShowAll && !DXUTIsWindowed() ) + { + float fAspect = (float) dwWidth / (float) dwHeight; + if ( fabsf(fDesktopAspectRatio - fAspect) >= 0.05f ) + { + // Our current fullscren resolution should be listed in the combo box despite the aspect ratio + pShowAllCB->SetChecked(true); + bShowAll = true; + } + } - if( DisplayMode.Format == g_DeviceSettings.d3d11.sd.BufferDesc.Format ) + for (size_t idm = 0; idm < pOutputInfo->displayModeList.size(); idm++) { - // If "Show All" is not checked, then hide all resolutions - // that don't match the aspect ratio of the desktop resolution - if( bShowAll || ( !bShowAll && fabsf( fDesktopAspectRatio - fAspect ) < 0.05f ) ) + auto DisplayMode = pOutputInfo->displayModeList[idm]; + float fAspect = (float) DisplayMode.Width / (float) DisplayMode.Height; + + if (DisplayMode.Format == g_DeviceSettings.d3d11.sd.BufferDesc.Format) { - AddD3D11Resolution( DisplayMode.Width, DisplayMode.Height ); + // If "Show All" is not checked, then hide all resolutions + // that don't match the aspect ratio of the desktop resolution + if (bShowAll || (!bShowAll && fabsf(fDesktopAspectRatio - fAspect) < 0.05f)) + { + AddD3D11Resolution(DisplayMode.Width, DisplayMode.Height); + } } } } + else + { + pResolutionComboBox->RemoveAllItems(); + AddD3D11Resolution( dwWidth, dwHeight ); + } + + pResolutionComboBox->SetSelectedByData(ULongToPtr(MAKELONG(dwWidth, dwHeight))); + OnD3D11ResolutionChanged(); - const DWORD dwCurResolution = MAKELONG( g_DeviceSettings.d3d11.sd.BufferDesc.Width, - g_DeviceSettings.d3d11.sd.BufferDesc.Height ); + return S_OK; +} - pResolutionComboBox->SetSelectedByData( ULongToPtr( dwCurResolution ) ); +//-------------------------------------------------------------------------------------- +// Updates the refresh list for D3D11 +//-------------------------------------------------------------------------------------- +HRESULT CD3DSettingsDlg::UpdateD3D11RefreshRates() +{ + const DWORD dwWidth = g_DeviceSettings.d3d11.sd.BufferDesc.Width; + const DWORD dwHeight = g_DeviceSettings.d3d11.sd.BufferDesc.Height; + DXGI_FORMAT backBuffer = g_DeviceSettings.d3d11.sd.BufferDesc.Format; + const DXGI_RATIONAL RefreshRate = g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate; + + auto pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + for( UINT i = 0; i < pRefreshRateComboBox->GetNumItems(); ++i ) + { + auto pRefreshRate = reinterpret_cast( pRefreshRateComboBox->GetItemData( i ) ); + delete pRefreshRate; + } + pRefreshRateComboBox->RemoveAllItems(); bool bWindowed = IsWindowed(); if( bWindowed ) { - pResolutionComboBox->RemoveAllItems(); - AddD3D11Resolution( dwWidth, dwHeight ); + DXGI_RATIONAL def; + def.Denominator = def.Numerator = 0; + AddD3D11RefreshRate(def); + } + else + { + auto pD3DEnum = DXUTGetD3D11Enumeration(); + if ( !pD3DEnum ) + return E_POINTER; - pResolutionComboBox->SetSelectedByData( ULongToPtr( MAKELONG( dwWidth, dwHeight ) ) ); + auto pOutputInfo = pD3DEnum->GetOutputInfo( g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.Output ); + if ( !pOutputInfo ) + return E_POINTER; + for( auto it = pOutputInfo->displayModeList.cbegin(); it != pOutputInfo->displayModeList.cend(); ++it ) + { + if ( it->Width == dwWidth && it->Height == dwHeight && it->Format == backBuffer ) + AddD3D11RefreshRate( it->RefreshRate ); + } + SetSelectedD3D11RefreshRate( RefreshRate ); } return S_OK; @@ -2669,25 +1537,25 @@ HRESULT CD3DSettingsDlg::UpdateD3D11Resolutions() // //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11DeviceType( D3D_DRIVER_TYPE devType ) +void CD3DSettingsDlg::AddD3D11DeviceType( _In_ D3D_DRIVER_TYPE devType ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - if( !pComboBox->ContainsItem( DXUTD3DX11DeviceTypeToString( devType ) ) ) - pComboBox->AddItem( DXUTD3DX11DeviceTypeToString( devType ), ULongToPtr( devType ) ); + if( !pComboBox->ContainsItem( DXUTDeviceTypeToString( devType ) ) ) + pComboBox->AddItem( DXUTDeviceTypeToString( devType ), ULongToPtr( devType ) ); } //------------------------------------------------------------------------------------- -D3D_DRIVER_TYPE CD3DSettingsDlg::GetSelectedD3D11DeviceType() +D3D_DRIVER_TYPE CD3DSettingsDlg::GetSelectedD3D11DeviceType() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); return ( D3D_DRIVER_TYPE )PtrToUlong( pComboBox->GetSelectedData() ); } -void CD3DSettingsDlg::UpdateModeChangeTimeoutText( int nSecRemaining ) +void CD3DSettingsDlg::UpdateModeChangeTimeoutText( _In_ int nSecRemaining ) { const WCHAR StrTimeout[] = L"Reverting to previous display settings in %d seconds"; const DWORD CchBuf = sizeof( StrTimeout ) / sizeof( WCHAR ) + 16; @@ -2695,52 +1563,14 @@ void CD3DSettingsDlg::UpdateModeChangeTimeoutText( int nSecRemaining ) swprintf_s( buf, CchBuf, StrTimeout, nSecRemaining ); - CDXUTStatic* pStatic = m_RevertModeDialog.GetStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT ); + auto pStatic = m_RevertModeDialog.GetStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT ); pStatic->SetText( buf ); } -//-------------------------------------------------------------------------------------- -// Returns the string for the given DXUTDeviceVersion. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTAPIVersionToString( DXUTDeviceVersion version ) -{ - switch( version ) - { - case DXUT_D3D9_DEVICE: - return L"Direct3D 9"; - case DXUT_D3D11_DEVICE: - return L"Direct3D 11"; - default: - return L"Unknown version"; - } -} - - -//-------------------------------------------------------------------------------------- -// Returns the string for the given D3DDEVTYPE. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTD3DDeviceTypeToString( D3DDEVTYPE devType ) -{ - switch( devType ) - { - case D3DDEVTYPE_HAL: - return L"D3DDEVTYPE_HAL"; - case D3DDEVTYPE_SW: - return L"D3DDEVTYPE_SW"; - case D3DDEVTYPE_REF: - return L"D3DDEVTYPE_REF"; - default: - return L"Unknown devType"; - } -} - - - - //-------------------------------------------------------------------------------------- // Returns the string for the given D3D_DRIVER_TYPE. //-------------------------------------------------------------------------------------- -WCHAR* DXUTD3DX11DeviceTypeToString( D3D_DRIVER_TYPE devType ) +const WCHAR* DXUTDeviceTypeToString( _In_ D3D_DRIVER_TYPE devType ) { switch( devType ) { @@ -2758,96 +1588,3 @@ WCHAR* DXUTD3DX11DeviceTypeToString( D3D_DRIVER_TYPE devType ) } -//-------------------------------------------------------------------------------------- -// Returns the string for the given D3DMULTISAMPLE_TYPE. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTMultisampleTypeToString( D3DMULTISAMPLE_TYPE MultiSampleType ) -{ - switch( MultiSampleType ) - { - case D3DMULTISAMPLE_NONE: - return L"D3DMULTISAMPLE_NONE"; - case D3DMULTISAMPLE_NONMASKABLE: - return L"D3DMULTISAMPLE_NONMASKABLE"; - case D3DMULTISAMPLE_2_SAMPLES: - return L"D3DMULTISAMPLE_2_SAMPLES"; - case D3DMULTISAMPLE_3_SAMPLES: - return L"D3DMULTISAMPLE_3_SAMPLES"; - case D3DMULTISAMPLE_4_SAMPLES: - return L"D3DMULTISAMPLE_4_SAMPLES"; - case D3DMULTISAMPLE_5_SAMPLES: - return L"D3DMULTISAMPLE_5_SAMPLES"; - case D3DMULTISAMPLE_6_SAMPLES: - return L"D3DMULTISAMPLE_6_SAMPLES"; - case D3DMULTISAMPLE_7_SAMPLES: - return L"D3DMULTISAMPLE_7_SAMPLES"; - case D3DMULTISAMPLE_8_SAMPLES: - return L"D3DMULTISAMPLE_8_SAMPLES"; - case D3DMULTISAMPLE_9_SAMPLES: - return L"D3DMULTISAMPLE_9_SAMPLES"; - case D3DMULTISAMPLE_10_SAMPLES: - return L"D3DMULTISAMPLE_10_SAMPLES"; - case D3DMULTISAMPLE_11_SAMPLES: - return L"D3DMULTISAMPLE_11_SAMPLES"; - case D3DMULTISAMPLE_12_SAMPLES: - return L"D3DMULTISAMPLE_12_SAMPLES"; - case D3DMULTISAMPLE_13_SAMPLES: - return L"D3DMULTISAMPLE_13_SAMPLES"; - case D3DMULTISAMPLE_14_SAMPLES: - return L"D3DMULTISAMPLE_14_SAMPLES"; - case D3DMULTISAMPLE_15_SAMPLES: - return L"D3DMULTISAMPLE_15_SAMPLES"; - case D3DMULTISAMPLE_16_SAMPLES: - return L"D3DMULTISAMPLE_16_SAMPLES"; - default: - return L"Unknown Multisample Type"; - } -} - - -//-------------------------------------------------------------------------------------- -// Returns the string for the given vertex processing type -//-------------------------------------------------------------------------------------- -WCHAR* DXUTVertexProcessingTypeToString( DWORD vpt ) -{ - switch( vpt ) - { - case D3DCREATE_SOFTWARE_VERTEXPROCESSING: - return L"Software vertex processing"; - case D3DCREATE_MIXED_VERTEXPROCESSING: - return L"Mixed vertex processing"; - case D3DCREATE_HARDWARE_VERTEXPROCESSING: - return L"Hardware vertex processing"; - case D3DCREATE_PUREDEVICE: - return L"Pure hardware vertex processing"; - default: - return L"Unknown vertex processing type"; - } -} - - -//-------------------------------------------------------------------------------------- -// Returns the string for the given present interval. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTPresentIntervalToString( UINT pi ) -{ - switch( pi ) - { - case D3DPRESENT_INTERVAL_IMMEDIATE: - return L"D3DPRESENT_INTERVAL_IMMEDIATE"; - case D3DPRESENT_INTERVAL_DEFAULT: - return L"D3DPRESENT_INTERVAL_DEFAULT"; - case D3DPRESENT_INTERVAL_ONE: - return L"D3DPRESENT_INTERVAL_ONE"; - case D3DPRESENT_INTERVAL_TWO: - return L"D3DPRESENT_INTERVAL_TWO"; - case D3DPRESENT_INTERVAL_THREE: - return L"D3DPRESENT_INTERVAL_THREE"; - case D3DPRESENT_INTERVAL_FOUR: - return L"D3DPRESENT_INTERVAL_FOUR"; - default: - return L"Unknown PresentInterval"; - } -} - - diff --git a/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.h b/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.h index fee91f3a..45ffdb5b 100644 --- a/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.h +++ b/FriedLiver/Source/DXUT/Optional/DXUTsettingsdlg.h @@ -1,16 +1,18 @@ //-------------------------------------------------------------------------------------- -// File: DXUTSettingsDlg.cpp +// File: DXUTSettingsDlg.h // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_SETTINGS_H -#define DXUT_SETTINGS_H //-------------------------------------------------------------------------------------- // Header Includes //-------------------------------------------------------------------------------------- #include "DXUTgui.h" + //-------------------------------------------------------------------------------------- // Control IDs //-------------------------------------------------------------------------------------- @@ -21,27 +23,7 @@ #define DXUTSETTINGSDLG_DEVICE_TYPE 4 #define DXUTSETTINGSDLG_WINDOWED 5 #define DXUTSETTINGSDLG_FULLSCREEN 6 -#define DXUTSETTINGSDLG_ADAPTER_FORMAT 7 -#define DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL 8 -#define DXUTSETTINGSDLG_RESOLUTION 9 -#define DXUTSETTINGSDLG_RESOLUTION_LABEL 10 -#define DXUTSETTINGSDLG_REFRESH_RATE 11 -#define DXUTSETTINGSDLG_REFRESH_RATE_LABEL 12 -#define DXUTSETTINGSDLG_BACK_BUFFER_FORMAT 13 -#define DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL 14 -#define DXUTSETTINGSDLG_DEPTH_STENCIL 15 -#define DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL 16 -#define DXUTSETTINGSDLG_MULTISAMPLE_TYPE 17 -#define DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL 18 -#define DXUTSETTINGSDLG_MULTISAMPLE_QUALITY 19 -#define DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL 20 -#define DXUTSETTINGSDLG_VERTEX_PROCESSING 21 -#define DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL 22 -#define DXUTSETTINGSDLG_PRESENT_INTERVAL 23 -#define DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL 24 -#define DXUTSETTINGSDLG_DEVICECLIP 25 #define DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL 26 -#define DXUTSETTINGSDLG_API_VERSION 27 #define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT 28 #define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL 29 #define DXUTSETTINGSDLG_D3D11_RESOLUTION 30 @@ -65,169 +47,109 @@ #define DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT 60 #define DXUTSETTINGSDLG_WINDOWED_GROUP 0x0100 -#define TOTAL_FEATURE_LEVLES 6 +#define TOTAL_FEATURE_LEVELS 9 + //-------------------------------------------------------------------------------------- // Dialog for selection of device settings // Use DXUTGetD3DSettingsDialog() to access global instance -// To control the contents of the dialog, use the CD3D9Enumeration class. +// To control the contents of the dialog, use the CD3D11Enumeration class. //-------------------------------------------------------------------------------------- class CD3DSettingsDlg { public: - CD3DSettingsDlg(); - ~CD3DSettingsDlg(); - - void Init( CDXUTDialogResourceManager* pManager ); - void Init( CDXUTDialogResourceManager* pManager, LPCWSTR szControlTextureFileName ); - void Init( CDXUTDialogResourceManager* pManager, LPCWSTR pszControlTextureResourcename, - HMODULE hModule ); - - HRESULT Refresh(); - void OnRender( float fElapsedTime ); - void OnRender9( float fElapsedTime ); - void OnRender10( float fElapsedTime ); - void OnRender11( float fElapsedTime ); - - HRESULT OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnD3D9ResetDevice(); - void OnD3D9LostDevice(); - void OnD3D9DestroyDevice(); - - HRESULT OnD3D11CreateDevice( ID3D11Device* pd3dDevice ); - HRESULT OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); - void OnD3D11DestroyDevice(); - - CDXUTDialog* GetDialogControl() - { - return &m_Dialog; - } - bool IsActive() - { - return m_bActive; - } - void SetActive( bool bActive ) - { - m_bActive = bActive; if( bActive ) Refresh(); - } - void ShowControlSet( DXUTDeviceVersion ver ); - - LRESULT MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - -protected: - friend CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); - - void CreateControls(); - HRESULT SetDeviceSettingsFromUI(); - void SetSelectedD3D11RefreshRate( DXGI_RATIONAL RefreshRate ); - HRESULT UpdateD3D11Resolutions(); - - void OnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl ); - static void WINAPI StaticOnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserData ); - static void WINAPI StaticOnModeChangeTimer( UINT nIDEvent, void* pUserContext ); + CD3DSettingsDlg() noexcept; + ~CD3DSettingsDlg(); - CD3D9EnumAdapterInfo* GetCurrentAdapterInfo(); - CD3D9EnumDeviceInfo* GetCurrentDeviceInfo(); - CD3D9EnumDeviceSettingsCombo* GetCurrentDeviceSettingsCombo(); + void Init( _In_ CDXUTDialogResourceManager* pManager ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR szControlTextureFileName ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR pszControlTextureResourcename, + _In_ HMODULE hModule ); - CD3D11EnumAdapterInfo* GetCurrentD3D11AdapterInfo(); - CD3D11EnumDeviceInfo* GetCurrentD3D11DeviceInfo(); - CD3D11EnumOutputInfo* GetCurrentD3D11OutputInfo(); - CD3D11EnumDeviceSettingsCombo* GetCurrentD3D11DeviceSettingsCombo(); + HRESULT Refresh(); + void OnRender( _In_ float fElapsedTime ); - void AddAPIVersion( DXUTDeviceVersion version ); - DXUTDeviceVersion GetSelectedAPIVersion(); + HRESULT OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice ); + HRESULT OnD3D11ResizedSwapChain( _In_ ID3D11Device* pd3dDevice, + _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); + void OnD3D11DestroyDevice(); - void AddAdapter( const WCHAR* strDescription, UINT iAdapter ); - UINT GetSelectedAdapter(); - - void AddDeviceType( D3DDEVTYPE devType ); - D3DDEVTYPE GetSelectedDeviceType(); - - void SetWindowed( bool bWindowed ); - bool IsWindowed(); - - void AddAdapterFormat( D3DFORMAT format ); - D3DFORMAT GetSelectedAdapterFormat(); - - void AddResolution( DWORD dwWidth, DWORD dwHeight ); - void GetSelectedResolution( DWORD* pdwWidth, DWORD* pdwHeight ); + CDXUTDialog* GetDialogControl() { return &m_Dialog; } + bool IsActive() const { return m_bActive; } + void SetActive( _In_ bool bActive ) + { + m_bActive = bActive; + if( bActive ) Refresh(); + } - void AddRefreshRate( DWORD dwRate ); - DWORD GetSelectedRefreshRate(); + LRESULT MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); - void AddBackBufferFormat( D3DFORMAT format ); - D3DFORMAT GetSelectedBackBufferFormat(); +protected: + friend CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); - void AddDepthStencilBufferFormat( D3DFORMAT format ); - D3DFORMAT GetSelectedDepthStencilBufferFormat(); + void CreateControls(); + void SetSelectedD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ); + HRESULT UpdateD3D11Resolutions(); + HRESULT UpdateD3D11RefreshRates(); - void AddMultisampleType( D3DMULTISAMPLE_TYPE type ); - D3DMULTISAMPLE_TYPE GetSelectedMultisampleType(); + void OnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl ); - void AddMultisampleQuality( DWORD dwQuality ); - DWORD GetSelectedMultisampleQuality(); + static void WINAPI StaticOnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl, _In_opt_ void* pUserData ); + static void WINAPI StaticOnModeChangeTimer( _In_ UINT nIDEvent, _In_opt_ void* pUserContext ); - void AddVertexProcessingType( DWORD dwType ); - DWORD GetSelectedVertexProcessingType(); + CD3D11EnumAdapterInfo* GetCurrentD3D11AdapterInfo() const; + CD3D11EnumDeviceInfo* GetCurrentD3D11DeviceInfo() const; + CD3D11EnumOutputInfo* GetCurrentD3D11OutputInfo() const; + CD3D11EnumDeviceSettingsCombo* GetCurrentD3D11DeviceSettingsCombo() const; - DWORD GetSelectedPresentInterval(); + void AddAdapter( _In_z_ const WCHAR* strDescription, _In_ UINT iAdapter ); + UINT GetSelectedAdapter() const; - void SetDeviceClip( bool bDeviceClip ); - bool IsDeviceClip(); + void SetWindowed( _In_ bool bWindowed ); + bool IsWindowed() const; // D3D11 - void AddD3D11DeviceType( D3D_DRIVER_TYPE devType ); - D3D_DRIVER_TYPE GetSelectedD3D11DeviceType(); + void AddD3D11DeviceType( _In_ D3D_DRIVER_TYPE devType ); + D3D_DRIVER_TYPE GetSelectedD3D11DeviceType() const; - void AddD3D11AdapterOutput( const WCHAR* strName, UINT nOutput ); - UINT GetSelectedD3D11AdapterOutput(); + void AddD3D11AdapterOutput( _In_z_ const WCHAR* strName, _In_ UINT nOutput ); + UINT GetSelectedD3D11AdapterOutput() const; - void AddD3D11Resolution( DWORD dwWidth, DWORD dwHeight ); - void GetSelectedD3D11Resolution( DWORD* pdwWidth, DWORD* pdwHeight ); + void AddD3D11Resolution( _In_ DWORD dwWidth, _In_ DWORD dwHeight ); + void GetSelectedD3D11Resolution( _Out_ DWORD* pdwWidth, _Out_ DWORD* pdwHeight ) const; - void AddD3D11FeatureLevel(D3D_FEATURE_LEVEL); - D3D_FEATURE_LEVEL GetSelectedFeatureLevel(); + void AddD3D11FeatureLevel( _In_ D3D_FEATURE_LEVEL fl ); + D3D_FEATURE_LEVEL GetSelectedFeatureLevel() const; - void AddD3D11RefreshRate( DXGI_RATIONAL RefreshRate ); - DXGI_RATIONAL GetSelectedD3D11RefreshRate(); + void AddD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ); + DXGI_RATIONAL GetSelectedD3D11RefreshRate() const; - void AddD3D11BackBufferFormat( DXGI_FORMAT format ); - DXGI_FORMAT GetSelectedD3D11BackBufferFormat(); - - void AddD3D11MultisampleCount( UINT count ); - UINT GetSelectedD3D11MultisampleCount(); - - void AddD3D11MultisampleQuality( UINT Quality ); - UINT GetSelectedD3D11MultisampleQuality(); - - DWORD GetSelectedD3D11PresentInterval(); - bool GetSelectedDebugDeviceValue(); + void AddD3D11BackBufferFormat( _In_ DXGI_FORMAT format ); + DXGI_FORMAT GetSelectedD3D11BackBufferFormat() const; + void AddD3D11MultisampleCount( _In_ UINT count ); + UINT GetSelectedD3D11MultisampleCount() const; + void AddD3D11MultisampleQuality( _In_ UINT Quality ); + UINT GetSelectedD3D11MultisampleQuality() const; + DWORD GetSelectedD3D11PresentInterval() const; + bool GetSelectedDebugDeviceValue() const; + HRESULT OnD3D11ResolutionChanged (); - HRESULT OnAPIVersionChanged( bool bRefresh=false ); HRESULT OnFeatureLevelChanged(); HRESULT OnAdapterChanged(); HRESULT OnDeviceTypeChanged(); HRESULT OnWindowedFullScreenChanged(); HRESULT OnAdapterOutputChanged(); - HRESULT OnAdapterFormatChanged(); - HRESULT OnResolutionChanged(); HRESULT OnRefreshRateChanged(); HRESULT OnBackBufferFormatChanged(); - HRESULT OnDepthStencilBufferFormatChanged(); HRESULT OnMultisampleTypeChanged(); HRESULT OnMultisampleQualityChanged(); - HRESULT OnVertexProcessingChanged(); HRESULT OnPresentIntervalChanged(); HRESULT OnDebugDeviceChanged(); - HRESULT OnDeviceClipChanged(); - void UpdateModeChangeTimeoutText( int nSecRemaining ); + void UpdateModeChangeTimeoutText( _In_ int nSecRemaining ); - IDirect3DStateBlock9* m_pStateBlock; CDXUTDialog* m_pActiveDialog; CDXUTDialog m_Dialog; CDXUTDialog m_RevertModeDialog; @@ -235,14 +157,9 @@ class CD3DSettingsDlg UINT m_nIDEvent; bool m_bActive; - D3D_FEATURE_LEVEL m_Levels[TOTAL_FEATURE_LEVLES]; + D3D_FEATURE_LEVEL m_Levels[TOTAL_FEATURE_LEVELS]; }; CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); - - - -#endif - diff --git a/FriedLiver/Source/DXUT/Optional/ImeUi.cpp b/FriedLiver/Source/DXUT/Optional/ImeUi.cpp index 912c6d6a..d23ceee4 100644 --- a/FriedLiver/Source/DXUT/Optional/ImeUi.cpp +++ b/FriedLiver/Source/DXUT/Optional/ImeUi.cpp @@ -2,19 +2,22 @@ // File: ImeUi.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "dxut.h" #include "ImeUi.h" #include #include #include -#include // Ignore typecast warnings #pragma warning( disable : 4312 ) #pragma warning( disable : 4244 ) #pragma warning( disable : 4311 ) +#pragma prefast( disable : 28159, "GetTickCount() is fine for a blinking cursor" ) #define MAX_CANDIDATE_LENGTH 256 #define COUNTOF(a) ( sizeof( a ) / sizeof( ( a )[0] ) ) @@ -61,7 +64,7 @@ static IMEUI_APPEARANCE gSkinIME = 24, // symbolHeight; 0xa0, // symbolTranslucence; 0, // symbolPlacement; - NULL, // symbolFont; + nullptr, // symbolFont; 0xffffffff, // candColorBase; 0xff000000, // candColorBorder; 0, // candColorText; @@ -121,14 +124,15 @@ FAR* LPINPUTCONTEXT2; class CDisableCicero { public: - CDisableCicero() : m_ptim( NULL ), - m_bComInit( false ) - { - } - ~CDisableCicero() - { - Uninitialize(); - } + CDisableCicero() noexcept : + m_ptim( nullptr ), + m_bComInit( false ) + {} + ~CDisableCicero() + { + Uninitialize(); + } + void Initialize() { if( m_bComInit ) @@ -136,12 +140,12 @@ class CDisableCicero return; } HRESULT hr; - hr = CoInitializeEx( NULL, COINIT_APARTMENTTHREADED ); + hr = CoInitializeEx( nullptr, COINIT_APARTMENTTHREADED ); if( SUCCEEDED( hr ) ) { m_bComInit = true; hr = CoCreateInstance( CLSID_TF_ThreadMgr, - NULL, + nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfThreadMgr ), ( void** )&m_ptim ); @@ -152,7 +156,7 @@ class CDisableCicero if( m_ptim ) { m_ptim->Release(); - m_ptim = NULL; + m_ptim = nullptr; } if( m_bComInit ) CoUninitialize(); @@ -161,13 +165,13 @@ class CDisableCicero void DisableCiceroOnThisWnd( HWND hwnd ) { - if( m_ptim == NULL ) + if( !m_ptim ) return; ITfDocumentMgr* pdimPrev; // the dim that is associated previously. - // Associate NULL dim to the window. + // Associate nullptr dim to the window. // When this window gets the focus, Cicero does not work and IMM32 IME // will be activated. - if( SUCCEEDED( m_ptim->AssociateFocus( hwnd, NULL, &pdimPrev ) ) ) + if( SUCCEEDED( m_ptim->AssociateFocus( hwnd, nullptr, &pdimPrev ) ) ) { if( pdimPrev ) pdimPrev->Release(); @@ -255,7 +259,7 @@ static DWORD g_hCompChar; static int g_iCandListIndexBase; static DWORD g_dwImeUiFlags = IMEUI_FLAG_SUPPORT_CARET; static bool g_bUILessMode = false; -static HMODULE g_hImmDll = NULL; +static HMODULE g_hImmDll = nullptr; #define IsNT() (g_osi.dwPlatformId == VER_PLATFORM_WIN32_NT) @@ -289,36 +293,29 @@ static double lastSwirl; static HKL g_hklCurrent = 0; static UINT g_uCodePage = 0; -static LPTSTR g_aszIndicator[] = +static LPCTSTR g_aszIndicator[] = { TEXT( "A" ), -#ifdef UNICODE - L"\x7B80", - L"\x7E41", - L"\xac00", - L"\x3042", -#else - "\xd6\xd0", - "\xa4\xa4", - "\xb0\xa1", - "\x82\xa0", -#endif + L"\x7B80", + L"\x7E41", + L"\xac00", + L"\x3042", }; -static LPTSTR g_pszIndicatior = g_aszIndicator[0]; +static LPCTSTR g_pszIndicatior = g_aszIndicator[0]; -static void GetReadingString( HWND hWnd ); -static DWORD GetImeId( UINT uIndex = 0 ); +static void GetReadingString( _In_ HWND hWnd ); +static DWORD GetImeId( _In_ UINT uIndex = 0 ); static void CheckToggleState(); static void DrawImeIndicator(); static void DrawCandidateList(); -static void DrawCompositionString( bool bDrawCompAttr ); -static void GetReadingWindowOrientation( DWORD dwId ); +static void DrawCompositionString( _In_ bool bDrawCompAttr ); +static void GetReadingWindowOrientation( _In_ DWORD dwId ); static void OnInputLangChangeWorker(); static void OnInputLangChange(); static void SetImeApi(); static void CheckInputLocale(); -static void SetSupportLevel( DWORD dwImeLevel ); -void ImeUi_SetSupportLevel( DWORD dwImeLevel ); +static void SetSupportLevel( _In_ DWORD dwImeLevel ); +void ImeUi_SetSupportLevel( _In_ DWORD dwImeLevel ); // @@ -352,15 +349,15 @@ class CTsfUiLessMode public ITfCompartmentEventSink { public: - CUIElementSink(); - ~CUIElementSink(); + CUIElementSink() noexcept; + virtual ~CUIElementSink(); // IUnknown - STDMETHODIMP QueryInterface( REFIID riid, void** ppvObj ); - STDMETHODIMP_( ULONG ) - AddRef( void ); - STDMETHODIMP_( ULONG ) - Release( void ); + STDMETHODIMP QueryInterface( _In_ REFIID riid, _COM_Outptr_ void** ppvObj ); + STDMETHODIMP_( ULONG ) + AddRef(); + STDMETHODIMP_( ULONG ) + Release(); // ITfUIElementSink // Notifications for Reading Window events. We could process candidate as well, but we'll use IMM for simplicity sake. @@ -370,12 +367,12 @@ class CTsfUiLessMode // ITfInputProcessorProfileActivationSink // Notification for keyboard input locale change - STDMETHODIMP OnActivated( DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid, - REFGUID guidProfile, HKL hkl, DWORD dwFlags ); + STDMETHODIMP OnActivated( DWORD dwProfileType, LANGID langid, _In_ REFCLSID clsid, _In_ REFGUID catid, + _In_ REFGUID guidProfile, HKL hkl, DWORD dwFlags ); // ITfCompartmentEventSink // Notification for open mode (toggle state) change - STDMETHODIMP OnChange( REFGUID rguid ); + STDMETHODIMP OnChange( _In_ REFGUID rguid ); private: LONG _cRef; @@ -386,8 +383,8 @@ class CTsfUiLessMode static ITfUIElement* GetUIElement( DWORD dwUIElementId ); static BOOL GetCompartments( ITfCompartmentMgr** ppcm, ITfCompartment** ppTfOpenMode, ITfCompartment** ppTfConvMode ); - static BOOL SetupCompartmentSinks( BOOL bResetOnly = FALSE, ITfCompartment* pTfOpenMode = NULL, - ITfCompartment* ppTfConvMode = NULL ); + static BOOL SetupCompartmentSinks( BOOL bResetOnly = FALSE, ITfCompartment* pTfOpenMode = nullptr, + ITfCompartment* ppTfConvMode = nullptr ); static ITfThreadMgrEx* m_tm; static DWORD m_dwUIElementSinkCookie; @@ -397,9 +394,7 @@ class CTsfUiLessMode static CUIElementSink* m_TsfSink; static int m_nCandidateRefCount; // Some IME shows multiple candidate lists but the Library doesn't support multiple candidate list. // So track open / close events to make sure the candidate list opened last is shown. - CTsfUiLessMode() - { - } // this class can't be instanciated + CTsfUiLessMode() = default; // this class can't be instanciated public: static BOOL SetupSinks(); @@ -414,8 +409,8 @@ DWORD CTsfUiLessMode::m_dwUIElementSinkCookie = TF_INV DWORD CTsfUiLessMode::m_dwAlpnSinkCookie = TF_INVALID_COOKIE; DWORD CTsfUiLessMode::m_dwOpenModeSinkCookie = TF_INVALID_COOKIE; DWORD CTsfUiLessMode::m_dwConvModeSinkCookie = TF_INVALID_COOKIE; -CTsfUiLessMode::CUIElementSink* CTsfUiLessMode::m_TsfSink = NULL; -int CTsfUiLessMode::m_nCandidateRefCount = NULL; +CTsfUiLessMode::CUIElementSink* CTsfUiLessMode::m_TsfSink = nullptr; +int CTsfUiLessMode::m_nCandidateRefCount = 0; static unsigned long _strtoul( LPCSTR psz, LPTSTR*, int ) { @@ -452,282 +447,8 @@ static unsigned long _strtoul( LPCSTR psz, LPTSTR*, int ) return ulRet; } -#ifdef UNICODE -#define GetCharCount(psz) lstrlen(psz) +#define GetCharCount(psz) (int)wcslen(psz) #define GetCharCountFromBytes(psz,iBytes) (iBytes) -static void AW_SendCompString() -{ - int i, iLen; - if ( ImeUiCallback_OnChar ) - { - for ( i = 0; g_szCompositionString[i]; i++ ) - { - ImeUiCallback_OnChar( g_szCompositionString[i] ); - } - return; - } - - BYTE szCompStr[COUNTOF(g_szCompositionString) * 2]; - iLen = WideCharToMultiByte(g_uCodePage, 0, g_szCompositionString, -1, - (LPSTR)szCompStr, COUNTOF(szCompStr), NULL, NULL) - 1; // don't need to send NUL terminator; - for (i = 0; i < iLen; i++) - { - SendKeyMsg(g_hwndCurr, WM_CHAR, szCompStr[i]); - } -} - -// The following AW_Imm* functions are there to support Win95/98 first version. -// They can be deleted if the game doesn't supports them (i.e. games requires Win98 SE or later). -static DWORD AW_GetCandidateList(HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList) -{ - DWORD dwBufLen = ImmGetCandidateListA( himc, dwIndex, NULL, 0 ); - if (dwBufLen) - { - LPCANDIDATELIST pCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(dwBufLen); - if (pCandList) { - dwBufLen = ImmGetCandidateListA( himc, dwIndex, pCandList, dwBufLen ); - if (dwBufLen) { - int i; - int wideBufLen = 0; - for (i = 0; i < (int)pCandList->dwCount; i++) { - wideBufLen += MultiByteToWideChar(g_uCodePage, 0, (LPSTR)pCandList + pCandList->dwOffset[i], -1, NULL, 0) * sizeof(WCHAR); - } - wideBufLen += pCandList->dwOffset[0]; - *ppCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(wideBufLen); - LPCANDIDATELIST pCandListW = *ppCandList; - memcpy(pCandListW, pCandList, pCandList->dwOffset[0]); - LPWSTR pwz = (LPWSTR)((LPSTR)pCandListW + pCandList->dwOffset[0]); - for (i = 0; i < (int)pCandList->dwCount; i++) { - pCandListW->dwOffset[i] = (LPSTR)pwz - (LPSTR)pCandListW; - pwz += MultiByteToWideChar(g_uCodePage, 0, (LPSTR)pCandList + pCandList->dwOffset[i], -1, pwz, 256); - } - dwBufLen = wideBufLen; - } - ImeUiCallback_Free(pCandList); - } - } - return dwBufLen; -} - -static LONG WINAPI AW_ImmGetCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen) -{ - char pszMb[COUNTOF(g_szCompositionString) * 2]; - DWORD dwRet = ImmGetCompositionStringA(himc, dwIndex, pszMb, sizeof(pszMb)); - switch (dwIndex) { - case GCS_RESULTSTR: - case GCS_COMPSTR: - if (dwRet) { - pszMb[dwRet] = 0; - dwRet = (DWORD)MultiByteToWideChar(g_uCodePage, 0, pszMb, -1, (LPWSTR)lpBuf, dwBufLen); - if (dwRet) { - // Note that ImmGetCompositionString() returns number of bytes copied, regardless of the width of character. - dwRet = (dwRet - 1) * sizeof(WCHAR); - } - } - break; - case GCS_CURSORPOS: - dwRet /= 2; - break; - case GCS_COMPATTR: { - char pszMb2[COUNTOF(g_szCompositionString) * 2]; - DWORD dwRet2 = ImmGetCompositionStringA(himc, GCS_COMPSTR, pszMb2, sizeof(pszMb2)); - if (!dwRet2) { - dwRet2 = ImmGetCompositionStringA(himc, GCS_RESULTSTR, pszMb2, sizeof(pszMb2)); - if (!dwRet2) { - return 0; - } - } - char* pOut = (char*)lpBuf; - for (DWORD i = 0; i < dwRet; i++) { - *pOut++ = pszMb[i]; // copy attribute - if (_IsLeadByte(pszMb2[i])) - i++; - } - dwRet = pOut - (char*)lpBuf; - } - break; - } - return dwRet; -} - -#else // !UNICODE -// returns number of characters from number of bytes -static int GetCharCountFromBytes( LPCSTR pszString, int iBytes ) -{ - int iCount = 0; - int i; - for( i = 0; pszString[i] && i < iBytes; i++ ) - { - iCount++; - if( _IsLeadByte(pszString[i]) ) - i++; - } - if( i != iBytes ) - iCount = -iCount; // indicate error - iBytes specifies wrong boundary (i.e. the last byte is leadbyte) - return iCount; -} - -static int GetCharCount( LPTSTR psz ) -{ - int i = 0; - while( *psz ) - { - if( _IsLeadByte(*psz) ) - { - psz++; - } - psz++; - i++; - } - return i; -} - -static DWORD WA_GetCandidateList( HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList ) -{ - DWORD dwBufLen = ImmGetCandidateListW( himc, dwIndex, NULL, 0 ); - if( dwBufLen ) - { - LPCANDIDATELIST pCandList = ( LPCANDIDATELIST )ImeUiCallback_Malloc( dwBufLen ); - if( pCandList ) - { - dwBufLen = ImmGetCandidateListW( himc, dwIndex, pCandList, dwBufLen ); - if( dwBufLen ) - { - int i; - int mbBufLen = 0; - for( i = 0; i < ( int )pCandList->dwCount; i++ ) - { - mbBufLen += WideCharToMultiByte( g_uCodePage, 0, ( LPWSTR )( ( LPSTR )pCandList + - pCandList->dwOffset[i] ), -1, NULL, 0, - NULL, NULL ); - } - mbBufLen += pCandList->dwOffset[0]; - *ppCandList = ( LPCANDIDATELIST )ImeUiCallback_Malloc( mbBufLen ); - LPCANDIDATELIST pCandListA = *ppCandList; - memcpy( pCandListA, pCandList, pCandList->dwOffset[0] ); - LPSTR psz = ( LPSTR )pCandListA + pCandList->dwOffset[0]; - for( i = 0; i < ( int )pCandList->dwCount; i++ ) - { - pCandListA->dwOffset[i] = ( LPSTR )psz - ( LPSTR )pCandListA; - psz += WideCharToMultiByte( g_uCodePage, 0, ( LPWSTR )( ( LPSTR )pCandList + - pCandList->dwOffset[i] ), -1, psz, 256, - NULL, NULL ); - } - dwBufLen = mbBufLen; - } - ImeUiCallback_Free( pCandList ); - } - } - return dwBufLen; -} - -static LONG WINAPI WA_ImmGetCompositionString( HIMC himc, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen ) -{ - WCHAR pwzUc[COUNTOF(g_szCompositionString)]; - DWORD dwRet = ImmGetCompositionStringW( himc, dwIndex, pwzUc, sizeof( pwzUc ) ); - switch( dwIndex ) - { - case GCS_RESULTSTR: - case GCS_COMPSTR: - if( dwRet ) - { - pwzUc[dwRet / sizeof( WCHAR )] = 0; - dwRet = ( DWORD )WideCharToMultiByte( g_uCodePage, 0, pwzUc, -1, ( LPSTR )lpBuf, dwBufLen, NULL, - NULL ); - if( dwRet ) - { - dwRet = dwRet - 1; - } - } - break; - - case GCS_CURSORPOS: - { - WCHAR pwzUc2[COUNTOF(g_szCompositionString)]; - DWORD dwRet2 = ImmGetCompositionStringW( himc, GCS_COMPSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - dwRet2 = ImmGetCompositionStringW( himc, GCS_RESULTSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - return 0; - } - } - dwRet2 /= 2; - //The return value of WideCharToMultiByte() should probably be checked/asserted for success. - //bounds violation (overflow) 'pszMb[iRc]' - const int bufSize = COUNTOF(g_szCompositionString) * 2; - char pszMb[bufSize]; - int iRc = WideCharToMultiByte( g_uCodePage, 0, pwzUc2, dwRet2, pszMb, sizeof( pszMb ), NULL, NULL ); - assert( iRc > 0 ); //WideCharToMultiByte returns 0 if it failed, and it should *never* be negative in the first place - if( iRc >= bufSize ) //if we wrote more bytes than the length of the buffer, we need to terminate it - { - pszMb[ bufSize - 1] = 0; //0 terminate the end of the buffer - } - else - { - pszMb[ iRc ] = 0; - } - char* psz = pszMb; - for( dwRet2 = 0; dwRet2 != dwRet; dwRet2++ ) - { - if( _IsLeadByte( *psz ) ) - psz++; - psz++; - } - dwRet = psz - pszMb; - } - break; - - case GCS_COMPATTR: - { - WCHAR pwzUc2[COUNTOF(g_szCompositionString)]; - DWORD dwRet2 = ImmGetCompositionStringW( himc, GCS_COMPSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - dwRet2 = ImmGetCompositionStringW( himc, GCS_RESULTSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - return 0; - } - } - dwRet2 /= 2; - const int bufSize = COUNTOF(g_szCompositionString) * 2; - char pszMb[bufSize]; - int iRc = WideCharToMultiByte( g_uCodePage, 0, pwzUc2, dwRet2, pszMb, sizeof( pszMb ), NULL, NULL ); - assert( iRc > 0 ); //WideCharToMultiByte returns 0 if it failed, and it should *never* be negative in the first place - if( iRc >= bufSize ) //if we wrote more bytes than the length of the buffer, we need to terminate it - { - pszMb[ bufSize - 1] = 0; //0 terminate the end of the buffer - } - else - { - pszMb[ iRc ] = 0; - } - char* pSrc = ( char* )pwzUc; - char* pOut = ( char* )lpBuf; - for( char* psz = pszMb; *psz; psz++, pSrc++ ) - { - *pOut++ = *pSrc; // copy attribute - if( _IsLeadByte( *psz ) ) - { - *pOut++ = *pSrc; - psz++; - } - // buffer overrun protection, pOut is incremented in the loop, but not part of the - // loop invariant test. To make the code more readable we have a test rather than - // rolling this into the for stmt. - if( ( DWORD )( pOut - ( char* )lpBuf ) >= dwBufLen ) - break; - } - dwRet = pOut - ( char* )lpBuf; - } - break; - } - return dwRet; -} - -#endif // UNICODE static void ComposeCandidateLine( int index, LPCTSTR pszCandidate ) { @@ -746,17 +467,11 @@ static void ComposeCandidateLine( int index, LPCTSTR pszCandidate ) static void SendCompString() { - int i, iLen = lstrlen( g_szCompositionString ); + int i, iLen = (int)wcslen( g_szCompositionString ); if( ImeUiCallback_OnChar ) { LPCWSTR pwz; -#ifdef UNICODE - pwz = g_szCompositionString; -#else - WCHAR szUnicode[COUNTOF( g_szCompositionString ) ]; - pwz = szUnicode; - iLen = MultiByteToWideChar( g_uCodePage, 0, g_szCompositionString, -1, szUnicode, COUNTOF(szUnicode) ) - 1; -#endif + pwz = g_szCompositionString; for( i = 0; i < iLen; i++ ) { ImeUiCallback_OnChar( pwz[i] ); @@ -766,18 +481,14 @@ static void SendCompString() for( i = 0; i < iLen; i++ ) { SendKeyMsg( g_hwndCurr, WM_CHAR, -#ifdef UNICODE - (WPARAM)g_szCompositionString[i] -#else - ( WPARAM )( BYTE )g_szCompositionString[i] -#endif + (WPARAM)g_szCompositionString[i] ); } } static DWORD GetCandidateList( HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList ) { - DWORD dwBufLen = _ImmGetCandidateList( himc, dwIndex, NULL, 0 ); + DWORD dwBufLen = _ImmGetCandidateList( himc, dwIndex, nullptr, 0 ); if( dwBufLen ) { *ppCandList = ( LPCANDIDATELIST )ImeUiCallback_Malloc( dwBufLen ); @@ -833,7 +544,7 @@ static void CancelCompString( HWND hwnd, bool bUseBackSpace = true, int iNewStrL } // initialize composition string data. -static void InitCompStringData( void ) +static void InitCompStringData() { g_IMECursorBytes = 0; g_IMECursorChars = 0; @@ -856,7 +567,7 @@ static void DrawCaret( DWORD x, DWORD y, DWORD height ) // // Draw text in the edit box; // ImeUi_RenderUi(false, true); // paint the rest of IME UI; // -void ImeUi_RenderUI( bool bDrawCompAttr, bool bDrawOtherUi ) +void ImeUi_RenderUI( _In_ bool bDrawCompAttr, _In_ bool bDrawOtherUi ) { if( !g_bInitialized || !g_bImeEnabled || !g_CaretInfo.pFont ) return; @@ -936,7 +647,7 @@ static void DrawImeIndicator() swirl = 0; for( int t1 = 1; t1 < 16; t1++ ) { - float radian = 2.0f * 3.1415926f * ( t1 - 1 + ( bOn * swirl ) ) / 14.0f; + float radian = 2.0f * 3.1415926f * ( t1 - 1 + ( DWORD(bOn) * swirl ) ) / 14.0f; PieData[t1].sx = ( float )( PieData[0].sx + SizeOfPie / 2 * cos( radian ) ); PieData[t1].sy = ( float )( PieData[0].sy + SizeOfPie / 2 * sin( radian ) ); PieData[t1].rhw = 1.0f; @@ -987,9 +698,9 @@ static void DrawImeIndicator() if( gSkinIME.symbolFont ) { #ifdef DS2 - // save the font height here since DS2 shares editbox font and indicator font - DWORD _w, _h; - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h ); + // save the font height here since DS2 shares editbox font and indicator font + DWORD _w, _h; + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h ); #endif //DS2 // GOS deals height in points that is 1/72nd inch and assumes display device is 96dpi. @@ -1008,33 +719,33 @@ static void DrawImeIndicator() gSkinIME.symbolFont->DrawText( cszSymbol ); #ifdef DS2 - // revert the height. - g_CaretInfo.pFont->SetHeight( _h ); - - // Double-check: Confirm match by testing a range of font heights to find best fit - DWORD _h2; - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); - if ( _h2 < _h ) - { - for ( int i=1; _h2<_h && i<10; i++ ) - { - g_CaretInfo.pFont->SetHeight( _h+i ); - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); - } - } - else if ( _h2 > _h ) - { - for ( int i=1; _h2>_h && i<10; i++ ) - { - g_CaretInfo.pFont->SetHeight( _h-i ); - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); - } - } + // revert the height. + g_CaretInfo.pFont->SetHeight( _h ); + + // Double-check: Confirm match by testing a range of font heights to find best fit + DWORD _h2; + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); + if ( _h2 < _h ) + { + for ( int i=1; _h2<_h && i<10; i++ ) + { + g_CaretInfo.pFont->SetHeight( _h+i ); + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); + } + } + else if ( _h2 > _h ) + { + for ( int i=1; _h2>_h && i<10; i++ ) + { + g_CaretInfo.pFont->SetHeight( _h-i ); + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); + } + } #endif //DS2 } } -static void DrawCompositionString( bool bDrawCompAttr ) +static void DrawCompositionString( _In_ bool bDrawCompAttr ) { // Process timer for caret blink UINT uCurrentTime = GetTickCount(); @@ -1050,7 +761,7 @@ static void DrawCompositionString( bool bDrawCompAttr ) DWORD uDummy; - int len = lstrlen( g_szCompositionString ); + int len = (int)wcslen( g_szCompositionString ); DWORD bgX = g_CaretInfo.caretX; DWORD bgY = g_CaretInfo.caretY; @@ -1089,11 +800,6 @@ static void DrawCompositionString( bool bDrawCompAttr ) TCHAR szChar[3]; szChar[0] = g_szCompositionString[i]; szChar[1] = szChar[2] = 0; -#ifndef UNICODE - cType = 1 + ( ( _IsLeadByte(g_szCompositionString[i]) ) ? 1 : 0 ); - if( cType == 2 && g_szCompositionString[i + 1] ) // in case we have 0 in trailbyte, we don't count it. - szChar[1] = g_szCompositionString[i + 1]; -#endif bgX = bgXnext; TCHAR cSave = g_szCompositionString[i + cType]; g_szCompositionString[i + cType] = 0; @@ -1169,10 +875,6 @@ static void DrawCompositionString( bool bDrawCompAttr ) if( bWrite ) { *pszMlcs++ = g_szCompositionString[i]; -#ifndef UNICODE - if( cType == 2 ) - *pszMlcs++ = g_szCompositionString[i + 1]; -#endif } if( ( DWORD )i == g_IMECursorBytes ) { @@ -1214,7 +916,7 @@ static void DrawCompositionString( bool bDrawCompAttr ) { g_CaretInfo.pFont->SetPosition( x, y ); g_CaretInfo.pFont->DrawText( pszMlcs ); - pszMlcs += lstrlen( pszMlcs ) + 1; + pszMlcs += wcslen( pszMlcs ) + 1; x = g_CaretInfo.margins.left; y += hCompChar; } @@ -1231,6 +933,8 @@ static void DrawCompositionString( bool bDrawCompAttr ) static void DrawCandidateList() { + assert( g_CaretInfo.pFont != nullptr ); + _Analysis_assume_( g_CaretInfo.pFont != nullptr ); DWORD candX = g_dwCandX; DWORD candY = g_dwCandY; DWORD hCompChar = g_hCompChar; @@ -1267,7 +971,7 @@ static void DrawCandidateList() static DWORD uDigitWidth = 0; DWORD uSpaceWidth = 0; static DWORD uDigitWidthList[10]; - static CImeUiFont_Base* pPrevFont = NULL; + static CImeUiFont_Base* pPrevFont = nullptr; // find out the widest width of the digits if( pPrevFont != g_CaretInfo.pFont ) { @@ -1406,13 +1110,9 @@ static void DrawCandidateList() TCHAR szTemp[COUNTOF( g_szReadingString ) ]; if( g_iReadingError >= 0 ) { - StringCchCopy( szTemp, COUNTOF(szTemp), g_szReadingString ); + wcscpy_s( szTemp, COUNTOF(szTemp), g_szReadingString ); LPTSTR psz = szTemp + g_iReadingError; -#ifdef UNICODE - psz++; -#else - psz += ( _IsLeadByte( szTemp[g_iReadingError] ) ) ? 2 : 1; -#endif + psz++; *psz = 0; g_CaretInfo.pFont->GetTextExtent( szTemp, ( DWORD* )&iEnd, ( DWORD* )&iDummy ); TCHAR cSave = szTemp[ g_iReadingError ]; @@ -1477,7 +1177,7 @@ static void DrawCandidateList() int dx = candX + ( seperateLineX - candX - uDigitWidthList[nOneDigit] ) / 2; int dy = candY + largest.cy * i; - + g_CaretInfo.pFont->SetPosition( dx, dy ); g_CaretInfo.pFont->DrawText( szOneDigit ); g_CaretInfo.pFont->SetPosition( seperateLineX + dwMarginX, dy ); @@ -1519,6 +1219,9 @@ static void CloseCandidateList() // ProcessIMEMessages() // Processes IME related messages and acquire information // +#pragma warning(push) +#pragma warning( disable : 4616 6305 ) +_Use_decl_annotations_ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam, bool* trapped ) { HIMC himc; @@ -1559,7 +1262,8 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam TCHAR szCompStr[COUNTOF(g_szCompositionString)]; *trapped = true; - if( NULL == ( himc = _ImmGetContext( hWnd ) ) ) + himc = ImmGetContext( hWnd ); + if( !himc ) { break; } @@ -1571,7 +1275,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam COUNTOF( szCompStr ) ) / sizeof( TCHAR ); szCompStr[lRet] = 0; CancelCompString( g_hwndCurr, false, GetCharCount( szCompStr ) ); - StringCchCopy( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); + wcscpy_s( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); _SendCompString(); InitCompStringData(); } @@ -1590,14 +1294,14 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam // CancelCompString( g_hwndCurr, false, GetCharCount( szCompStr ) ); - StringCchCopy( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); + wcscpy_s( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); lRet = _ImmGetCompositionString( himc, GCS_COMPATTR, g_szCompAttrString, COUNTOF( g_szCompAttrString ) ); g_szCompAttrString[lRet] = 0; // Older CHT IME uses composition string for reading string if( GETLANG() == LANG_CHT && !GetImeId() ) { - int i, chars = lstrlen( g_szCompositionString ) / ( 3 - sizeof( TCHAR ) ); + int i, chars = (int)wcslen( g_szCompositionString ) / ( 3 - sizeof( TCHAR ) ); if( chars ) { g_dwCount = 4; @@ -1609,14 +1313,8 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam g_szCandidate[i][0] = 0; else { -#ifdef UNICODE - g_szCandidate[i][0] = g_szCompositionString[i]; - g_szCandidate[i][1] = 0; -#else - g_szCandidate[i][0] = g_szCompositionString[i * 2]; - g_szCandidate[i][1] = g_szCompositionString[i * 2 + 1]; - g_szCandidate[i][2] = 0; -#endif + g_szCandidate[i][0] = g_szCompositionString[i]; + g_szCandidate[i][1] = 0; } } g_uCandPageSize = MAX_CANDLIST; @@ -1630,7 +1328,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam for( i = 0; i < ( int )g_dwCount; i++ ) { if( g_dwSelection == ( DWORD )i ) - g_iReadingError = lstrlen( g_szReadingString ); + g_iReadingError = (int)wcslen( g_szReadingString ); LPCTSTR pszTmp = g_szCandidate[i]; wcscat_s( g_szReadingString, COUNTOF(g_szReadingString), pszTmp ); } @@ -1641,7 +1339,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } // get caret position in composition string - g_IMECursorBytes = _ImmGetCompositionString( himc, GCS_CURSORPOS, NULL, 0 ); + g_IMECursorBytes = _ImmGetCompositionString( himc, GCS_CURSORPOS, nullptr, 0 ); g_IMECursorChars = GetCharCountFromBytes( g_szCompositionString, g_IMECursorBytes ); if( g_dwIMELevel == 3 ) @@ -1686,7 +1384,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam break; CheckToggleState(); break; - + case IMN_OPENCANDIDATE: case IMN_CHANGECANDIDATE: if( g_bUILessMode ) @@ -1696,9 +1394,10 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam { g_bCandList = true; *trapped = true; - if( NULL == ( himc = _ImmGetContext( hWnd ) ) ) + himc = _ImmGetContext( hWnd ); + if( !himc ) break; - + LPCANDIDATELIST lpCandList; DWORD dwIndex, dwBufLen; @@ -1721,8 +1420,8 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam UINT i; for( i = 0; i < g_dwCount; i++ ) { - UINT uLen = lstrlen( - ( LPTSTR )( ( DWORD )lpCandList + lpCandList->dwOffset[i] ) ) + + UINT uLen = (int)wcslen( + ( LPTSTR )( (UINT_PTR)lpCandList + lpCandList->dwOffset[i] ) ) + ( 3 - sizeof( TCHAR ) ); if( uLen + cChars > maxCandChar ) { @@ -1742,7 +1441,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } else { - g_uCandPageSize = min( lpCandList->dwPageSize, MAX_CANDLIST ); + g_uCandPageSize = std::min( lpCandList->dwPageSize, MAX_CANDLIST ); startOfPage = g_bUILessMode ? lpCandList->dwPageStart : ( g_dwSelection / g_uCandPageSize ) * g_uCandPageSize; } @@ -1756,7 +1455,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam i++, j++ ) { ComposeCandidateLine( j, - ( LPTSTR )( ( DWORD )lpCandList + lpCandList->dwOffset[i] ) ); + ( LPTSTR )( (UINT_PTR)lpCandList + lpCandList->dwOffset[i] ) ); } ImeUiCallback_Free( ( HANDLE )lpCandList ); _ImmReleaseContext( hWnd, himc ); @@ -1768,7 +1467,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } break; } - + case IMN_CLOSECANDIDATE: if( g_bUILessMode ) { @@ -1859,7 +1558,9 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } return 0; } +#pragma warning(pop) +_Use_decl_annotations_ void ImeUi_SetCaretPosition( UINT x, UINT y ) { if( !g_bInitialized ) @@ -1868,6 +1569,7 @@ void ImeUi_SetCaretPosition( UINT x, UINT y ) g_CaretInfo.caretY = y; } +_Use_decl_annotations_ void ImeUi_SetCompStringAppearance( CImeUiFont_Base* pFont, DWORD color, const RECT* prc ) { if( !g_bInitialized ) @@ -1885,7 +1587,7 @@ void ImeUi_SetCompStringAppearance( CImeUiFont_Base* pFont, DWORD color, const R g_CaretInfo.colorComp = gSkinIME.compColorText; } -void ImeUi_SetState( DWORD dwState ) +void ImeUi_SetState( _In_ DWORD dwState ) { if( !g_bInitialized ) return; @@ -1894,7 +1596,8 @@ void ImeUi_SetState( DWORD dwState ) { ImeUi_EnableIme( true ); } - if( NULL != ( himc = _ImmGetContext( g_hwndCurr ) ) ) + himc = _ImmGetContext( g_hwndCurr ); + if( himc ) { if( g_bDisableImeCompletely ) dwState = IMEUI_STATE_OFF; @@ -1951,7 +1654,7 @@ DWORD ImeUi_GetState() return g_dwState; } -void ImeUi_EnableIme( bool bEnable ) +void ImeUi_EnableIme( _In_ bool bEnable ) { if( !g_bInitialized || !g_hwndCurr ) return; @@ -1961,7 +1664,7 @@ void ImeUi_EnableIme( bool bEnable ) if( g_hwndCurr == g_hwndMain ) { HIMC himcDbg; - himcDbg = _ImmAssociateContext( g_hwndCurr, bEnable? g_himcOrg : NULL ); + himcDbg = _ImmAssociateContext( g_hwndCurr, bEnable? g_himcOrg : nullptr ); } g_bImeEnabled = bEnable; if( bEnable ) @@ -1971,12 +1674,12 @@ void ImeUi_EnableIme( bool bEnable ) CTsfUiLessMode::EnableUiUpdates( bEnable ); } -bool ImeUi_IsEnabled( void ) +bool ImeUi_IsEnabled() { return g_bImeEnabled; } -bool ImeUi_Initialize( HWND hwnd, bool bDisable ) +bool ImeUi_Initialize(_In_ HWND hwnd, _In_ bool bDisable ) { if( g_bInitialized ) { @@ -1985,29 +1688,17 @@ bool ImeUi_Initialize( HWND hwnd, bool bDisable ) g_hwndMain = hwnd; g_disableCicero.Initialize(); - g_osi.dwOSVersionInfoSize = sizeof( OSVERSIONINFOA ); - GetVersionExA( &g_osi ); - - bool bUnicodeImm = false; - // IMM in NT or Win98 supports Unicode - if( g_osi.dwPlatformId == VER_PLATFORM_WIN32_NT || - ( g_osi.dwMajorVersion > 4 ) || - ( g_osi.dwMajorVersion == 4 ) && ( g_osi.dwMinorVersion > 0 ) ) - { - bUnicodeImm = true; - } - - g_hImmDll = LoadLibraryA( "imm32.dll" ); + g_hImmDll = LoadLibraryEx( L"imm32.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); g_bDisableImeCompletely = false; if( g_hImmDll ) { - _ImmLockIMC = ( LPINPUTCONTEXT2 ( WINAPI* )( HIMC hIMC ) )GetProcAddress( g_hImmDll, "ImmLockIMC" ); - _ImmUnlockIMC = ( BOOL ( WINAPI* )( HIMC hIMC ) )GetProcAddress( g_hImmDll, "ImmUnlockIMC" ); - _ImmLockIMCC = ( LPVOID ( WINAPI* )( HIMCC hIMCC ) )GetProcAddress( g_hImmDll, "ImmLockIMCC" ); - _ImmUnlockIMCC = ( BOOL ( WINAPI* )( HIMCC hIMCC ) )GetProcAddress( g_hImmDll, "ImmUnlockIMCC" ); - BOOL ( WINAPI* _ImmDisableTextFrameService )( DWORD ) = ( BOOL ( WINAPI* )( DWORD ) )GetProcAddress( g_hImmDll, - "ImmDisableTextFrameService" ); + _ImmLockIMC = reinterpret_cast( reinterpret_cast( GetProcAddress( g_hImmDll, "ImmLockIMC" ) ) ); + _ImmUnlockIMC = reinterpret_cast( reinterpret_cast( GetProcAddress( g_hImmDll, "ImmUnlockIMC" ) ) ); + _ImmLockIMCC = reinterpret_cast( reinterpret_cast( GetProcAddress( g_hImmDll, "ImmLockIMCC" ) ) ); + _ImmUnlockIMCC = reinterpret_cast( reinterpret_cast( GetProcAddress( g_hImmDll, "ImmUnlockIMCC" ) ) ); + BOOL ( WINAPI* _ImmDisableTextFrameService )( DWORD ) = reinterpret_cast( reinterpret_cast( GetProcAddress( g_hImmDll, + "ImmDisableTextFrameService" ) ) ); if( _ImmDisableTextFrameService ) { _ImmDisableTextFrameService( ( DWORD )-1 ); @@ -2018,52 +1709,11 @@ bool ImeUi_Initialize( HWND hwnd, bool bDisable ) g_bDisableImeCompletely = true; return false; } -#ifdef UNICODE - if ( bUnicodeImm ) - { - _ImmGetCompositionString = ImmGetCompositionStringW; - _ImmGetCandidateList = ImmGetCandidateListW; - _GetCandidateList = GetCandidateList; - } - else - { - _ImmGetCandidateList = ImmGetCandidateListA; - _ImmGetCompositionString = AW_ImmGetCompositionString; - _GetCandidateList = AW_GetCandidateList; - } -#else - if( bUnicodeImm ) - { - _ImmGetCompositionString = WA_ImmGetCompositionString; - _ImmGetCandidateList = ImmGetCandidateListA; - _GetCandidateList = WA_GetCandidateList; - } - else - { - _ImmGetCompositionString = ImmGetCompositionStringA; - _ImmGetCandidateList = ImmGetCandidateListA; - _GetCandidateList = GetCandidateList; - } -#endif - - // There are the following combinations of code config, window type, and the method of sending characters. - // Wnd: Unicode, Code: Unicode, Method: SendMessageW (SendMessageW must be supported since RegisterClassW is successful) - // Wnd: non Uni, Code: Unicode, Method: AW_SendCompString (Send characters in multibyte after W->A conversion) - // Wnd: Unicode, Code: non Uni, Method: SendMessageA (System does A->W conversion) - possible, but unlikely to be used. - // Wnd: non Uni, Code: non Uni, Method: SendMessageA -#ifdef UNICODE - if ( !IsWindowUnicode( hwnd ) ) - { - _SendCompString = AW_SendCompString; - } - else -#endif - { - _SendCompString = SendCompString; -#ifdef UNICODE - _SendMessage = SendMessageW; -#endif - } + _ImmGetCompositionString = ImmGetCompositionStringW; + _ImmGetCandidateList = ImmGetCandidateListW; + _GetCandidateList = GetCandidateList; + _SendCompString = SendCompString; + _SendMessage = SendMessageW; // turn init flag on so that subsequent calls to ImeUi functions work. g_bInitialized = true; @@ -2091,19 +1741,6 @@ bool ImeUi_Initialize( HWND hwnd, bool bDisable ) g_uCaretBlinkTime = GetCaretBlinkTime(); -#ifndef UNICODE - // Check if system is SBCS system - CPINFO cpi; - BOOL bRc = GetCPInfo( CP_ACP, &cpi ); - if( bRc ) - { - if( cpi.MaxCharSize == 1 ) - { - g_bDisableImeCompletely = true; // SBCS system. Disable IME. - } - } -#endif - g_CaretInfo.caretX = 0; g_CaretInfo.caretY = 0; g_CaretInfo.pFont = 0; @@ -2142,12 +1779,12 @@ void ImeUi_Uninitialize() { ImmAssociateContext( g_hwndMain, g_himcOrg ); } - g_hwndMain = NULL; - g_himcOrg = NULL; + g_hwndMain = nullptr; + g_himcOrg = nullptr; if( g_hImmDll ) { FreeLibrary( g_hImmDll ); - g_hImmDll = NULL; + g_hImmDll = nullptr; } g_disableCicero.Uninitialize(); g_bInitialized = false; @@ -2172,14 +1809,14 @@ void ImeUi_Uninitialize() // // Use IMEID_VER and IMEID_LANG macro to extract version and language information. // -static DWORD GetImeId( UINT uIndex ) +static DWORD GetImeId( _In_ UINT uIndex ) { static HKL hklPrev = 0; static DWORD dwRet[2] = { 0, 0 }; - + DWORD dwVerSize; DWORD dwVerHandle; LPVOID lpVerBuffer; @@ -2196,7 +1833,7 @@ static DWORD GetImeId( UINT uIndex ) return dwRet[uIndex]; } hklPrev = kl; - DWORD dwLang = ( ( DWORD )kl & 0xffff ); + DWORD dwLang = ( static_cast(reinterpret_cast(kl)) & 0xffff ); if( g_bUILessMode && GETLANG() == LANG_CHT ) { @@ -2211,7 +1848,7 @@ static DWORD GetImeId( UINT uIndex ) { goto error; } - + if( _ImmGetIMEFileNameA( kl, szTmp, sizeof( szTmp ) - 1 ) <= 0 ) { goto error; @@ -2237,7 +1874,7 @@ static DWORD GetImeId( UINT uIndex ) lpVerBuffer = ( LPVOID )ImeUiCallback_Malloc( dwVerSize ); if( lpVerBuffer ) { - if( GetFileVersionInfoA( szTmp, dwVerHandle, dwVerSize, lpVerBuffer ) ) + if( GetFileVersionInfoA( szTmp, 0, dwVerSize, lpVerBuffer ) ) { if( VerQueryValueA( lpVerBuffer, "\\", &lpVerData, &cbVerData ) ) { @@ -2267,10 +1904,9 @@ static DWORD GetImeId( UINT uIndex ) #undef pVerFixedInfo } } + ImeUiCallback_Free( lpVerBuffer ); } - ImeUiCallback_Free( lpVerBuffer ); } - // The flow comes here in the following conditions // - Non Chinese IME input locale // - Older Chinese IME @@ -2280,7 +1916,7 @@ static DWORD GetImeId( UINT uIndex ) return dwRet[uIndex]; } -static void GetReadingString( HWND hWnd ) +static void GetReadingString( _In_ HWND hWnd ) { if( g_bUILessMode ) { @@ -2291,7 +1927,7 @@ static void GetReadingString( HWND hWnd ) { return; } - + HIMC himc; himc = _ImmGetContext( hWnd ); if( !himc ) @@ -2302,13 +1938,13 @@ static void GetReadingString( HWND hWnd ) WCHAR wzBuf[16]; // We believe 16 wchars are big enough to hold reading string after having discussion with CHT IME team. WCHAR* wstr = wzBuf; bool unicode = FALSE; - LPINPUTCONTEXT2 lpIMC = NULL; + LPINPUTCONTEXT2 lpIMC = nullptr; if( _GetReadingString ) { BOOL bVertical; UINT uMaxUiLen; - dwlen = _GetReadingString( himc, 0, NULL, ( PINT )&dwerr, &bVertical, &uMaxUiLen ); + dwlen = _GetReadingString( himc, 0, nullptr, ( PINT )&dwerr, &bVertical, &uMaxUiLen ); if( dwlen ) { if( dwlen > COUNTOF(wzBuf) ) @@ -2324,18 +1960,18 @@ static void GetReadingString( HWND hWnd ) else // IMEs that doesn't implement Reading String API { lpIMC = _ImmLockIMC( himc ); - + // *** hacking code from Michael Yang *** - + LPBYTE p = 0; - + switch( dwId ) { - + case IMEID_CHT_VER42: // New(Phonetic/ChanJie)IME98 : 4.2.x.x // Win98 case IMEID_CHT_VER43: // New(Phonetic/ChanJie)IME98a : 4.3.x.x // WinMe, Win2k case IMEID_CHT_VER44: // New ChanJie IME98b : 4.4.x.x // WinXP - + p = *( LPBYTE* )( ( LPBYTE )_ImmLockIMCC( lpIMC->hPrivate ) + 24 ); if( !p ) break; dwlen = *( DWORD* )( p + 7 * 4 + 32 * 4 ); //m_dwInputReadStrLen @@ -2343,9 +1979,9 @@ static void GetReadingString( HWND hWnd ) wstr = ( WCHAR* )( p + 56 ); unicode = TRUE; break; - + case IMEID_CHT_VER50: // 5.0.x.x // WinME - + p = *( LPBYTE* )( ( LPBYTE )_ImmLockIMCC( lpIMC->hPrivate ) + 3 * 4 ); // PCKeyCtrlManager if( !p ) break; p = *( LPBYTE* )( ( LPBYTE )p + 1 * 4 + 5 * 4 + 4 * 2 ); // = PCReading = &STypingInfo @@ -2380,7 +2016,7 @@ static void GetReadingString( HWND hWnd ) if( !p ) break; dwlen = *( DWORD* )( p + 7 * 4 + 16 * 2 * 4 ); dwerr = *( DWORD* )( p + 8 * 4 + 16 * 2 * 4 ); - dwerr = min( dwerr, dwlen ); + dwerr = std::min( dwerr, dwlen ); wstr = ( WCHAR* )( p + 6 * 4 + 16 * 2 * 1 ); unicode = TRUE; break; @@ -2397,7 +2033,7 @@ static void GetReadingString( HWND hWnd ) unicode = IsNT() ? TRUE : FALSE; } } // switch - + g_szCandidate[0][0] = 0; g_szCandidate[1][0] = 0; g_szCandidate[2][0] = 0; @@ -2414,19 +2050,8 @@ static void GetReadingString( HWND hWnd ) { // select error char g_dwSelection = i; } -#ifdef UNICODE - g_szCandidate[i][0] = wstr[i]; - g_szCandidate[i][1] = 0; -#else - char mbc[3]; - mbc[1] = 0; - mbc[2] = 0; - WideCharToMultiByte( g_uCodePage, 0, wstr + i, 1, mbc, sizeof( mbc ), NULL, NULL ); - - g_szCandidate[i][0] = mbc[0]; - g_szCandidate[i][1] = mbc[1]; - g_szCandidate[i][2] = 0; -#endif + g_szCandidate[i][0] = wstr[i]; + g_szCandidate[i][1] = 0; } g_szCandidate[i][0] = 0; } @@ -2440,23 +2065,12 @@ static void GetReadingString( HWND hWnd ) { g_dwSelection = ( DWORD )j; } -#ifdef UNICODE - MultiByteToWideChar( g_uCodePage, 0, p + i, 1 + ( _IsLeadByte( p[i] ) ? 1 : 0 ), - g_szCandidate[j], 1 ); - if ( _IsLeadByte( p[i] ) ) - { - i++; - } -#else - g_szCandidate[j][0] = p[i]; - g_szCandidate[j][1] = 0; - g_szCandidate[j][2] = 0; - if( _IsLeadByte(p[i]) ) + MultiByteToWideChar( g_uCodePage, 0, p + i, 1 + ( _IsLeadByte( p[i] ) ? 1 : 0 ), + g_szCandidate[j], 1 ); + if ( _IsLeadByte( p[i] ) ) { i++; - g_szCandidate[j][1] = p[i]; } -#endif } g_szCandidate[j][0] = 0; g_dwCount = j; @@ -2477,7 +2091,7 @@ static void GetReadingString( HWND hWnd ) for( UINT i = 0; i < g_dwCount; i++ ) { if( g_dwSelection == ( DWORD )i ) - g_iReadingError = lstrlen( g_szReadingString ); + g_iReadingError = (int)wcslen( g_szReadingString ); LPCTSTR pszTmp = g_szCandidate[i]; wcscat_s( g_szReadingString, COUNTOF(g_szReadingString), pszTmp ); } @@ -2525,7 +2139,7 @@ static struct // - Caller doesn't have to check whether IME is on. // - This function must be called before TranslateMessage() is called. // -bool ImeUi_IgnoreHotKey( const MSG* pmsg ) +bool ImeUi_IgnoreHotKey( _In_ const MSG* pmsg ) { if( !g_bInitialized || !pmsg ) return false; @@ -2567,34 +2181,29 @@ bool ImeUi_IgnoreHotKey( const MSG* pmsg ) return false; } -void ImeUi_FinalizeString( bool bSend ) +void ImeUi_FinalizeString( _In_ bool bSend ) { HIMC himc; static bool bProcessing = false; // to avoid infinite recursion - if( !g_bInitialized || bProcessing || NULL == ( himc = _ImmGetContext( g_hwndCurr ) ) ) + if( !g_bInitialized || bProcessing ) + return; + + himc = _ImmGetContext( g_hwndCurr ); + if ( !himc ) return; bProcessing = true; if( g_dwIMELevel == 2 && bSend ) { // Send composition string to app. - LONG lRet = lstrlen( g_szCompositionString ); + LONG lRet = (int)wcslen( g_szCompositionString ); assert( lRet >= 2 ); // In case of CHT IME, don't send the trailing double byte space, if it exists. -#ifdef UNICODE - if ( GETLANG() == LANG_CHT && (lRet >= 1) - && g_szCompositionString[lRet - 1] == 0x3000 ) - { - lRet--; - } -#else - if( GETLANG() == LANG_CHT && ( lRet >= 2 ) - && ( BYTE )( g_szCompositionString[lRet - 2] ) == 0xa1 - && ( BYTE )( g_szCompositionString[lRet - 1] ) == 0x40 ) + if ( GETLANG() == LANG_CHT && (lRet >= 1) + && g_szCompositionString[lRet - 1] == 0x3000 ) { - lRet -= 2; + lRet--; } -#endif _SendCompString(); } @@ -2604,7 +2213,7 @@ void ImeUi_FinalizeString( bool bSend ) if( g_bUILessMode ) { // For some reason ImmNotifyIME doesn't work on DaYi and Array CHT IMEs. Cancel composition string by setting zero-length string. - ImmSetCompositionString( himc, SCS_SETSTR, TEXT( "" ), sizeof( TCHAR ), TEXT( "" ), sizeof( TCHAR ) ); + ImmSetCompositionString( himc, SCS_SETSTR, const_cast(L""), sizeof(wchar_t), const_cast(""), sizeof(wchar_t) ); } // the following line is necessary as Korean IME doesn't close cand list when comp string is cancelled. _ImmNotifyIME( himc, NI_CLOSECANDIDATE, 0, 0 ); @@ -2627,7 +2236,7 @@ static void SetCompStringColor() gSkinCompStr.colorInputErr = dwTranslucency | gSkinIME.compColorInputErr; } -static void SetSupportLevel( DWORD dwImeLevel ) +static void SetSupportLevel( _In_ DWORD dwImeLevel ) { if( dwImeLevel < 2 || 3 < dwImeLevel ) return; @@ -2641,7 +2250,7 @@ static void SetSupportLevel( DWORD dwImeLevel ) SetCompStringColor(); } -void ImeUi_SetSupportLevel( DWORD dwImeLevel ) +void ImeUi_SetSupportLevel( _In_ DWORD dwImeLevel ) { if( !g_bInitialized ) return; @@ -2649,9 +2258,9 @@ void ImeUi_SetSupportLevel( DWORD dwImeLevel ) SetSupportLevel( dwImeLevel ); } -void ImeUi_SetAppearance( const IMEUI_APPEARANCE* pia ) +void ImeUi_SetAppearance( _In_opt_ const IMEUI_APPEARANCE* pia ) { - if( !g_bInitialized || NULL == pia ) + if( !g_bInitialized || !pia ) return; gSkinIME = *pia; gSkinIME.symbolColor &= 0xffffff; // mask translucency @@ -2665,11 +2274,18 @@ void ImeUi_SetAppearance( const IMEUI_APPEARANCE* pia ) SetCompStringColor(); } -void ImeUi_GetAppearance( IMEUI_APPEARANCE* pia ) +void ImeUi_GetAppearance( _Out_opt_ IMEUI_APPEARANCE* pia ) { - if( g_bInitialized && pia ) + if ( pia ) { - *pia = gSkinIME; + if ( g_bInitialized ) + { + *pia = gSkinIME; + } + else + { + memset( pia, 0, sizeof(IMEUI_APPEARANCE) ); + } } } @@ -2686,11 +2302,11 @@ static void CheckToggleState() } bool bIme = _ImmIsIME( g_hklCurrent ) != 0 - && ( ( 0xF0000000 & ( DWORD )g_hklCurrent ) == 0xE0000000 ); // Hack to detect IME correctly. When IME is running as TIP, ImmIsIME() returns true for CHT US keyboard. + && ( ( 0xF0000000 & static_cast( reinterpret_cast( g_hklCurrent ) ) ) == 0xE0000000 ); // Hack to detect IME correctly. When IME is running as TIP, ImmIsIME() returns true for CHT US keyboard. g_bChineseIME = ( GETPRIMLANG() == LANG_CHINESE ) && bIme; - HIMC himc; - if( NULL != ( himc = _ImmGetContext( g_hwndCurr ) ) ) + HIMC himc = _ImmGetContext( g_hwndCurr ); + if( himc ) { if( g_bChineseIME ) { @@ -2708,7 +2324,7 @@ static void CheckToggleState() g_dwState = IMEUI_STATE_OFF; } -void ImeUi_SetInsertMode( bool bInsert ) +void ImeUi_SetInsertMode( _In_ bool bInsert ) { if( !g_bInitialized ) return; @@ -2720,7 +2336,7 @@ bool ImeUi_GetCaretStatus() return !g_bInitialized || !g_szCompositionString[0]; } -void ImeUi_SetScreenDimension( UINT width, UINT height ) +void ImeUi_SetScreenDimension( _In_ UINT width, _In_ UINT height ) { if( !g_bInitialized ) return; @@ -2732,9 +2348,9 @@ void ImeUi_SetScreenDimension( UINT width, UINT height ) static void _PumpMessage() { MSG msg; - while( PeekMessageA( &msg, NULL, 0, 0, PM_NOREMOVE ) ) + while( PeekMessageA( &msg, nullptr, 0, 0, PM_NOREMOVE ) ) { - if( !GetMessageA( &msg, NULL, 0, 0 ) ) + if( !GetMessageA( &msg, nullptr, 0, 0 ) ) { PostQuitMessage( msg.wParam ); return; @@ -2746,7 +2362,7 @@ static void _PumpMessage() } } -static void GetReadingWindowOrientation( DWORD dwId ) +static void GetReadingWindowOrientation( _In_ DWORD dwId ) { g_bHorizontalReading = ( g_hklCurrent == _CHS_HKL ) || ( g_hklCurrent == _CHT_HKL_NEW_CHANG_JIE ) || ( dwId == 0 ); if( !g_bHorizontalReading && IMEID_LANG( dwId ) == LANG_CHT ) @@ -2754,13 +2370,13 @@ static void GetReadingWindowOrientation( DWORD dwId ) char szRegPath[MAX_PATH]; HKEY hkey; DWORD dwVer = IMEID_VER( dwId ); - StringCchCopyA( szRegPath, COUNTOF(szRegPath), "software\\microsoft\\windows\\currentversion\\" ); + strcpy_s( szRegPath, COUNTOF(szRegPath), "software\\microsoft\\windows\\currentversion\\" ); strcat_s( szRegPath, COUNTOF(szRegPath), ( dwVer >= MAKEIMEVERSION(5, 1) ) ? "MSTCIPH" : "TINTLGNT" ); LONG lRc = RegOpenKeyExA( HKEY_CURRENT_USER, szRegPath, 0, KEY_READ, &hkey ); if( lRc == ERROR_SUCCESS ) { DWORD dwSize = sizeof( DWORD ), dwMapping, dwType; - lRc = RegQueryValueExA( hkey, "keyboard mapping", NULL, &dwType, ( PBYTE )&dwMapping, &dwSize ); + lRc = RegQueryValueExA( hkey, "keyboard mapping", nullptr, &dwType, ( PBYTE )&dwMapping, &dwSize ); if( lRc == ERROR_SUCCESS ) { if( @@ -2780,7 +2396,7 @@ static void GetReadingWindowOrientation( DWORD dwId ) } } -void ImeUi_ToggleLanguageBar( BOOL bRestore ) +void ImeUi_ToggleLanguageBar( _In_ BOOL bRestore ) { static BOOL prevRestore = TRUE; bool bCheck = ( prevRestore == TRUE || bRestore == TRUE ); @@ -2792,17 +2408,17 @@ void ImeUi_ToggleLanguageBar( BOOL bRestore ) if( iShowStatusWindow == -1 ) { iShowStatusWindow = IsNT() && g_osi.dwMajorVersion >= 5 && - ( g_osi.dwMinorVersion > 1 || ( g_osi.dwMinorVersion == 1 && lstrlenA( g_osi.szCSDVersion ) ) ) ? 1 : 0; + ( g_osi.dwMinorVersion > 1 || ( g_osi.dwMinorVersion == 1 && strlen( g_osi.szCSDVersion ) ) ) ? 1 : 0; } HWND hwndImeDef = _ImmGetDefaultIMEWnd( g_hwndCurr ); if( hwndImeDef && bRestore && iShowStatusWindow ) SendMessageA( hwndImeDef, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0 ); HRESULT hr; - hr = CoInitialize( NULL ); + hr = CoInitialize( nullptr ); if( SUCCEEDED( hr ) ) { - ITfLangBarMgr* plbm = NULL; - hr = CoCreateInstance( CLSID_TF_LangBarMgr, NULL, CLSCTX_INPROC_SERVER, __uuidof( ITfLangBarMgr ), + ITfLangBarMgr* plbm = nullptr; + hr = CoCreateInstance( CLSID_TF_LangBarMgr, nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfLangBarMgr ), ( void** )&plbm ); if( SUCCEEDED( hr ) && plbm ) { @@ -2874,8 +2490,8 @@ static void OnInputLangChange() static void SetImeApi() { - _GetReadingString = NULL; - _ShowReadingWindow = NULL; + _GetReadingString = nullptr; + _ShowReadingWindow = nullptr; if( g_bUILessMode ) return; @@ -2883,17 +2499,15 @@ static void SetImeApi() HKL kl = g_hklCurrent; if( _ImmGetIMEFileNameA( kl, szImeFile, sizeof( szImeFile ) - 1 ) <= 0 ) return; - HMODULE hIme = LoadLibraryA( szImeFile ); + HMODULE hIme = LoadLibraryExA( szImeFile, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( !hIme ) return; - _GetReadingString = ( UINT ( WINAPI* )( HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT ) ) - ( GetProcAddress( hIme, "GetReadingString" ) ); - _ShowReadingWindow = ( BOOL ( WINAPI* )( HIMC himc, BOOL ) ) - ( GetProcAddress( hIme, "ShowReadingWindow" ) ); + _GetReadingString = reinterpret_cast( reinterpret_cast( GetProcAddress( hIme, "GetReadingString" ) ) ); + _ShowReadingWindow = reinterpret_cast( reinterpret_cast( GetProcAddress( hIme, "ShowReadingWindow" ) ) ); if( _ShowReadingWindow ) { - HIMC himc; - if( NULL != ( himc = _ImmGetContext( g_hwndCurr ) ) ) + HIMC himc = _ImmGetContext( g_hwndCurr ); + if( himc ) { _ShowReadingWindow( himc, false ); _ImmReleaseContext( g_hwndCurr, himc ); @@ -2944,16 +2558,16 @@ static void CheckInputLocale() g_pszIndicatior = g_aszIndicator[INDICATOR_NON_IME]; } char szCodePage[8]; - int iRc = GetLocaleInfoA( MAKELCID( GETLANG(), SORT_DEFAULT ), LOCALE_IDEFAULTANSICODEPAGE, szCodePage, - COUNTOF( szCodePage ) ); iRc; - g_uCodePage = _strtoul( szCodePage, NULL, 0 ); + (void)GetLocaleInfoA( MAKELCID( GETLANG(), SORT_DEFAULT ), LOCALE_IDEFAULTANSICODEPAGE, szCodePage, + COUNTOF( szCodePage ) ); + g_uCodePage = _strtoul( szCodePage, nullptr, 0 ); for( int i = 0; i < 256; i++ ) { LeadByteTable[i] = ( BYTE )IsDBCSLeadByteEx( g_uCodePage, ( BYTE )i ); } } -void ImeUi_SetWindow( HWND hwnd ) +void ImeUi_SetWindow( _In_ HWND hwnd ) { g_hwndCurr = hwnd; g_disableCicero.DisableCiceroOnThisWnd( hwnd ); @@ -2969,7 +2583,7 @@ DWORD ImeUi_GetFlags() return g_dwImeUiFlags; } -void ImeUi_SetFlags( DWORD dwFlags, bool bSet ) +void ImeUi_SetFlags( _In_ DWORD dwFlags, _In_ bool bSet ) { if( bSet ) { @@ -2997,7 +2611,7 @@ BOOL CTsfUiLessMode::SetupSinks() // ITfThreadMgrEx is available on Vista or later. HRESULT hr; hr = CoCreateInstance( CLSID_TF_ThreadMgr, - NULL, + nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfThreadMgrEx ), ( void** )&m_tm ); @@ -3016,7 +2630,7 @@ BOOL CTsfUiLessMode::SetupSinks() // Setup sinks BOOL bRc = FALSE; - m_TsfSink = new CUIElementSink(); + m_TsfSink = new (std::nothrow) CUIElementSink(); if( m_TsfSink ) { ITfSource* srcTm; @@ -3061,9 +2675,8 @@ void CTsfUiLessMode::ReleaseSinks() } } -CTsfUiLessMode::CUIElementSink::CUIElementSink() +CTsfUiLessMode::CUIElementSink::CUIElementSink() noexcept : _cRef(1) { - _cRef = 1; } @@ -3071,16 +2684,16 @@ CTsfUiLessMode::CUIElementSink::~CUIElementSink() { } -STDAPI CTsfUiLessMode::CUIElementSink::QueryInterface( REFIID riid, void** ppvObj ) +STDAPI CTsfUiLessMode::CUIElementSink::QueryInterface( _In_ REFIID riid, _COM_Outptr_ void** ppvObj ) { - if( ppvObj == NULL ) + if( !ppvObj ) return E_INVALIDARG; - *ppvObj = NULL; + *ppvObj = nullptr; if( IsEqualIID( riid, IID_IUnknown ) ) { - *ppvObj = reinterpret_cast( this ); + *ppvObj = static_cast( static_cast( this ) ); } else if( IsEqualIID( riid, __uuidof( ITfUIElementSink ) ) ) { @@ -3125,12 +2738,12 @@ CTsfUiLessMode::CUIElementSink::Release() STDAPI CTsfUiLessMode::CUIElementSink::BeginUIElement( DWORD dwUIElementId, BOOL* pbShow ) { - ITfUIElement* pElement = GetUIElement( dwUIElementId ); + auto pElement = GetUIElement( dwUIElementId ); if( !pElement ) return E_INVALIDARG; - ITfReadingInformationUIElement* preading = NULL; - ITfCandidateListUIElement* pcandidate = NULL; + ITfReadingInformationUIElement* preading = nullptr; + ITfCandidateListUIElement* pcandidate = nullptr; *pbShow = FALSE; if( !g_bCandList && SUCCEEDED( pElement->QueryInterface( __uuidof( ITfReadingInformationUIElement ), ( void** )&preading ) ) ) @@ -3152,12 +2765,12 @@ STDAPI CTsfUiLessMode::CUIElementSink::BeginUIElement( DWORD dwUIElementId, BOOL STDAPI CTsfUiLessMode::CUIElementSink::UpdateUIElement( DWORD dwUIElementId ) { - ITfUIElement* pElement = GetUIElement( dwUIElementId ); + auto pElement = GetUIElement( dwUIElementId ); if( !pElement ) return E_INVALIDARG; - ITfReadingInformationUIElement* preading = NULL; - ITfCandidateListUIElement* pcandidate = NULL; + ITfReadingInformationUIElement* preading = nullptr; + ITfCandidateListUIElement* pcandidate = nullptr; if( !g_bCandList && SUCCEEDED( pElement->QueryInterface( __uuidof( ITfReadingInformationUIElement ), ( void** )&preading ) ) ) { @@ -3177,11 +2790,11 @@ STDAPI CTsfUiLessMode::CUIElementSink::UpdateUIElement( DWORD dwUIElementId ) STDAPI CTsfUiLessMode::CUIElementSink::EndUIElement( DWORD dwUIElementId ) { - ITfUIElement* pElement = GetUIElement( dwUIElementId ); + auto pElement = GetUIElement( dwUIElementId ); if( !pElement ) return E_INVALIDARG; - ITfReadingInformationUIElement* preading = NULL; + ITfReadingInformationUIElement* preading = nullptr; if( !g_bCandList && SUCCEEDED( pElement->QueryInterface( __uuidof( ITfReadingInformationUIElement ), ( void** )&preading ) ) ) { @@ -3189,7 +2802,7 @@ STDAPI CTsfUiLessMode::CUIElementSink::EndUIElement( DWORD dwUIElementId ) preading->Release(); } - ITfCandidateListUIElement* pcandidate = NULL; + ITfCandidateListUIElement* pcandidate = nullptr; if( SUCCEEDED( pElement->QueryInterface( __uuidof( ITfCandidateListUIElement ), ( void** )&pcandidate ) ) ) { @@ -3206,27 +2819,31 @@ STDAPI CTsfUiLessMode::CUIElementSink::EndUIElement( DWORD dwUIElementId ) void CTsfUiLessMode::UpdateImeState( BOOL bResetCompartmentEventSink ) { ITfCompartmentMgr* pcm; - ITfCompartment* pTfOpenMode = NULL; - ITfCompartment* pTfConvMode = NULL; + ITfCompartment* pTfOpenMode = nullptr; + ITfCompartment* pTfConvMode = nullptr; if( GetCompartments( &pcm, &pTfOpenMode, &pTfConvMode ) ) { VARIANT valOpenMode; - VARIANT valConvMode; - pTfOpenMode->GetValue( &valOpenMode ); - pTfConvMode->GetValue( &valConvMode ); - if( valOpenMode.vt == VT_I4 ) + if ( SUCCEEDED(pTfOpenMode->GetValue(&valOpenMode)) ) { - if( g_bChineseIME ) + VARIANT valConvMode; + if (SUCCEEDED(pTfConvMode->GetValue(&valConvMode))) { - g_dwState = valOpenMode.lVal != 0 && valConvMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_ENGLISH; - } - else - { - g_dwState = valOpenMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_OFF; + if (valOpenMode.vt == VT_I4) + { + if (g_bChineseIME) + { + g_dwState = valOpenMode.lVal != 0 && valConvMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_ENGLISH; + } + else + { + g_dwState = valOpenMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_OFF; + } + } + VariantClear(&valConvMode); } + VariantClear(&valOpenMode); } - VariantClear( &valOpenMode ); - VariantClear( &valConvMode ); if( bResetCompartmentEventSink ) { @@ -3238,14 +2855,17 @@ void CTsfUiLessMode::UpdateImeState( BOOL bResetCompartmentEventSink ) } } -STDAPI CTsfUiLessMode::CUIElementSink::OnActivated( DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid, - REFGUID guidProfile, HKL hkl, DWORD dwFlags ) +STDAPI CTsfUiLessMode::CUIElementSink::OnActivated( DWORD dwProfileType, LANGID langid, _In_ REFCLSID clsid, _In_ REFGUID catid, + _In_ REFGUID guidProfile, HKL hkl, DWORD dwFlags ) { - static GUID TF_PROFILE_DAYI = + UNREFERENCED_PARAMETER(clsid); + UNREFERENCED_PARAMETER(hkl); + + static GUID s_TF_PROFILE_DAYI = { 0x037B2C25, 0x480C, 0x4D7F, 0xB0, 0x27, 0xD6, 0xCA, 0x6B, 0x69, 0x78, 0x8A }; - g_iCandListIndexBase = IsEqualGUID( TF_PROFILE_DAYI, guidProfile ) ? 0 : 1; + g_iCandListIndexBase = IsEqualGUID( s_TF_PROFILE_DAYI, guidProfile ) ? 0 : 1; if( IsEqualIID( catid, GUID_TFCAT_TIP_KEYBOARD ) && ( dwFlags & TF_IPSINK_FLAG_ACTIVE ) ) { g_bChineseIME = ( dwProfileType & TF_PROFILETYPE_INPUTPROCESSOR ) && langid == LANG_CHT; @@ -3260,8 +2880,9 @@ STDAPI CTsfUiLessMode::CUIElementSink::OnActivated( DWORD dwProfileType, LANGID return S_OK; } -STDAPI CTsfUiLessMode::CUIElementSink::OnChange( REFGUID rguid ) +STDAPI CTsfUiLessMode::CUIElementSink::OnChange( _In_ REFGUID rguid ) { + UNREFERENCED_PARAMETER(rguid); UpdateImeState(); return S_OK; } @@ -3283,39 +2904,13 @@ void CTsfUiLessMode::MakeReadingInformationString( ITfReadingInformationUIElemen g_uCandPageSize = MAX_CANDLIST; g_dwSelection = g_iReadingError ? g_iReadingError - 1 : ( DWORD )-1; g_iReadingError--; // g_iReadingError is used only in horizontal window, and has to be -1 if there's no error. -#ifndef UNICODE - if( g_iReadingError > 0 ) - { - // convert g_iReadingError to byte based - LPCSTR pszNext = g_szReadingString; - for( int i = 0; i < g_iReadingError && pszNext && *pszNext; ++i ) - { - pszNext = CharNext( pszNext ); - } - if( pszNext ) // should be non-NULL, but just in case - { - g_iReadingError = pszNext - g_szReadingString; - } - } -#endif BSTR bstr; if( SUCCEEDED( preading->GetString( &bstr ) ) ) { if( bstr ) { -#ifndef UNICODE - char szStr[COUNTOF(g_szReadingString)*2]; - szStr[0] = 0; - int iRc = WideCharToMultiByte( CP_ACP, 0, bstr, -1, szStr, sizeof( szStr ), NULL, NULL ); - if( iRc >= sizeof( szStr ) ) - { - szStr[sizeof( szStr ) - 1] = 0; - } - StringCchCopy( g_szReadingString, COUNTOF(g_szReadingString), szStr ); -#else - StringCchCopy( g_szReadingString, COUNTOF(g_szReadingString), bstr ); -#endif + wcscpy_s( g_szReadingString, COUNTOF(g_szReadingString), bstr ); g_dwCount = cchMax; LPCTSTR pszSource = g_szReadingString; if( fVertical ) @@ -3328,7 +2923,7 @@ void CTsfUiLessMode::MakeReadingInformationString( ITfReadingInformationUIElemen { LPTSTR pszNextSrc = CharNext( pszSource ); SIZE_T size = ( LPSTR )pszNextSrc - ( LPSTR )pszSource; - CopyMemory( pszDest, pszSource, size ); + memcpy( pszDest, pszSource, size ); pszSource = pszNextSrc; pszDest += size; } @@ -3349,7 +2944,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate UINT uIndex = 0; UINT uCount = 0; UINT uCurrentPage = 0; - UINT* IndexList = NULL; + UINT* IndexList = nullptr; UINT uPageCnt = 0; DWORD dwPageStart = 0; DWORD dwPageSize = 0; @@ -3363,7 +2958,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate g_bCandList = true; g_bReadingWindow = false; - pcandidate->GetPageIndex( NULL, 0, &uPageCnt ); + pcandidate->GetPageIndex( nullptr, 0, &uPageCnt ); if( uPageCnt > 0 ) { IndexList = ( UINT* )ImeUiCallback_Malloc( sizeof( UINT ) * uPageCnt ); @@ -3372,12 +2967,12 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate pcandidate->GetPageIndex( IndexList, uPageCnt, &uPageCnt ); dwPageStart = IndexList[uCurrentPage]; dwPageSize = ( uCurrentPage < uPageCnt - 1 ) ? - min( uCount, IndexList[uCurrentPage + 1] ) - dwPageStart: + std::min( uCount, IndexList[uCurrentPage + 1] ) - dwPageStart: uCount - dwPageStart; } } - g_uCandPageSize = min( dwPageSize, MAX_CANDLIST ); + g_uCandPageSize = std::min( dwPageSize, MAX_CANDLIST ); g_dwSelection = g_dwSelection - dwPageStart; memset( &g_szCandidate, 0, sizeof( g_szCandidate ) ); @@ -3387,18 +2982,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate { if( bstr ) { -#ifndef UNICODE - char szStr[COUNTOF(g_szCandidate[0])*2]; - szStr[0] = 0; - int iRc = WideCharToMultiByte( CP_ACP, 0, bstr, -1, szStr, sizeof( szStr ), NULL, NULL ); - if( iRc >= sizeof( szStr ) ) - { - szStr[sizeof( szStr ) - 1] = 0; - } - ComposeCandidateLine( j, szStr ); -#else - ComposeCandidateLine( j, bstr ); -#endif + ComposeCandidateLine( j, bstr ); SysFreeString( bstr ); } } @@ -3418,7 +3002,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate ITfUIElement* CTsfUiLessMode::GetUIElement( DWORD dwUIElementId ) { ITfUIElementMgr* puiem; - ITfUIElement* pElement = NULL; + ITfUIElement* pElement = nullptr; if( SUCCEEDED( m_tm->QueryInterface( __uuidof( ITfUIElementMgr ), ( void** )&puiem ) ) ) { @@ -3435,7 +3019,7 @@ BOOL CTsfUiLessMode::CurrentInputLocaleIsIme() HRESULT hr; ITfInputProcessorProfiles* pProfiles; - hr = CoCreateInstance( CLSID_TF_InputProcessorProfiles, NULL, CLSCTX_INPROC_SERVER, + hr = CoCreateInstance( CLSID_TF_InputProcessorProfiles, nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfInputProcessorProfiles ), ( LPVOID* )&pProfiles ); if( SUCCEEDED( hr ) ) { @@ -3461,13 +3045,13 @@ BOOL CTsfUiLessMode::CurrentInputLocaleIsIme() // otherwise the sink can be triggered when a game has multiple instances of IME UI library. void CTsfUiLessMode::EnableUiUpdates( bool bEnable ) { - if( m_tm == NULL || + if( !m_tm || ( bEnable && m_dwUIElementSinkCookie != TF_INVALID_COOKIE ) || ( !bEnable && m_dwUIElementSinkCookie == TF_INVALID_COOKIE ) ) { return; } - ITfSource* srcTm = NULL; + ITfSource* srcTm = nullptr; HRESULT hr = E_FAIL; if( SUCCEEDED( hr = m_tm->QueryInterface( __uuidof( ITfSource ), ( void** )&srcTm ) ) ) { @@ -3490,9 +3074,9 @@ void CTsfUiLessMode::EnableUiUpdates( bool bEnable ) BOOL CTsfUiLessMode::GetCompartments( ITfCompartmentMgr** ppcm, ITfCompartment** ppTfOpenMode, ITfCompartment** ppTfConvMode ) { - ITfCompartmentMgr* pcm = NULL; - ITfCompartment* pTfOpenMode = NULL; - ITfCompartment* pTfConvMode = NULL; + ITfCompartmentMgr* pcm = nullptr; + ITfCompartment* pTfOpenMode = nullptr; + ITfCompartment* pTfConvMode = nullptr; static GUID _GUID_COMPARTMENT_KEYBOARD_INPUTMODE_CONVERSION = { @@ -3527,7 +3111,7 @@ BOOL CTsfUiLessMode::SetupCompartmentSinks( BOOL bRemoveOnly, ITfCompartment* pT ITfCompartment* pTfConvMode ) { bool bLocalCompartments = false; - ITfCompartmentMgr* pcm = NULL; + ITfCompartmentMgr* pcm = nullptr; BOOL bRc = FALSE; HRESULT hr = E_FAIL; @@ -3541,7 +3125,7 @@ BOOL CTsfUiLessMode::SetupCompartmentSinks( BOOL bRemoveOnly, ITfCompartment* pT // Invalid parameters or GetCompartments() has failed. return FALSE; } - ITfSource* srcOpenMode = NULL; + ITfSource* srcOpenMode = nullptr; if( SUCCEEDED( hr = pTfOpenMode->QueryInterface( IID_ITfSource, ( void** )&srcOpenMode ) ) ) { // Remove existing sink for open mode @@ -3555,7 +3139,7 @@ BOOL CTsfUiLessMode::SetupCompartmentSinks( BOOL bRemoveOnly, ITfCompartment* pT ( ITfCompartmentEventSink* )m_TsfSink, &m_dwOpenModeSinkCookie ) ) ) { - ITfSource* srcConvMode = NULL; + ITfSource* srcConvMode = nullptr; if( SUCCEEDED( hr = pTfConvMode->QueryInterface( IID_ITfSource, ( void** )&srcConvMode ) ) ) { // Remove existing sink for open mode @@ -3591,7 +3175,7 @@ WORD ImeUi_GetPrimaryLanguage() return GETPRIMLANG(); }; -DWORD ImeUi_GetImeId( UINT uIndex ) +DWORD ImeUi_GetImeId( _In_ UINT uIndex ) { return GetImeId( uIndex ); }; @@ -3601,7 +3185,7 @@ WORD ImeUi_GetLanguage() return GETLANG(); }; -PTSTR ImeUi_GetIndicatior() +PCTSTR ImeUi_GetIndicatior() { return g_pszIndicatior; }; @@ -3627,7 +3211,7 @@ bool ImeUi_IsHorizontalReading() return g_bHorizontalReading; }; -TCHAR* ImeUi_GetCandidate( UINT idx ) +TCHAR* ImeUi_GetCandidate( _In_ UINT idx ) { if( idx < MAX_CANDLIST ) return g_szCandidate[idx]; diff --git a/FriedLiver/Source/DXUT/Optional/ImeUi.h b/FriedLiver/Source/DXUT/Optional/ImeUi.h index c8d2b2f0..908b5ae1 100644 --- a/FriedLiver/Source/DXUT/Optional/ImeUi.h +++ b/FriedLiver/Source/DXUT/Optional/ImeUi.h @@ -2,25 +2,25 @@ // File: ImeUi.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- -#ifndef _IMEUI_H_ -#define _IMEUI_H_ -#if _WIN32_WINNT < 0x0400 -#error IMEUI requires _WIN32_WINNT to be 0x0400 or higher. Please add "_WIN32_WINNT=0x0400" to your project's preprocessor setting. -#endif +#pragma once + #include class CImeUiFont_Base { public: - virtual void SetHeight( UINT uHeight ) + virtual void SetHeight( _In_ UINT uHeight ) { - uHeight; + UNREFERENCED_PARAMETER(uHeight); }; // for backward compatibility - virtual void SetColor( DWORD color ) = 0; - virtual void SetPosition( int x, int y ) = 0; - virtual void GetTextExtent( LPCTSTR szText, DWORD* puWidth, DWORD* puHeight ) = 0; - virtual void DrawText( LPCTSTR pszText ) = 0; + virtual void SetColor( _In_ DWORD color ) = 0; + virtual void SetPosition( _In_ int x, _In_ int y ) = 0; + virtual void GetTextExtent( _In_z_ LPCTSTR szText, _Out_ DWORD* puWidth, _Out_ DWORD* puHeight ) = 0; + virtual void DrawText( _In_z_ LPCTSTR pszText ) = 0; }; typedef struct @@ -76,49 +76,47 @@ typedef struct // D3DTLVERTEX compatible // IME Flags #define IMEUI_FLAG_SUPPORT_CARET 0x00000001 -bool ImeUi_Initialize( HWND hwnd, bool bDisable = false ); +bool ImeUi_Initialize( _In_ HWND hwnd, _In_ bool bDisable = false ); void ImeUi_Uninitialize(); -void ImeUi_SetAppearance( const IMEUI_APPEARANCE* pia ); -void ImeUi_GetAppearance( IMEUI_APPEARANCE* pia ); -bool ImeUi_IgnoreHotKey( const MSG* pmsg ); -LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam, bool* trapped ); -void ImeUi_SetScreenDimension( UINT width, UINT height ); -void ImeUi_RenderUI( bool bDrawCompAttr = true, bool bDrawOtherUi = true ); -void ImeUi_SetCaretPosition( UINT x, UINT y ); -void ImeUi_SetCompStringAppearance( CImeUiFont_Base* pFont, DWORD color, const RECT* prc ); +void ImeUi_SetAppearance( _In_opt_ const IMEUI_APPEARANCE* pia ); +void ImeUi_GetAppearance( _Out_opt_ IMEUI_APPEARANCE* pia ); +bool ImeUi_IgnoreHotKey( _In_ const MSG* pmsg ); +LPARAM ImeUi_ProcessMessage( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _Inout_ LPARAM& lParam, _Out_ bool* trapped ); +void ImeUi_SetScreenDimension( _In_ UINT width, _In_ UINT height ); +void ImeUi_RenderUI( _In_ bool bDrawCompAttr = true, _In_ bool bDrawOtherUi = true ); +void ImeUi_SetCaretPosition( _In_ UINT x, _In_ UINT y ); +void ImeUi_SetCompStringAppearance( _In_ CImeUiFont_Base* pFont, _In_ DWORD color, _In_ const RECT* prc ); bool ImeUi_GetCaretStatus(); -void ImeUi_SetInsertMode( bool bInsert ); -void ImeUi_SetState( DWORD dwState ); +void ImeUi_SetInsertMode( _In_ bool bInsert ); +void ImeUi_SetState( _In_ DWORD dwState ); DWORD ImeUi_GetState(); -void ImeUi_EnableIme( bool bEnable ); -bool ImeUi_IsEnabled( void ); -void ImeUi_FinalizeString( bool bSend = false ); -void ImeUi_ToggleLanguageBar( BOOL bRestore ); +void ImeUi_EnableIme( _In_ bool bEnable ); +bool ImeUi_IsEnabled(); +void ImeUi_FinalizeString( _In_ bool bSend = false ); +void ImeUi_ToggleLanguageBar( _In_ BOOL bRestore ); bool ImeUi_IsSendingKeyMessage(); -void ImeUi_SetWindow( HWND hwnd ); +void ImeUi_SetWindow( _In_ HWND hwnd ); UINT ImeUi_GetInputCodePage(); DWORD ImeUi_GetFlags(); -void ImeUi_SetFlags( DWORD dwFlags, bool bSet ); +void ImeUi_SetFlags( _In_ DWORD dwFlags, _In_ bool bSet ); WORD ImeUi_GetPrimaryLanguage(); -DWORD ImeUi_GetImeId( UINT uIndex ); +DWORD ImeUi_GetImeId( _In_ UINT uIndex ); WORD ImeUi_GetLanguage(); -LPTSTR ImeUi_GetIndicatior(); +LPCTSTR ImeUi_GetIndicatior(); bool ImeUi_IsShowReadingWindow(); bool ImeUi_IsShowCandListWindow(); bool ImeUi_IsVerticalCand(); bool ImeUi_IsHorizontalReading(); -TCHAR* ImeUi_GetCandidate( UINT idx ); +TCHAR* ImeUi_GetCandidate( _In_ UINT idx ); TCHAR* ImeUi_GetCompositionString(); DWORD ImeUi_GetCandidateSelection(); DWORD ImeUi_GetCandidateCount(); BYTE* ImeUi_GetCompStringAttr(); DWORD ImeUi_GetImeCursorChars(); -extern void ( CALLBACK*ImeUiCallback_DrawRect )( int x1, int y1, int x2, int y2, DWORD color ); -extern void* ( __cdecl*ImeUiCallback_Malloc )( size_t bytes ); -extern void ( __cdecl*ImeUiCallback_Free )( void* ptr ); -extern void ( CALLBACK*ImeUiCallback_DrawFans )( const IMEUI_VERTEX* paVertex, UINT uNum ); -extern void ( CALLBACK*ImeUiCallback_OnChar )( WCHAR wc ); - -#endif //_IMEUI_H_ +extern void ( CALLBACK*ImeUiCallback_DrawRect )( _In_ int x1, _In_ int y1, _In_ int x2, _In_ int y2, _In_ DWORD color ); +extern void* ( __cdecl*ImeUiCallback_Malloc )( _In_ size_t bytes ); +extern void ( __cdecl*ImeUiCallback_Free )( _In_ void* ptr ); +extern void ( CALLBACK*ImeUiCallback_DrawFans )( _In_ const IMEUI_VERTEX* paVertex, _In_ UINT uNum ); +extern void ( CALLBACK*ImeUiCallback_OnChar )( _In_ WCHAR wc ); diff --git a/FriedLiver/Source/DXUT/Optional/SDKmesh.cpp b/FriedLiver/Source/DXUT/Optional/SDKmesh.cpp index 18b72ca1..9df5d119 100644 --- a/FriedLiver/Source/DXUT/Optional/SDKmesh.cpp +++ b/FriedLiver/Source/DXUT/Optional/SDKmesh.cpp @@ -7,12 +7,18 @@ // meets the specific needs of the application. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "SDKMesh.h" #include "SDKMisc.h" +using namespace DirectX; + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pMaterials, UINT numMaterials, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { @@ -22,12 +28,12 @@ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pM { for( UINT m = 0; m < numMaterials; m++ ) { - pMaterials[m].pDiffuseTexture11 = NULL; - pMaterials[m].pNormalTexture11 = NULL; - pMaterials[m].pSpecularTexture11 = NULL; - pMaterials[m].pDiffuseRV11 = NULL; - pMaterials[m].pNormalRV11 = NULL; - pMaterials[m].pSpecularRV11 = NULL; + pMaterials[m].pDiffuseTexture11 = nullptr; + pMaterials[m].pNormalTexture11 = nullptr; + pMaterials[m].pSpecularTexture11 = nullptr; + pMaterials[m].pDiffuseRV11 = nullptr; + pMaterials[m].pNormalRV11 = nullptr; + pMaterials[m].pSpecularRV11 = nullptr; // load textures if( pMaterials[m].DiffuseTexture[0] != 0 ) @@ -54,12 +60,12 @@ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pM { for( UINT m = 0; m < numMaterials; m++ ) { - pMaterials[m].pDiffuseTexture11 = NULL; - pMaterials[m].pNormalTexture11 = NULL; - pMaterials[m].pSpecularTexture11 = NULL; - pMaterials[m].pDiffuseRV11 = NULL; - pMaterials[m].pNormalRV11 = NULL; - pMaterials[m].pSpecularRV11 = NULL; + pMaterials[m].pDiffuseTexture11 = nullptr; + pMaterials[m].pNormalTexture11 = nullptr; + pMaterials[m].pSpecularTexture11 = nullptr; + pMaterials[m].pDiffuseRV11 = nullptr; + pMaterials[m].pNormalRV11 = nullptr; + pMaterials[m].pSpecularRV11 = nullptr; // load textures if( pMaterials[m].DiffuseTexture[0] != 0 ) @@ -92,84 +98,7 @@ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pM } //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::LoadMaterials( IDirect3DDevice9* pd3dDevice, SDKMESH_MATERIAL* pMaterials, UINT numMaterials, - SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - char strPath[MAX_PATH]; - - if( pLoaderCallbacks && pLoaderCallbacks->pCreateTextureFromFile ) - { - for( UINT m = 0; m < numMaterials; m++ ) - { - pMaterials[m].pDiffuseTexture9 = NULL; - pMaterials[m].pNormalTexture9 = NULL; - pMaterials[m].pSpecularTexture9 = NULL; - - // load textures - if( pMaterials[m].DiffuseTexture[0] != 0 ) - { - pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice, - pMaterials[m].DiffuseTexture, - &pMaterials[m].pDiffuseTexture9, - pLoaderCallbacks->pContext ); - } - if( pMaterials[m].NormalTexture[0] != 0 ) - { - pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice, - pMaterials[m].NormalTexture, &pMaterials[m].pNormalTexture9, - pLoaderCallbacks->pContext ); - } - if( pMaterials[m].SpecularTexture[0] != 0 ) - { - pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice, - pMaterials[m].SpecularTexture, - &pMaterials[m].pSpecularTexture9, - pLoaderCallbacks->pContext ); - } - } - } - else - { - for( UINT m = 0; m < numMaterials; m++ ) - { - pMaterials[m].pDiffuseTexture9 = NULL; - pMaterials[m].pNormalTexture9 = NULL; - pMaterials[m].pSpecularTexture9 = NULL; - pMaterials[m].pDiffuseRV11 = NULL; - pMaterials[m].pNormalRV11 = NULL; - pMaterials[m].pSpecularRV11 = NULL; - - // load textures - if( pMaterials[m].DiffuseTexture[0] != 0 ) - { - sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].DiffuseTexture ); - if( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, - strPath, - &pMaterials[m].pDiffuseTexture9 ) ) ) - pMaterials[m].pDiffuseTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE; - } - if( pMaterials[m].NormalTexture[0] != 0 ) - { - sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].NormalTexture ); - if( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, - strPath, - &pMaterials[m].pNormalTexture9 ) ) ) - pMaterials[m].pNormalTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE; - } - if( pMaterials[m].SpecularTexture[0] != 0 ) - { - sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].SpecularTexture ); - if( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, - strPath, - &pMaterials[m].pSpecularTexture9 ) ) ) - pMaterials[m].pSpecularTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE; - } - - } - } -} - -//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateVertexBuffer( ID3D11Device* pd3dDevice, SDKMESH_VERTEX_BUFFER_HEADER* pHeader, void* pVertices, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { @@ -193,7 +122,10 @@ HRESULT CDXUTSDKMesh::CreateVertexBuffer( ID3D11Device* pd3dDevice, SDKMESH_VERT D3D11_SUBRESOURCE_DATA InitData; InitData.pSysMem = pVertices; hr = pd3dDevice->CreateBuffer( &bufferDesc, &InitData, &pHeader->pVB11 ); - DXUT_SetDebugName( pHeader->pVB11, "CDXUTSDKMesh" ); + if (SUCCEEDED(hr)) + { + DXUT_SetDebugName(pHeader->pVB11, "CDXUTSDKMesh"); + } } return hr; @@ -201,6 +133,7 @@ HRESULT CDXUTSDKMesh::CreateVertexBuffer( ID3D11Device* pd3dDevice, SDKMESH_VERT //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateIndexBuffer( ID3D11Device* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader, void* pIndices, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { @@ -224,101 +157,21 @@ HRESULT CDXUTSDKMesh::CreateIndexBuffer( ID3D11Device* pd3dDevice, SDKMESH_INDEX D3D11_SUBRESOURCE_DATA InitData; InitData.pSysMem = pIndices; hr = pd3dDevice->CreateBuffer( &bufferDesc, &InitData, &pHeader->pIB11 ); - DXUT_SetDebugName( pHeader->pIB11, "CDXUTSDKMesh" ); - } - - return hr; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::CreateVertexBuffer( IDirect3DDevice9* pd3dDevice, SDKMESH_VERTEX_BUFFER_HEADER* pHeader, - void* pVertices, SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - HRESULT hr = S_OK; - - pHeader->DataOffset = 0; - if( pLoaderCallbacks && pLoaderCallbacks->pCreateVertexBuffer ) - { - pLoaderCallbacks->pCreateVertexBuffer( pd3dDevice, &pHeader->pVB9, ( UINT )pHeader->SizeBytes, - D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, pVertices, - pLoaderCallbacks->pContext ); - } - else - { - hr = pd3dDevice->CreateVertexBuffer( ( UINT )pHeader->SizeBytes, - D3DUSAGE_WRITEONLY, - 0, - D3DPOOL_DEFAULT, - &pHeader->pVB9, - NULL ); - - //lock - if( SUCCEEDED( hr ) ) + if (SUCCEEDED(hr)) { - void* pLockedVerts = NULL; - V_RETURN( pHeader->pVB9->Lock( 0, 0, &pLockedVerts, 0 ) ); - CopyMemory( pLockedVerts, pVertices, ( size_t )pHeader->SizeBytes ); - pHeader->pVB9->Unlock(); + DXUT_SetDebugName(pHeader->pIB11, "CDXUTSDKMesh"); } } return hr; } -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::CreateIndexBuffer( IDirect3DDevice9* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader, - void* pIndices, SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - HRESULT hr = S_OK; - - pHeader->DataOffset = 0; - - D3DFORMAT ibFormat = D3DFMT_INDEX16; - switch( pHeader->IndexType ) - { - case IT_16BIT: - ibFormat = D3DFMT_INDEX16; - break; - case IT_32BIT: - ibFormat = D3DFMT_INDEX32; - break; - }; - - if( pLoaderCallbacks && pLoaderCallbacks->pCreateIndexBuffer ) - { - pLoaderCallbacks->pCreateIndexBuffer( pd3dDevice, &pHeader->pIB9, ( UINT )pHeader->SizeBytes, - D3DUSAGE_WRITEONLY, ibFormat, D3DPOOL_DEFAULT, pIndices, - pLoaderCallbacks->pContext ); - } - else - { - hr = pd3dDevice->CreateIndexBuffer( ( UINT )( pHeader->SizeBytes ), - D3DUSAGE_WRITEONLY, - ibFormat, - D3DPOOL_DEFAULT, - &pHeader->pIB9, - NULL ); - - if( SUCCEEDED( hr ) ) - { - void* pLockedIndices = NULL; - V_RETURN( pHeader->pIB9->Lock( 0, 0, &pLockedIndices, 0 ) ); - CopyMemory( pLockedIndices, pIndices, ( size_t )( pHeader->SizeBytes ) ); - pHeader->pIB9->Unlock(); - } - } - - return hr; -} //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, - LPCTSTR szFileName, - bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS11* pLoaderCallbacks11, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 ) + LPCWSTR szFileName, + SDKMESH_CALLBACKS11* pLoaderCallbacks11 ) { HRESULT hr = S_OK; @@ -326,8 +179,8 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, V_RETURN( DXUTFindDXSDKMediaFileCch( m_strPathW, sizeof( m_strPathW ) / sizeof( WCHAR ), szFileName ) ); // Open the file - m_hFile = CreateFile( m_strPathW, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, - NULL ); + m_hFile = CreateFile( m_strPathW, FILE_READ_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, + nullptr ); if( INVALID_HANDLE_VALUE == m_hFile ) return DXUTERR_MEDIANOTFOUND; @@ -338,7 +191,7 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, else *m_strPathW = L'\0'; - WideCharToMultiByte( CP_ACP, 0, m_strPathW, -1, m_strPath, MAX_PATH, NULL, FALSE ); + WideCharToMultiByte( CP_ACP, 0, m_strPathW, -1, m_strPath, MAX_PATH, nullptr, FALSE ); // Get the file size LARGE_INTEGER FileSize; @@ -346,7 +199,7 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, UINT cBytes = FileSize.LowPart; // Allocate memory - m_pStaticMeshData = new BYTE[ cBytes ]; + m_pStaticMeshData = new (std::nothrow) BYTE[ cBytes ]; if( !m_pStaticMeshData ) { CloseHandle( m_hFile ); @@ -355,7 +208,7 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, // Read in the file DWORD dwBytesRead; - if( !ReadFile( m_hFile, m_pStaticMeshData, cBytes, &dwBytesRead, NULL ) ) + if( !ReadFile( m_hFile, m_pStaticMeshData, cBytes, &dwBytesRead, nullptr ) ) hr = E_FAIL; CloseHandle( m_hFile ); @@ -363,13 +216,10 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, if( SUCCEEDED( hr ) ) { hr = CreateFromMemory( pDev11, - pDev9, m_pStaticMeshData, cBytes, - bCreateAdjacencyIndices, false, - pLoaderCallbacks11, - pLoaderCallbacks9 ); + pLoaderCallbacks11 ); if( FAILED( hr ) ) delete []m_pStaticMeshData; } @@ -377,37 +227,39 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, return hr; } +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, BYTE* pData, - UINT DataBytes, - bool bCreateAdjacencyIndices, + size_t DataBytes, bool bCopyStatic, - SDKMESH_CALLBACKS11* pLoaderCallbacks11, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 ) + SDKMESH_CALLBACKS11* pLoaderCallbacks11 ) { - HRESULT hr = E_FAIL; - D3DXVECTOR3 lower; - D3DXVECTOR3 upper; + DirectX::XMFLOAT3 lower; + DirectX::XMFLOAT3 upper; - m_pDev9 = pDev9; - m_pDev11 = pDev11; + m_pDev11 = pDev11; + + if ( DataBytes < sizeof(SDKMESH_HEADER) ) + return E_FAIL; // Set outstanding resources to zero m_NumOutstandingResources = 0; if( bCopyStatic ) { - SDKMESH_HEADER* pHeader = ( SDKMESH_HEADER* )pData; + auto pHeader = reinterpret_cast( pData ); SIZE_T StaticSize = ( SIZE_T )( pHeader->HeaderSize + pHeader->NonBufferDataSize ); - m_pHeapData = new BYTE[ StaticSize ]; + if ( DataBytes < StaticSize ) + return E_FAIL; + + m_pHeapData = new (std::nothrow) BYTE[ StaticSize ]; if( !m_pHeapData ) - return hr; + return E_OUTOFMEMORY; m_pStaticMeshData = m_pHeapData; - CopyMemory( m_pStaticMeshData, pData, StaticSize ); + memcpy( m_pStaticMeshData, pData, StaticSize ); } else { @@ -416,7 +268,8 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, } // Pointer fixup - m_pMeshHeader = ( SDKMESH_HEADER* )m_pStaticMeshData; + m_pMeshHeader = reinterpret_cast( m_pStaticMeshData ); + m_pVertexBufferArray = ( SDKMESH_VERTEX_BUFFER_HEADER* )( m_pStaticMeshData + m_pMeshHeader->VertexStreamHeadersOffset ); m_pIndexBufferArray = ( SDKMESH_INDEX_BUFFER_HEADER* )( m_pStaticMeshData + @@ -436,8 +289,7 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, // error condition if( m_pMeshHeader->Version != SDKMESH_FILE_VERSION ) { - hr = E_NOINTERFACE; - goto Error; + return E_NOINTERFACE; } // Setup buffer data pointer @@ -447,31 +299,36 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, UINT64 BufferDataStart = m_pMeshHeader->HeaderSize + m_pMeshHeader->NonBufferDataSize; // Create VBs - m_ppVertices = new BYTE*[m_pMeshHeader->NumVertexBuffers]; + m_ppVertices = new (std::nothrow) BYTE*[m_pMeshHeader->NumVertexBuffers]; + if ( !m_ppVertices ) + { + return E_OUTOFMEMORY; + } for( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) { - BYTE* pVertices = NULL; + BYTE* pVertices = nullptr; pVertices = ( BYTE* )( pBufferData + ( m_pVertexBufferArray[i].DataOffset - BufferDataStart ) ); if( pDev11 ) CreateVertexBuffer( pDev11, &m_pVertexBufferArray[i], pVertices, pLoaderCallbacks11 ); - else if( pDev9 ) - CreateVertexBuffer( pDev9, &m_pVertexBufferArray[i], pVertices, pLoaderCallbacks9 ); m_ppVertices[i] = pVertices; } // Create IBs - m_ppIndices = new BYTE*[m_pMeshHeader->NumIndexBuffers]; + m_ppIndices = new (std::nothrow) BYTE*[m_pMeshHeader->NumIndexBuffers]; + if ( !m_ppIndices ) + { + return E_OUTOFMEMORY; + } + for( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) { - BYTE* pIndices = NULL; + BYTE* pIndices = nullptr; pIndices = ( BYTE* )( pBufferData + ( m_pIndexBufferArray[i].DataOffset - BufferDataStart ) ); if( pDev11 ) CreateIndexBuffer( pDev11, &m_pIndexBufferArray[i], pIndices, pLoaderCallbacks11 ); - else if( pDev9 ) - CreateIndexBuffer( pDev9, &m_pIndexBufferArray[i], pIndices, pLoaderCallbacks9 ); m_ppIndices[i] = pIndices; } @@ -479,23 +336,28 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, // Load Materials if( pDev11 ) LoadMaterials( pDev11, m_pMaterialArray, m_pMeshHeader->NumMaterials, pLoaderCallbacks11 ); - else if( pDev9 ) - LoadMaterials( pDev9, m_pMaterialArray, m_pMeshHeader->NumMaterials, pLoaderCallbacks9 ); // Create a place to store our bind pose frame matrices - m_pBindPoseFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ]; + m_pBindPoseFrameMatrices = new (std::nothrow) DirectX::XMFLOAT4X4[ m_pMeshHeader->NumFrames ]; if( !m_pBindPoseFrameMatrices ) - goto Error; + { + return E_OUTOFMEMORY; + } // Create a place to store our transformed frame matrices - m_pTransformedFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ]; + m_pTransformedFrameMatrices = new (std::nothrow) DirectX::XMFLOAT4X4[ m_pMeshHeader->NumFrames ]; if( !m_pTransformedFrameMatrices ) - goto Error; - m_pWorldPoseFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ]; + { + return E_OUTOFMEMORY; + } + + m_pWorldPoseFrameMatrices = new (std::nothrow) DirectX::XMFLOAT4X4[ m_pMeshHeader->NumFrames ]; if( !m_pWorldPoseFrameMatrices ) - goto Error; + { + return E_OUTOFMEMORY; + } - SDKMESH_SUBSET* pSubset = NULL; + SDKMESH_SUBSET* pSubset = nullptr; D3D11_PRIMITIVE_TOPOLOGY PrimType; // update bounding volume @@ -528,10 +390,10 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, IndexStart *= 2; }*/ - //BYTE* pIndices = NULL; + //BYTE* pIndices = nullptr; //m_ppIndices[i] UINT *ind = ( UINT * )m_ppIndices[currentMesh->IndexBuffer]; - FLOAT *verts = ( FLOAT* )m_ppVertices[currentMesh->VertexBuffers[0]]; + float *verts = ( float* )m_ppVertices[currentMesh->VertexBuffers[0]]; UINT stride = (UINT)m_pVertexBufferArray[currentMesh->VertexBuffers[0]].StrideBytes; assert (stride % 4 == 0); stride /=4; @@ -550,7 +412,7 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, current_ind = ind[vertind]; } tris++; - D3DXVECTOR3 *pt = (D3DXVECTOR3*)&(verts[stride * current_ind]); + DirectX::XMFLOAT3 *pt = (DirectX::XMFLOAT3*)&(verts[stride * current_ind]); if (pt->x < lower.x) { lower.x = pt->x; } @@ -575,153 +437,137 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, //pd3dDeviceContext->DrawIndexed( IndexCount, IndexStart, VertexStart ); } - D3DXVECTOR3 half = upper - lower; - half *=0.5f; + DirectX::XMFLOAT3 half( ( upper.x - lower.x ) * 0.5f, + ( upper.y - lower.y ) * 0.5f, + ( upper.z - lower.z ) * 0.5f ); + + currentMesh->BoundingBoxCenter.x = lower.x + half.x; + currentMesh->BoundingBoxCenter.y = lower.y + half.y; + currentMesh->BoundingBoxCenter.z = lower.z + half.z; - currentMesh->BoundingBoxCenter = lower + half; currentMesh->BoundingBoxExtents = half; } // Update - - - hr = S_OK; -Error: - - if( !pLoaderCallbacks9 ) - { - CheckLoadDone(); - } - - return hr; + return S_OK; } + //-------------------------------------------------------------------------------------- // transform bind pose frame using a recursive traversal //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformBindPoseFrame( UINT iFrame, D3DXMATRIX* pParentWorld ) +_Use_decl_annotations_ +void CDXUTSDKMesh::TransformBindPoseFrame( UINT iFrame, CXMMATRIX parentWorld ) { if( !m_pBindPoseFrameMatrices ) return; // Transform ourselves - D3DXMATRIX LocalWorld; - D3DXMatrixMultiply( &LocalWorld, &m_pFrameArray[iFrame].Matrix, pParentWorld ); - m_pBindPoseFrameMatrices[iFrame] = LocalWorld; + XMMATRIX m = XMLoadFloat4x4( &m_pFrameArray[iFrame].Matrix ); + XMMATRIX mLocalWorld = XMMatrixMultiply( m, parentWorld ); + XMStoreFloat4x4( &m_pBindPoseFrameMatrices[iFrame], mLocalWorld ); // Transform our siblings if( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME ) - TransformBindPoseFrame( m_pFrameArray[iFrame].SiblingFrame, pParentWorld ); + { + TransformBindPoseFrame( m_pFrameArray[iFrame].SiblingFrame, parentWorld ); + } // Transform our children if( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME ) - TransformBindPoseFrame( m_pFrameArray[iFrame].ChildFrame, &LocalWorld ); + { + TransformBindPoseFrame( m_pFrameArray[iFrame].ChildFrame, mLocalWorld ); + } } + //-------------------------------------------------------------------------------------- // transform frame using a recursive traversal //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformFrame( UINT iFrame, D3DXMATRIX* pParentWorld, double fTime ) +_Use_decl_annotations_ +void CDXUTSDKMesh::TransformFrame( UINT iFrame, CXMMATRIX parentWorld, double fTime ) { // Get the tick data - D3DXMATRIX LocalTransform; + XMMATRIX mLocalTransform; + UINT iTick = GetAnimationKeyFromTime( fTime ); if( INVALID_ANIMATION_DATA != m_pFrameArray[iFrame].AnimationDataIndex ) { - SDKANIMATION_FRAME_DATA* pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; - SDKANIMATION_DATA* pData = &pFrameData->pAnimationData[ iTick ]; + auto pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; + auto pData = &pFrameData->pAnimationData[ iTick ]; // turn it into a matrix (Ignore scaling for now) - D3DXVECTOR3 parentPos = pData->Translation; - D3DXMATRIX mTranslate; - D3DXMatrixTranslation( &mTranslate, parentPos.x, parentPos.y, parentPos.z ); - - D3DXQUATERNION quat; - D3DXMATRIX mQuat; - quat.w = pData->Orientation.w; - quat.x = pData->Orientation.x; - quat.y = pData->Orientation.y; - quat.z = pData->Orientation.z; - if( quat.w == 0 && quat.x == 0 && quat.y == 0 && quat.z == 0 ) - D3DXQuaternionIdentity( &quat ); - D3DXQuaternionNormalize( &quat, &quat ); - D3DXMatrixRotationQuaternion( &mQuat, &quat ); - LocalTransform = ( mQuat * mTranslate ); + DirectX::XMFLOAT3 parentPos = pData->Translation; + XMMATRIX mTranslate = XMMatrixTranslation( parentPos.x, parentPos.y, parentPos.z ); + + XMVECTOR quat = XMVectorSet( pData->Orientation.x, pData->Orientation.y, pData->Orientation.z, pData->Orientation.w ); + if ( XMVector4Equal( quat, g_XMZero ) ) + quat = XMQuaternionIdentity(); + quat = XMQuaternionNormalize( quat ); + XMMATRIX mQuat = XMMatrixRotationQuaternion( quat ); + mLocalTransform = ( mQuat * mTranslate ); } else { - LocalTransform = m_pFrameArray[iFrame].Matrix; + mLocalTransform = XMLoadFloat4x4( &m_pFrameArray[iFrame].Matrix ); } // Transform ourselves - D3DXMATRIX LocalWorld; - D3DXMatrixMultiply( &LocalWorld, &LocalTransform, pParentWorld ); - m_pTransformedFrameMatrices[iFrame] = LocalWorld; - m_pWorldPoseFrameMatrices[iFrame] = LocalWorld; + XMMATRIX mLocalWorld = XMMatrixMultiply( mLocalTransform, parentWorld ); + XMStoreFloat4x4( &m_pTransformedFrameMatrices[iFrame], mLocalWorld ); + XMStoreFloat4x4( &m_pWorldPoseFrameMatrices[iFrame], mLocalWorld ); // Transform our siblings if( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME ) - TransformFrame( m_pFrameArray[iFrame].SiblingFrame, pParentWorld, fTime ); + { + TransformFrame( m_pFrameArray[iFrame].SiblingFrame, parentWorld, fTime ); + } // Transform our children if( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME ) - TransformFrame( m_pFrameArray[iFrame].ChildFrame, &LocalWorld, fTime ); + { + TransformFrame( m_pFrameArray[iFrame].ChildFrame, mLocalWorld, fTime ); + } } + //-------------------------------------------------------------------------------------- // transform frame assuming that it is an absolute transformation //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::TransformFrameAbsolute( UINT iFrame, double fTime ) { - D3DXMATRIX mTrans1; - D3DXMATRIX mTrans2; - D3DXMATRIX mRot1; - D3DXMATRIX mRot2; - D3DXQUATERNION quat1; - D3DXQUATERNION quat2; - D3DXMATRIX mTo; - D3DXMATRIX mInvTo; - D3DXMATRIX mFrom; - UINT iTick = GetAnimationKeyFromTime( fTime ); if( INVALID_ANIMATION_DATA != m_pFrameArray[iFrame].AnimationDataIndex ) { - SDKANIMATION_FRAME_DATA* pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; - SDKANIMATION_DATA* pData = &pFrameData->pAnimationData[ iTick ]; - SDKANIMATION_DATA* pDataOrig = &pFrameData->pAnimationData[ 0 ]; - - D3DXMatrixTranslation( &mTrans1, -pDataOrig->Translation.x, - -pDataOrig->Translation.y, - -pDataOrig->Translation.z ); - D3DXMatrixTranslation( &mTrans2, pData->Translation.x, - pData->Translation.y, - pData->Translation.z ); - - quat1.x = pDataOrig->Orientation.x; - quat1.y = pDataOrig->Orientation.y; - quat1.z = pDataOrig->Orientation.z; - quat1.w = pDataOrig->Orientation.w; - D3DXQuaternionInverse( &quat1, &quat1 ); - D3DXMatrixRotationQuaternion( &mRot1, &quat1 ); - mInvTo = mTrans1 * mRot1; - - quat2.x = pData->Orientation.x; - quat2.y = pData->Orientation.y; - quat2.z = pData->Orientation.z; - quat2.w = pData->Orientation.w; - D3DXMatrixRotationQuaternion( &mRot2, &quat2 ); - mFrom = mRot2 * mTrans2; - - D3DXMATRIX mOutput = mInvTo * mFrom; - m_pTransformedFrameMatrices[iFrame] = mOutput; + auto pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; + auto pData = &pFrameData->pAnimationData[ iTick ]; + auto pDataOrig = &pFrameData->pAnimationData[ 0 ]; + + XMMATRIX mTrans1 = XMMatrixTranslation( -pDataOrig->Translation.x, -pDataOrig->Translation.y, -pDataOrig->Translation.z ); + XMMATRIX mTrans2 = XMMatrixTranslation( pData->Translation.x, pData->Translation.y, pData->Translation.z ); + + XMVECTOR quat1 = XMVectorSet( pDataOrig->Orientation.x, pDataOrig->Orientation.y, pDataOrig->Orientation.z, pDataOrig->Orientation.w ); + quat1 = XMQuaternionInverse( quat1 ); + XMMATRIX mRot1 = XMMatrixRotationQuaternion( quat1 ); + XMMATRIX mInvTo = mTrans1 * mRot1; + + XMVECTOR quat2 = XMVectorSet( pData->Orientation.x, pData->Orientation.y, pData->Orientation.z, pData->Orientation.w ); + XMMATRIX mRot2 = XMMatrixRotationQuaternion( quat2 ); + XMMATRIX mFrom = mRot2 * mTrans2; + + XMMATRIX mOutput = mInvTo * mFrom; + XMStoreFloat4x4( &m_pTransformedFrameMatrices[iFrame], mOutput ); } } #define MAX_D3D11_VERTEX_STREAMS D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::RenderMesh( UINT iMesh, bool bAdjacent, ID3D11DeviceContext* pd3dDeviceContext, @@ -732,7 +578,7 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, if( 0 < GetOutstandingBufferResources() ) return; - SDKMESH_MESH* pMesh = &m_pMeshArray[iMesh]; + auto pMesh = &m_pMeshArray[iMesh]; UINT Strides[MAX_D3D11_VERTEX_STREAMS]; UINT Offsets[MAX_D3D11_VERTEX_STREAMS]; @@ -754,7 +600,7 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, else pIndexBufferArray = m_pIndexBufferArray; - ID3D11Buffer* pIB = pIndexBufferArray[ pMesh->IndexBuffer ].pIB11; + auto pIB = pIndexBufferArray[ pMesh->IndexBuffer ].pIB11; DXGI_FORMAT ibFormat = DXGI_FORMAT_R16_UINT; switch( pIndexBufferArray[ pMesh->IndexBuffer ].IndexType ) { @@ -769,8 +615,8 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, pd3dDeviceContext->IASetVertexBuffers( 0, pMesh->NumVertexBuffers, pVB, Strides, Offsets ); pd3dDeviceContext->IASetIndexBuffer( pIB, ibFormat, 0 ); - SDKMESH_SUBSET* pSubset = NULL; - SDKMESH_MATERIAL* pMat = NULL; + SDKMESH_SUBSET* pSubset = nullptr; + SDKMESH_MATERIAL* pMat = nullptr; D3D11_PRIMITIVE_TOPOLOGY PrimType; for( UINT subset = 0; subset < pMesh->NumSubsets; subset++ ) @@ -821,6 +667,7 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::RenderFrame( UINT iFrame, bool bAdjacent, ID3D11DeviceContext* pd3dDeviceContext, @@ -853,140 +700,33 @@ void CDXUTSDKMesh::RenderFrame( UINT iFrame, } //-------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::RenderMesh( UINT iMesh, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ) -{ - if( 0 < GetOutstandingBufferResources() ) - return; - - SDKMESH_MESH* pMesh = &m_pMeshArray[iMesh]; - - // set vb streams - for( UINT i = 0; i < ( UINT )pMesh->NumVertexBuffers; i++ ) - { - pd3dDevice->SetStreamSource( i, - m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].pVB9, - 0, - ( UINT )m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].StrideBytes ); - } - - // Set our index buffer as well - pd3dDevice->SetIndices( m_pIndexBufferArray[ pMesh->IndexBuffer ].pIB9 ); - - // Render the scene with this technique - pEffect->SetTechnique( hTechnique ); - - SDKMESH_SUBSET* pSubset = NULL; - SDKMESH_MATERIAL* pMat = NULL; - D3DPRIMITIVETYPE PrimType; - UINT cPasses = 0; - pEffect->Begin( &cPasses, 0 ); - - for( UINT p = 0; p < cPasses; ++p ) - { - pEffect->BeginPass( p ); - - for( UINT subset = 0; subset < pMesh->NumSubsets; subset++ ) - { - pSubset = &m_pSubsetArray[ pMesh->pSubsets[subset] ]; - - PrimType = GetPrimitiveType9( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType ); - - if( INVALID_MATERIAL != pSubset->MaterialID && m_pMeshHeader->NumMaterials > 0 ) - { - pMat = &m_pMaterialArray[ pSubset->MaterialID ]; - if( htxDiffuse && !IsErrorResource( pMat->pDiffuseTexture9 ) ) - pEffect->SetTexture( htxDiffuse, pMat->pDiffuseTexture9 ); - if( htxNormal && !IsErrorResource( pMat->pNormalTexture9 ) ) - pEffect->SetTexture( htxNormal, pMat->pNormalTexture9 ); - if( htxSpecular && !IsErrorResource( pMat->pSpecularTexture9 ) ) - pEffect->SetTexture( htxSpecular, pMat->pSpecularTexture9 ); - } - - pEffect->CommitChanges(); - - UINT PrimCount = ( UINT )pSubset->IndexCount; - UINT IndexStart = ( UINT )pSubset->IndexStart; - UINT VertexStart = ( UINT )pSubset->VertexStart; - UINT VertexCount = ( UINT )pSubset->VertexCount; - if( D3DPT_TRIANGLELIST == PrimType ) - PrimCount /= 3; - if( D3DPT_LINELIST == PrimType ) - PrimCount /= 2; - if( D3DPT_TRIANGLESTRIP == PrimType ) - PrimCount = ( PrimCount - 3 ) + 1; - if( D3DPT_LINESTRIP == PrimType ) - PrimCount -= 1; - - pd3dDevice->DrawIndexedPrimitive( PrimType, VertexStart, 0, VertexCount, IndexStart, PrimCount ); - } - - pEffect->EndPass(); - } - - pEffect->End(); -} - -//-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::RenderFrame( UINT iFrame, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ) -{ - if( !m_pStaticMeshData || !m_pFrameArray ) - return; - - if( m_pFrameArray[iFrame].Mesh != INVALID_MESH ) - { - RenderMesh( m_pFrameArray[iFrame].Mesh, - pd3dDevice, - pEffect, - hTechnique, - htxDiffuse, - htxNormal, - htxSpecular ); - } - - // Render our children - if( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME ) - RenderFrame( m_pFrameArray[iFrame].ChildFrame, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal, - htxSpecular ); - - // Render our siblings - if( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME ) - RenderFrame( m_pFrameArray[iFrame].SiblingFrame, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal, - htxSpecular ); -} - - -//-------------------------------------------------------------------------------------- -CDXUTSDKMesh::CDXUTSDKMesh() : m_NumOutstandingResources( 0 ), - m_bLoading( false ), - m_hFile( 0 ), - m_hFileMappingObject( 0 ), - m_pMeshHeader( NULL ), - m_pStaticMeshData( NULL ), - m_pHeapData( NULL ), - m_pAdjacencyIndexBufferArray( NULL ), - m_pAnimationData( NULL ), - m_pAnimationHeader( NULL ), - m_ppVertices( NULL ), - m_ppIndices( NULL ), - m_pBindPoseFrameMatrices( NULL ), - m_pTransformedFrameMatrices( NULL ), - m_pWorldPoseFrameMatrices( NULL ), - m_pDev9( NULL ), - m_pDev11( NULL ) +CDXUTSDKMesh::CDXUTSDKMesh() noexcept : + m_NumOutstandingResources(0), + m_bLoading(false), + m_hFile(0), + m_hFileMappingObject(0), + m_pDev11(nullptr), + m_pDevContext11(nullptr), + m_pStaticMeshData(nullptr), + m_pHeapData(nullptr), + m_pAnimationData(nullptr), + m_ppVertices(nullptr), + m_ppIndices(nullptr), + m_strPathW{}, + m_strPath{}, + m_pMeshHeader(nullptr), + m_pVertexBufferArray(nullptr), + m_pIndexBufferArray(nullptr), + m_pMeshArray(nullptr), + m_pSubsetArray(nullptr), + m_pFrameArray(nullptr), + m_pMaterialArray(nullptr), + m_pAdjacencyIndexBufferArray(nullptr), + m_pAnimationHeader(nullptr), + m_pAnimationFrameData(nullptr), + m_pBindPoseFrameMatrices(nullptr), + m_pTransformedFrameMatrices(nullptr), + m_pWorldPoseFrameMatrices(nullptr) { } @@ -998,38 +738,22 @@ CDXUTSDKMesh::~CDXUTSDKMesh() } //-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, LPCTSTR szFileName, bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS11* pLoaderCallbacks ) +_Use_decl_annotations_ +HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, LPCWSTR szFileName, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { - return CreateFromFile( pDev11, NULL, szFileName, bCreateAdjacencyIndices, pLoaderCallbacks, NULL ); + return CreateFromFile( pDev11, szFileName, pLoaderCallbacks ); } //-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( IDirect3DDevice9* pDev9, LPCTSTR szFileName, bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS9* pLoaderCallbacks ) +_Use_decl_annotations_ +HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, BYTE* pData, size_t DataBytes, bool bCopyStatic, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { - return CreateFromFile( NULL, pDev9, szFileName, bCreateAdjacencyIndices, NULL, pLoaderCallbacks ); + return CreateFromMemory( pDev11, pData, DataBytes, bCopyStatic, pLoaderCallbacks ); } -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, BYTE* pData, UINT DataBytes, bool bCreateAdjacencyIndices, - bool bCopyStatic, SDKMESH_CALLBACKS11* pLoaderCallbacks ) -{ - return CreateFromMemory( pDev11, NULL, pData, DataBytes, bCreateAdjacencyIndices, bCopyStatic, - pLoaderCallbacks, NULL ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( IDirect3DDevice9* pDev9, BYTE* pData, UINT DataBytes, bool bCreateAdjacencyIndices, - bool bCopyStatic, SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - return CreateFromMemory( NULL, pDev9, pData, DataBytes, bCreateAdjacencyIndices, bCopyStatic, NULL, - pLoaderCallbacks ); -} //-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::LoadAnimation( WCHAR* szFileName ) +HRESULT CDXUTSDKMesh::LoadAnimation( _In_z_ const WCHAR* szFileName ) { HRESULT hr = E_FAIL; DWORD dwBytesRead = 0; @@ -1040,32 +764,42 @@ HRESULT CDXUTSDKMesh::LoadAnimation( WCHAR* szFileName ) V_RETURN( DXUTFindDXSDKMediaFileCch( strPath, MAX_PATH, szFileName ) ); // Open the file - HANDLE hFile = CreateFile( strPath, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_FLAG_SEQUENTIAL_SCAN, NULL ); + HANDLE hFile = CreateFile( strPath, FILE_READ_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_SEQUENTIAL_SCAN, nullptr ); if( INVALID_HANDLE_VALUE == hFile ) return DXUTERR_MEDIANOTFOUND; ///////////////////////// // Header SDKANIMATION_FILE_HEADER fileheader; - if( !ReadFile( hFile, &fileheader, sizeof( SDKANIMATION_FILE_HEADER ), &dwBytesRead, NULL ) ) - goto Error; + if( !ReadFile( hFile, &fileheader, sizeof( SDKANIMATION_FILE_HEADER ), &dwBytesRead, nullptr ) ) + { + CloseHandle(hFile); + return HRESULT_FROM_WIN32(GetLastError()); + } //allocate - m_pAnimationData = new BYTE[ ( size_t )( sizeof( SDKANIMATION_FILE_HEADER ) + fileheader.AnimationDataSize ) ]; + m_pAnimationData = new (std::nothrow) BYTE[ ( size_t )( sizeof( SDKANIMATION_FILE_HEADER ) + fileheader.AnimationDataSize ) ]; if( !m_pAnimationData ) { - hr = E_OUTOFMEMORY; - goto Error; + CloseHandle(hFile); + return E_OUTOFMEMORY; } // read it all in liMove.QuadPart = 0; - if( !SetFilePointerEx( hFile, liMove, NULL, FILE_BEGIN ) ) - goto Error; + if( !SetFilePointerEx( hFile, liMove, nullptr, FILE_BEGIN ) ) + { + CloseHandle(hFile); + return HRESULT_FROM_WIN32(GetLastError()); + } + if( !ReadFile( hFile, m_pAnimationData, ( DWORD )( sizeof( SDKANIMATION_FILE_HEADER ) + - fileheader.AnimationDataSize ), &dwBytesRead, NULL ) ) - goto Error; + fileheader.AnimationDataSize ), &dwBytesRead, nullptr ) ) + { + CloseHandle(hFile); + return HRESULT_FROM_WIN32(GetLastError()); + } // pointer fixup m_pAnimationHeader = ( SDKANIMATION_FILE_HEADER* )m_pAnimationData; @@ -1077,17 +811,14 @@ HRESULT CDXUTSDKMesh::LoadAnimation( WCHAR* szFileName ) m_pAnimationFrameData[i].pAnimationData = ( SDKANIMATION_DATA* )( m_pAnimationData + m_pAnimationFrameData[i].DataOffset + BaseOffset ); - SDKMESH_FRAME* pFrame = FindFrame( m_pAnimationFrameData[i].FrameName ); + auto pFrame = FindFrame( m_pAnimationFrameData[i].FrameName ); if( pFrame ) { pFrame->AnimationDataIndex = i; } } - hr = S_OK; -Error: - CloseHandle( hFile ); - return hr; + return S_OK; } //-------------------------------------------------------------------------------------- @@ -1102,18 +833,8 @@ void CDXUTSDKMesh::Destroy() { for( UINT64 m = 0; m < m_pMeshHeader->NumMaterials; m++ ) { - if( m_pDev9 ) - { - if( !IsErrorResource( m_pMaterialArray[m].pDiffuseTexture9 ) ) - SAFE_RELEASE( m_pMaterialArray[m].pDiffuseTexture9 ); - if( !IsErrorResource( m_pMaterialArray[m].pNormalTexture9 ) ) - SAFE_RELEASE( m_pMaterialArray[m].pNormalTexture9 ); - if( !IsErrorResource( m_pMaterialArray[m].pSpecularTexture9 ) ) - SAFE_RELEASE( m_pMaterialArray[m].pSpecularTexture9 ); - } - else if( m_pDev11 ) + if( m_pDev11 ) { - //ID3D11Resource* pRes = NULL; if( m_pMaterialArray[m].pDiffuseRV11 && !IsErrorResource( m_pMaterialArray[m].pDiffuseRV11 ) ) { //m_pMaterialArray[m].pDiffuseRV11->GetResource( &pRes ); @@ -1138,17 +859,14 @@ void CDXUTSDKMesh::Destroy() } } } - for( UINT64 i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) { - if( !IsErrorResource( m_pVertexBufferArray[i].pVB9 ) ) - SAFE_RELEASE( m_pVertexBufferArray[i].pVB9 ); + SAFE_RELEASE( m_pVertexBufferArray[i].pVB11 ); } for( UINT64 i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) { - if( !IsErrorResource( m_pIndexBufferArray[i].pIB9 ) ) - SAFE_RELEASE( m_pIndexBufferArray[i].pIB9 ); + SAFE_RELEASE( m_pIndexBufferArray[i].pIB11 ); } } @@ -1162,7 +880,7 @@ void CDXUTSDKMesh::Destroy() SAFE_DELETE_ARRAY( m_pAdjacencyIndexBufferArray ); SAFE_DELETE_ARRAY( m_pHeapData ); - m_pStaticMeshData = NULL; + m_pStaticMeshData = nullptr; SAFE_DELETE_ARRAY( m_pAnimationData ); SAFE_DELETE_ARRAY( m_pBindPoseFrameMatrices ); SAFE_DELETE_ARRAY( m_pTransformedFrameMatrices ); @@ -1171,45 +889,39 @@ void CDXUTSDKMesh::Destroy() SAFE_DELETE_ARRAY( m_ppVertices ); SAFE_DELETE_ARRAY( m_ppIndices ); - m_pMeshHeader = NULL; - m_pVertexBufferArray = NULL; - m_pIndexBufferArray = NULL; - m_pMeshArray = NULL; - m_pSubsetArray = NULL; - m_pFrameArray = NULL; - m_pMaterialArray = NULL; + m_pMeshHeader = nullptr; + m_pVertexBufferArray = nullptr; + m_pIndexBufferArray = nullptr; + m_pMeshArray = nullptr; + m_pSubsetArray = nullptr; + m_pFrameArray = nullptr; + m_pMaterialArray = nullptr; - m_pAnimationHeader = NULL; - m_pAnimationFrameData = NULL; + m_pAnimationHeader = nullptr; + m_pAnimationFrameData = nullptr; } -//-------------------------------------------------------------------------------------- -// transform the bind pose -//-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformBindPose( D3DXMATRIX* pWorld ) -{ - TransformBindPoseFrame( 0, pWorld ); -} //-------------------------------------------------------------------------------------- // transform the mesh frames according to the animation for time fTime //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformMesh( D3DXMATRIX* pWorld, double fTime ) +_Use_decl_annotations_ +void CDXUTSDKMesh::TransformMesh( CXMMATRIX world, double fTime ) { - if( m_pAnimationHeader == NULL || FTT_RELATIVE == m_pAnimationHeader->FrameTransformType ) + if( !m_pAnimationHeader || FTT_RELATIVE == m_pAnimationHeader->FrameTransformType ) { - TransformFrame( 0, pWorld, fTime ); + TransformFrame( 0, world, fTime ); // For each frame, move the transform to the bind pose, then // move it to the final position - D3DXMATRIX mInvBindPose; - D3DXMATRIX mFinal; for( UINT i = 0; i < m_pMeshHeader->NumFrames; i++ ) { - D3DXMatrixInverse( &mInvBindPose, NULL, &m_pBindPoseFrameMatrices[i] ); - mFinal = mInvBindPose * m_pTransformedFrameMatrices[i]; - m_pTransformedFrameMatrices[i] = mFinal; + XMMATRIX m = XMLoadFloat4x4( &m_pBindPoseFrameMatrices[i] ); + XMMATRIX mInvBindPose = XMMatrixInverse( nullptr, m ); + m = XMLoadFloat4x4( &m_pTransformedFrameMatrices[i] ); + XMMATRIX mFinal = mInvBindPose * m; + XMStoreFloat4x4( &m_pTransformedFrameMatrices[i], mFinal ); } } else if( FTT_ABSOLUTE == m_pAnimationHeader->FrameTransformType ) @@ -1221,6 +933,7 @@ void CDXUTSDKMesh::TransformMesh( D3DXMATRIX* pWorld, double fTime ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::Render( ID3D11DeviceContext* pd3dDeviceContext, UINT iDiffuseSlot, UINT iNormalSlot, @@ -1230,6 +943,7 @@ void CDXUTSDKMesh::Render( ID3D11DeviceContext* pd3dDeviceContext, } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::RenderAdjacent( ID3D11DeviceContext* pd3dDeviceContext, UINT iDiffuseSlot, UINT iNormalSlot, @@ -1240,18 +954,7 @@ void CDXUTSDKMesh::RenderAdjacent( ID3D11DeviceContext* pd3dDeviceContext, //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ) -{ - RenderFrame( 0, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal, htxSpecular ); -} - -//-------------------------------------------------------------------------------------- -D3D11_PRIMITIVE_TOPOLOGY CDXUTSDKMesh::GetPrimitiveType11( SDKMESH_PRIMITIVE_TYPE PrimType ) +D3D11_PRIMITIVE_TOPOLOGY CDXUTSDKMesh::GetPrimitiveType11( _In_ SDKMESH_PRIMITIVE_TYPE PrimType ) { D3D11_PRIMITIVE_TOPOLOGY retType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; @@ -1290,7 +993,7 @@ D3D11_PRIMITIVE_TOPOLOGY CDXUTSDKMesh::GetPrimitiveType11( SDKMESH_PRIMITIVE_TYP } //-------------------------------------------------------------------------------------- -DXGI_FORMAT CDXUTSDKMesh::GetIBFormat11( UINT iMesh ) +DXGI_FORMAT CDXUTSDKMesh::GetIBFormat11( _In_ UINT iMesh ) const { switch( m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].IndexType ) { @@ -1303,100 +1006,48 @@ DXGI_FORMAT CDXUTSDKMesh::GetIBFormat11( UINT iMesh ) } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetVB11( UINT iMesh, UINT iVB ) +ID3D11Buffer* CDXUTSDKMesh::GetVB11( _In_ UINT iMesh, _In_ UINT iVB ) const { return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].pVB11; } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetIB11( UINT iMesh ) +ID3D11Buffer* CDXUTSDKMesh::GetIB11( _In_ UINT iMesh ) const { return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB11; } -SDKMESH_INDEX_TYPE CDXUTSDKMesh::GetIndexType( UINT iMesh ) +SDKMESH_INDEX_TYPE CDXUTSDKMesh::GetIndexType( _In_ UINT iMesh ) const { return ( SDKMESH_INDEX_TYPE ) m_pIndexBufferArray[m_pMeshArray[ iMesh ].IndexBuffer].IndexType; } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetAdjIB11( UINT iMesh ) +ID3D11Buffer* CDXUTSDKMesh::GetAdjIB11( _In_ UINT iMesh ) const { return m_pAdjacencyIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB11; } //-------------------------------------------------------------------------------------- -D3DPRIMITIVETYPE CDXUTSDKMesh::GetPrimitiveType9( SDKMESH_PRIMITIVE_TYPE PrimType ) +const char* CDXUTSDKMesh::GetMeshPathA() const { - D3DPRIMITIVETYPE retType = D3DPT_TRIANGLELIST; - - switch( PrimType ) - { - case PT_TRIANGLE_LIST: - retType = D3DPT_TRIANGLELIST; - break; - case PT_TRIANGLE_STRIP: - retType = D3DPT_TRIANGLESTRIP; - break; - case PT_LINE_LIST: - retType = D3DPT_LINELIST; - break; - case PT_LINE_STRIP: - retType = D3DPT_LINESTRIP; - break; - case PT_POINT_LIST: - retType = D3DPT_POINTLIST; - break; - }; - - return retType; + return m_strPath; } //-------------------------------------------------------------------------------------- -D3DFORMAT CDXUTSDKMesh::GetIBFormat9( UINT iMesh ) +const WCHAR* CDXUTSDKMesh::GetMeshPathW() const { - switch( m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].IndexType ) - { - case IT_16BIT: - return D3DFMT_INDEX16; - case IT_32BIT: - return D3DFMT_INDEX32; - }; - return D3DFMT_INDEX16; + return m_strPathW; } //-------------------------------------------------------------------------------------- -IDirect3DVertexBuffer9* CDXUTSDKMesh::GetVB9( UINT iMesh, UINT iVB ) +UINT CDXUTSDKMesh::GetNumMeshes() const { - return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].pVB9; + if( !m_pMeshHeader ) + return 0; + return m_pMeshHeader->NumMeshes; } //-------------------------------------------------------------------------------------- -IDirect3DIndexBuffer9* CDXUTSDKMesh::GetIB9( UINT iMesh ) -{ - return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB9; -} - -//-------------------------------------------------------------------------------------- -char* CDXUTSDKMesh::GetMeshPathA() -{ - return m_strPath; -} - -//-------------------------------------------------------------------------------------- -WCHAR* CDXUTSDKMesh::GetMeshPathW() -{ - return m_strPathW; -} - -//-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumMeshes() -{ - if( !m_pMeshHeader ) - return 0; - return m_pMeshHeader->NumMeshes; -} - -//-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumMaterials() +UINT CDXUTSDKMesh::GetNumMaterials() const { if( !m_pMeshHeader ) return 0; @@ -1404,7 +1055,7 @@ UINT CDXUTSDKMesh::GetNumMaterials() } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumVBs() +UINT CDXUTSDKMesh::GetNumVBs() const { if( !m_pMeshHeader ) return 0; @@ -1412,7 +1063,7 @@ UINT CDXUTSDKMesh::GetNumVBs() } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumIBs() +UINT CDXUTSDKMesh::GetNumIBs() const { if( !m_pMeshHeader ) return 0; @@ -1420,86 +1071,74 @@ UINT CDXUTSDKMesh::GetNumIBs() } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetVB11At( UINT iVB ) +ID3D11Buffer* CDXUTSDKMesh::GetVB11At( _In_ UINT iVB ) const { return m_pVertexBufferArray[ iVB ].pVB11; } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetIB11At( UINT iIB ) +ID3D11Buffer* CDXUTSDKMesh::GetIB11At( _In_ UINT iIB ) const { return m_pIndexBufferArray[ iIB ].pIB11; } //-------------------------------------------------------------------------------------- -IDirect3DVertexBuffer9* CDXUTSDKMesh::GetVB9At( UINT iVB ) -{ - return m_pVertexBufferArray[ iVB ].pVB9; -} - -//-------------------------------------------------------------------------------------- -IDirect3DIndexBuffer9* CDXUTSDKMesh::GetIB9At( UINT iIB ) -{ - return m_pIndexBufferArray[ iIB ].pIB9; -} - -//-------------------------------------------------------------------------------------- -BYTE* CDXUTSDKMesh::GetRawVerticesAt( UINT iVB ) +BYTE* CDXUTSDKMesh::GetRawVerticesAt( _In_ UINT iVB ) const { return m_ppVertices[iVB]; } //-------------------------------------------------------------------------------------- -BYTE* CDXUTSDKMesh::GetRawIndicesAt( UINT iIB ) +BYTE* CDXUTSDKMesh::GetRawIndicesAt( _In_ UINT iIB ) const { return m_ppIndices[iIB]; } //-------------------------------------------------------------------------------------- -SDKMESH_MATERIAL* CDXUTSDKMesh::GetMaterial( UINT iMaterial ) +SDKMESH_MATERIAL* CDXUTSDKMesh::GetMaterial( _In_ UINT iMaterial ) const { return &m_pMaterialArray[ iMaterial ]; } //-------------------------------------------------------------------------------------- -SDKMESH_MESH* CDXUTSDKMesh::GetMesh( UINT iMesh ) +SDKMESH_MESH* CDXUTSDKMesh::GetMesh( _In_ UINT iMesh ) const { return &m_pMeshArray[ iMesh ]; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumSubsets( UINT iMesh ) +UINT CDXUTSDKMesh::GetNumSubsets( _In_ UINT iMesh ) const { return m_pMeshArray[ iMesh ].NumSubsets; } //-------------------------------------------------------------------------------------- -SDKMESH_SUBSET* CDXUTSDKMesh::GetSubset( UINT iMesh, UINT iSubset ) +SDKMESH_SUBSET* CDXUTSDKMesh::GetSubset( _In_ UINT iMesh, _In_ UINT iSubset ) const { return &m_pSubsetArray[ m_pMeshArray[ iMesh ].pSubsets[iSubset] ]; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetVertexStride( UINT iMesh, UINT iVB ) +UINT CDXUTSDKMesh::GetVertexStride( _In_ UINT iMesh, _In_ UINT iVB ) const { return ( UINT )m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].StrideBytes; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumFrames() +UINT CDXUTSDKMesh::GetNumFrames() const { return m_pMeshHeader->NumFrames; } //-------------------------------------------------------------------------------------- -SDKMESH_FRAME* CDXUTSDKMesh::GetFrame( UINT iFrame ) +SDKMESH_FRAME* CDXUTSDKMesh::GetFrame( _In_ UINT iFrame ) const { assert( iFrame < m_pMeshHeader->NumFrames ); return &m_pFrameArray[ iFrame ]; } //-------------------------------------------------------------------------------------- -SDKMESH_FRAME* CDXUTSDKMesh::FindFrame( char* pszName ) +SDKMESH_FRAME* CDXUTSDKMesh::FindFrame( _In_z_ const char* pszName ) const { for( UINT i = 0; i < m_pMeshHeader->NumFrames; i++ ) { @@ -1508,35 +1147,35 @@ SDKMESH_FRAME* CDXUTSDKMesh::FindFrame( char* pszName ) return &m_pFrameArray[i]; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -UINT64 CDXUTSDKMesh::GetNumVertices( UINT iMesh, UINT iVB ) +UINT64 CDXUTSDKMesh::GetNumVertices( _In_ UINT iMesh, _In_ UINT iVB ) const { return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].NumVertices; } //-------------------------------------------------------------------------------------- -UINT64 CDXUTSDKMesh::GetNumIndices( UINT iMesh ) +UINT64 CDXUTSDKMesh::GetNumIndices( _In_ UINT iMesh ) const { return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].NumIndices; } //-------------------------------------------------------------------------------------- -D3DXVECTOR3 CDXUTSDKMesh::GetMeshBBoxCenter( UINT iMesh ) +XMVECTOR CDXUTSDKMesh::GetMeshBBoxCenter( _In_ UINT iMesh ) const { - return m_pMeshArray[iMesh].BoundingBoxCenter; + return XMLoadFloat3( &m_pMeshArray[iMesh].BoundingBoxCenter ); } //-------------------------------------------------------------------------------------- -D3DXVECTOR3 CDXUTSDKMesh::GetMeshBBoxExtents( UINT iMesh ) +XMVECTOR CDXUTSDKMesh::GetMeshBBoxExtents( _In_ UINT iMesh ) const { - return m_pMeshArray[iMesh].BoundingBoxExtents; + return XMLoadFloat3( &m_pMeshArray[iMesh].BoundingBoxExtents ); } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetOutstandingResources() +UINT CDXUTSDKMesh::GetOutstandingResources() const { UINT outstandingResources = 0; if( !m_pMeshHeader ) @@ -1544,9 +1183,9 @@ UINT CDXUTSDKMesh::GetOutstandingResources() outstandingResources += GetOutstandingBufferResources(); - if( m_pDev11 ) - { - for( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ ) + if( m_pDev11 ) + { + for( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ ) { if( m_pMaterialArray[i].DiffuseTexture[0] != 0 ) { @@ -1566,54 +1205,18 @@ UINT CDXUTSDKMesh::GetOutstandingResources() outstandingResources ++; } } - } - else - { - for( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ ) - { - if( m_pMaterialArray[i].DiffuseTexture[0] != 0 ) - { - if( !m_pMaterialArray[i].pDiffuseTexture9 && !IsErrorResource( m_pMaterialArray[i].pDiffuseTexture9 ) ) - outstandingResources ++; - } - - if( m_pMaterialArray[i].NormalTexture[0] != 0 ) - { - if( !m_pMaterialArray[i].pNormalTexture9 && !IsErrorResource( m_pMaterialArray[i].pNormalTexture9 ) ) - outstandingResources ++; - } - - if( m_pMaterialArray[i].SpecularTexture[0] != 0 ) - { - if( !m_pMaterialArray[i].pSpecularTexture9 && - !IsErrorResource( m_pMaterialArray[i].pSpecularTexture9 ) ) - outstandingResources ++; - } - } } return outstandingResources; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetOutstandingBufferResources() +UINT CDXUTSDKMesh::GetOutstandingBufferResources() const { UINT outstandingResources = 0; if( !m_pMeshHeader ) return 1; - for( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) - { - if( !m_pVertexBufferArray[i].pVB9 && !IsErrorResource( m_pVertexBufferArray[i].pVB9 ) ) - outstandingResources ++; - } - - for( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) - { - if( !m_pIndexBufferArray[i].pIB9 && !IsErrorResource( m_pIndexBufferArray[i].pIB9 ) ) - outstandingResources ++; - } - return outstandingResources; } @@ -1630,7 +1233,7 @@ bool CDXUTSDKMesh::CheckLoadDone() } //-------------------------------------------------------------------------------------- -bool CDXUTSDKMesh::IsLoaded() +bool CDXUTSDKMesh::IsLoaded() const { if( m_pStaticMeshData && !m_bLoading ) { @@ -1641,65 +1244,51 @@ bool CDXUTSDKMesh::IsLoaded() } //-------------------------------------------------------------------------------------- -bool CDXUTSDKMesh::IsLoading() +bool CDXUTSDKMesh::IsLoading() const { return m_bLoading; } //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::SetLoading( bool bLoading ) +void CDXUTSDKMesh::SetLoading( _In_ bool bLoading ) { m_bLoading = bLoading; } //-------------------------------------------------------------------------------------- -BOOL CDXUTSDKMesh::HadLoadingError() +BOOL CDXUTSDKMesh::HadLoadingError() const { - if( m_pMeshHeader ) - { - for( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) - { - if( IsErrorResource( m_pVertexBufferArray[i].pVB9 ) ) - return TRUE; - } - - for( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) - { - if( IsErrorResource( m_pIndexBufferArray[i].pIB9 ) ) - return TRUE; - } - } - return FALSE; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumInfluences( UINT iMesh ) +UINT CDXUTSDKMesh::GetNumInfluences( _In_ UINT iMesh ) const { return m_pMeshArray[iMesh].NumFrameInfluences; } //-------------------------------------------------------------------------------------- -const D3DXMATRIX* CDXUTSDKMesh::GetMeshInfluenceMatrix( UINT iMesh, UINT iInfluence ) +XMMATRIX CDXUTSDKMesh::GetMeshInfluenceMatrix( _In_ UINT iMesh, _In_ UINT iInfluence ) const { UINT iFrame = m_pMeshArray[iMesh].pFrameInfluences[ iInfluence ]; - return &m_pTransformedFrameMatrices[iFrame]; + return XMLoadFloat4x4( &m_pTransformedFrameMatrices[iFrame] ); } -const D3DXMATRIX* CDXUTSDKMesh::GetWorldMatrix( UINT iFrameIndex ) +XMMATRIX CDXUTSDKMesh::GetWorldMatrix( _In_ UINT iFrameIndex ) const { - return &m_pWorldPoseFrameMatrices[iFrameIndex]; + return XMLoadFloat4x4( &m_pWorldPoseFrameMatrices[iFrameIndex] ); } -const D3DXMATRIX* CDXUTSDKMesh::GetInfluenceMatrix( UINT iFrameIndex ) +XMMATRIX CDXUTSDKMesh::GetInfluenceMatrix( _In_ UINT iFrameIndex ) const { - return &m_pTransformedFrameMatrices[iFrameIndex]; + return XMLoadFloat4x4( &m_pTransformedFrameMatrices[iFrameIndex] ); } + //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetAnimationKeyFromTime( double fTime ) +UINT CDXUTSDKMesh::GetAnimationKeyFromTime( _In_ double fTime ) const { - if( m_pAnimationHeader == NULL ) + if( !m_pAnimationHeader ) { return 0; } @@ -1712,638 +1301,18 @@ UINT CDXUTSDKMesh::GetAnimationKeyFromTime( double fTime ) return iTick; } -bool CDXUTSDKMesh::GetAnimationProperties( UINT* pNumKeys, FLOAT* pFrameTime ) +_Use_decl_annotations_ +bool CDXUTSDKMesh::GetAnimationProperties( UINT* pNumKeys, float* pFrameTime ) const { - if( m_pAnimationHeader == NULL ) + if( !m_pAnimationHeader ) { + *pNumKeys = 0; + *pFrameTime = 0; return false; } *pNumKeys = m_pAnimationHeader->NumAnimationKeys; - *pFrameTime = 1.0f / (FLOAT)m_pAnimationHeader->AnimationFPS; + *pFrameTime = 1.0f / (float)m_pAnimationHeader->AnimationFPS; return true; } - - -//------------------------------------------------------------------------------------- -// CDXUTXFileMesh implementation. -//------------------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -CDXUTXFileMesh::CDXUTXFileMesh( LPCWSTR strName ) -{ - wcscpy_s( m_strName, 512, strName ); - m_pMesh = NULL; - m_pMaterials = NULL; - m_pTextures = NULL; - m_bUseMaterials = TRUE; - m_pVB = NULL; - m_pIB = NULL; - m_pDecl = NULL; - m_strMaterials = NULL; - m_dwNumMaterials = 0; - m_dwNumVertices = 0; - m_dwNumFaces = 0; - m_dwBytesPerVertex = 0; -} - - - - -//----------------------------------------------------------------------------- -CDXUTXFileMesh::~CDXUTXFileMesh() -{ - Destroy(); -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, LPCWSTR strFilename ) -{ - WCHAR strPath[MAX_PATH]; - LPD3DXBUFFER pAdjacencyBuffer = NULL; - LPD3DXBUFFER pMtrlBuffer = NULL; - HRESULT hr; - - // Cleanup previous mesh if any - Destroy(); - - // Find the path for the file, and convert it to ANSI (for the D3DX API) - DXUTFindDXSDKMediaFileCch( strPath, sizeof( strPath ) / sizeof( WCHAR ), strFilename ); - - // Load the mesh - if( FAILED( hr = D3DXLoadMeshFromX( strPath, D3DXMESH_MANAGED, pd3dDevice, - &pAdjacencyBuffer, &pMtrlBuffer, NULL, - &m_dwNumMaterials, &m_pMesh ) ) ) - { - return hr; - } - - // Optimize the mesh for performance - if( FAILED( hr = m_pMesh->OptimizeInplace( - D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, - ( DWORD* )pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) ) - { - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - return hr; - } - - // Set strPath to the path of the mesh file - WCHAR* pLastBSlash = wcsrchr( strPath, L'\\' ); - if( pLastBSlash ) - *( pLastBSlash + 1 ) = L'\0'; - else - *strPath = L'\0'; - - D3DXMATERIAL* d3dxMtrls = ( D3DXMATERIAL* )pMtrlBuffer->GetBufferPointer(); - hr = CreateMaterials( strPath, pd3dDevice, d3dxMtrls, m_dwNumMaterials ); - - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - - // Extract data from m_pMesh for easy access - D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE]; - m_dwNumVertices = m_pMesh->GetNumVertices(); - m_dwNumFaces = m_pMesh->GetNumFaces(); - m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex(); - m_pMesh->GetIndexBuffer( &m_pIB ); - m_pMesh->GetVertexBuffer( &m_pVB ); - m_pMesh->GetDeclaration( decl ); - pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl ); - - return hr; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXFILEDATA pFileData ) -{ - LPD3DXBUFFER pMtrlBuffer = NULL; - LPD3DXBUFFER pAdjacencyBuffer = NULL; - HRESULT hr; - - // Cleanup previous mesh if any - Destroy(); - - // Load the mesh from the DXFILEDATA object - if( FAILED( hr = D3DXLoadMeshFromXof( pFileData, D3DXMESH_MANAGED, pd3dDevice, - &pAdjacencyBuffer, &pMtrlBuffer, NULL, - &m_dwNumMaterials, &m_pMesh ) ) ) - { - return hr; - } - - // Optimize the mesh for performance - if( FAILED( hr = m_pMesh->OptimizeInplace( - D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, - ( DWORD* )pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) ) - { - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - return hr; - } - - D3DXMATERIAL* d3dxMtrls = ( D3DXMATERIAL* )pMtrlBuffer->GetBufferPointer(); - hr = CreateMaterials( L"", pd3dDevice, d3dxMtrls, m_dwNumMaterials ); - - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - - // Extract data from m_pMesh for easy access - D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE]; - m_dwNumVertices = m_pMesh->GetNumVertices(); - m_dwNumFaces = m_pMesh->GetNumFaces(); - m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex(); - m_pMesh->GetIndexBuffer( &m_pIB ); - m_pMesh->GetVertexBuffer( &m_pVB ); - m_pMesh->GetDeclaration( decl ); - pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl ); - - return hr; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh* pInMesh, - D3DXMATERIAL* pd3dxMaterials, DWORD dwMaterials ) -{ - // Cleanup previous mesh if any - Destroy(); - - // Optimize the mesh for performance - DWORD* rgdwAdjacency = NULL; - rgdwAdjacency = new DWORD[pInMesh->GetNumFaces() * 3]; - if( rgdwAdjacency == NULL ) - return E_OUTOFMEMORY; - pInMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ); - - D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE]; - pInMesh->GetDeclaration( decl ); - - DWORD dwOptions = pInMesh->GetOptions(); - dwOptions &= ~( D3DXMESH_32BIT | D3DXMESH_SYSTEMMEM | D3DXMESH_WRITEONLY ); - dwOptions |= D3DXMESH_MANAGED; - dwOptions |= D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE; - - ID3DXMesh* pTempMesh = NULL; - if( FAILED( pInMesh->Optimize( dwOptions, rgdwAdjacency, NULL, NULL, NULL, &pTempMesh ) ) ) - { - SAFE_DELETE_ARRAY( rgdwAdjacency ); - return E_FAIL; - } - - SAFE_DELETE_ARRAY( rgdwAdjacency ); - SAFE_RELEASE( m_pMesh ); - m_pMesh = pTempMesh; - - HRESULT hr; - hr = CreateMaterials( L"", pd3dDevice, pd3dxMaterials, dwMaterials ); - - // Extract data from m_pMesh for easy access - m_dwNumVertices = m_pMesh->GetNumVertices(); - m_dwNumFaces = m_pMesh->GetNumFaces(); - m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex(); - m_pMesh->GetIndexBuffer( &m_pIB ); - m_pMesh->GetVertexBuffer( &m_pVB ); - m_pMesh->GetDeclaration( decl ); - pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl ); - - return hr; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::CreateMaterials( LPCWSTR strPath, IDirect3DDevice9* pd3dDevice, D3DXMATERIAL* d3dxMtrls, - DWORD dwNumMaterials ) -{ - // Get material info for the mesh - // Get the array of materials out of the buffer - m_dwNumMaterials = dwNumMaterials; - if( d3dxMtrls && m_dwNumMaterials > 0 ) - { - // Allocate memory for the materials and textures - m_pMaterials = new D3DMATERIAL9[m_dwNumMaterials]; - if( m_pMaterials == NULL ) - return E_OUTOFMEMORY; - m_pTextures = new LPDIRECT3DBASETEXTURE9[m_dwNumMaterials]; - if( m_pTextures == NULL ) - return E_OUTOFMEMORY; - m_strMaterials = new CHAR[m_dwNumMaterials][MAX_PATH]; - if( m_strMaterials == NULL ) - return E_OUTOFMEMORY; - - // Copy each material and create its texture - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - // Copy the material - m_pMaterials[i] = d3dxMtrls[i].MatD3D; - m_pTextures[i] = NULL; - - // Create a texture - if( d3dxMtrls[i].pTextureFilename ) - { - strcpy_s( m_strMaterials[i], MAX_PATH, d3dxMtrls[i].pTextureFilename ); - - WCHAR strTexture[MAX_PATH]; - WCHAR strTextureTemp[MAX_PATH]; - D3DXIMAGE_INFO ImgInfo; - - // First attempt to look for texture in the same folder as the input folder. - MultiByteToWideChar( CP_ACP, 0, d3dxMtrls[i].pTextureFilename, -1, strTextureTemp, MAX_PATH ); - strTextureTemp[MAX_PATH - 1] = 0; - - wcscpy_s( strTexture, MAX_PATH, strPath ); - wcscat_s( strTexture, MAX_PATH, strTextureTemp ); - - // Inspect the texture file to determine the texture type. - if( FAILED( D3DXGetImageInfoFromFile( strTexture, &ImgInfo ) ) ) - { - // Search the media folder - if( FAILED( DXUTFindDXSDKMediaFileCch( strTexture, MAX_PATH, strTextureTemp ) ) ) - continue; // Can't find. Skip. - - D3DXGetImageInfoFromFile( strTexture, &ImgInfo ); - } - - // Call the appropriate loader according to the texture type. - switch( ImgInfo.ResourceType ) - { - case D3DRTYPE_TEXTURE: - { - IDirect3DTexture9* pTex; - if( SUCCEEDED( D3DXCreateTextureFromFile( pd3dDevice, strTexture, &pTex ) ) ) - { - // Obtain the base texture interface - pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] ); - // Release the specialized instance - pTex->Release(); - } - break; - } - case D3DRTYPE_CUBETEXTURE: - { - IDirect3DCubeTexture9* pTex; - if( SUCCEEDED( D3DXCreateCubeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) ) - { - // Obtain the base texture interface - pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] ); - // Release the specialized instance - pTex->Release(); - } - break; - } - case D3DRTYPE_VOLUMETEXTURE: - { - IDirect3DVolumeTexture9* pTex; - if( SUCCEEDED( D3DXCreateVolumeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) ) - { - // Obtain the base texture interface - pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] ); - // Release the specialized instance - pTex->Release(); - } - break; - } - } - } - } - } - return S_OK; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::SetFVF( LPDIRECT3DDEVICE9 pd3dDevice, DWORD dwFVF ) -{ - LPD3DXMESH pTempMesh = NULL; - - if( m_pMesh ) - { - if( FAILED( m_pMesh->CloneMeshFVF( m_pMesh->GetOptions(), dwFVF, - pd3dDevice, &pTempMesh ) ) ) - { - SAFE_RELEASE( pTempMesh ); - return E_FAIL; - } - - DWORD dwOldFVF = 0; - dwOldFVF = m_pMesh->GetFVF(); - SAFE_RELEASE( m_pMesh ); - m_pMesh = pTempMesh; - - // Compute normals if they are being requested and - // the old mesh does not have them. - if( !( dwOldFVF & D3DFVF_NORMAL ) && dwFVF & D3DFVF_NORMAL ) - { - D3DXComputeNormals( m_pMesh, NULL ); - } - } - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -// Convert the mesh to the format specified by the given vertex declarations. -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::SetVertexDecl( LPDIRECT3DDEVICE9 pd3dDevice, const D3DVERTEXELEMENT9* pDecl, - bool bAutoComputeNormals, bool bAutoComputeTangents, - bool bSplitVertexForOptimalTangents ) -{ - LPD3DXMESH pTempMesh = NULL; - - if( m_pMesh ) - { - if( FAILED( m_pMesh->CloneMesh( m_pMesh->GetOptions(), pDecl, - pd3dDevice, &pTempMesh ) ) ) - { - SAFE_RELEASE( pTempMesh ); - return E_FAIL; - } - } - - - // Check if the old declaration contains a normal. - bool bHadNormal = false; - bool bHadTangent = false; - D3DVERTEXELEMENT9 aOldDecl[MAX_FVF_DECL_SIZE]; - if( m_pMesh && SUCCEEDED( m_pMesh->GetDeclaration( aOldDecl ) ) ) - { - for( UINT index = 0; index < D3DXGetDeclLength( aOldDecl ); ++index ) - { - if( aOldDecl[index].Usage == D3DDECLUSAGE_NORMAL ) - { - bHadNormal = true; - } - if( aOldDecl[index].Usage == D3DDECLUSAGE_TANGENT ) - { - bHadTangent = true; - } - } - } - - // Check if the new declaration contains a normal. - bool bHaveNormalNow = false; - bool bHaveTangentNow = false; - D3DVERTEXELEMENT9 aNewDecl[MAX_FVF_DECL_SIZE]; - if( pTempMesh && SUCCEEDED( pTempMesh->GetDeclaration( aNewDecl ) ) ) - { - for( UINT index = 0; index < D3DXGetDeclLength( aNewDecl ); ++index ) - { - if( aNewDecl[index].Usage == D3DDECLUSAGE_NORMAL ) - { - bHaveNormalNow = true; - } - if( aNewDecl[index].Usage == D3DDECLUSAGE_TANGENT ) - { - bHaveTangentNow = true; - } - } - } - - SAFE_RELEASE( m_pMesh ); - - if( pTempMesh ) - { - m_pMesh = pTempMesh; - - if( !bHadNormal && bHaveNormalNow && bAutoComputeNormals ) - { - // Compute normals in case the meshes have them - D3DXComputeNormals( m_pMesh, NULL ); - } - - if( bHaveNormalNow && !bHadTangent && bHaveTangentNow && bAutoComputeTangents ) - { - ID3DXMesh* pNewMesh; - HRESULT hr; - - DWORD* rgdwAdjacency = NULL; - rgdwAdjacency = new DWORD[m_pMesh->GetNumFaces() * 3]; - if( rgdwAdjacency == NULL ) - return E_OUTOFMEMORY; - V( m_pMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ) ); - - float fPartialEdgeThreshold; - float fSingularPointThreshold; - float fNormalEdgeThreshold; - if( bSplitVertexForOptimalTangents ) - { - fPartialEdgeThreshold = 0.01f; - fSingularPointThreshold = 0.25f; - fNormalEdgeThreshold = 0.01f; - } - else - { - fPartialEdgeThreshold = -1.01f; - fSingularPointThreshold = 0.01f; - fNormalEdgeThreshold = -1.01f; - } - - // Compute tangents, which are required for normal mapping - hr = D3DXComputeTangentFrameEx( m_pMesh, - D3DDECLUSAGE_TEXCOORD, 0, - D3DDECLUSAGE_TANGENT, 0, - D3DX_DEFAULT, 0, - D3DDECLUSAGE_NORMAL, 0, - 0, rgdwAdjacency, - fPartialEdgeThreshold, fSingularPointThreshold, fNormalEdgeThreshold, - &pNewMesh, NULL ); - - SAFE_DELETE_ARRAY( rgdwAdjacency ); - if( FAILED( hr ) ) - return hr; - - SAFE_RELEASE( m_pMesh ); - m_pMesh = pNewMesh; - } - } - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::RestoreDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice ) -{ - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::InvalidateDeviceObjects() -{ - SAFE_RELEASE( m_pIB ); - SAFE_RELEASE( m_pVB ); - SAFE_RELEASE( m_pDecl ); - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Destroy() -{ - InvalidateDeviceObjects(); - for( UINT i = 0; i < m_dwNumMaterials; i++ ) - SAFE_RELEASE( m_pTextures[i] ); - SAFE_DELETE_ARRAY( m_pTextures ); - SAFE_DELETE_ARRAY( m_pMaterials ); - SAFE_DELETE_ARRAY( m_strMaterials ); - - SAFE_RELEASE( m_pMesh ); - - m_dwNumMaterials = 0L; - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice, bool bDrawOpaqueSubsets, - bool bDrawAlphaSubsets ) -{ - if( NULL == m_pMesh ) - return E_FAIL; - - // Frist, draw the subsets without alpha - if( bDrawOpaqueSubsets ) - { - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_bUseMaterials ) - { - if( m_pMaterials[i].Diffuse.a < 1.0f ) - continue; - pd3dDevice->SetMaterial( &m_pMaterials[i] ); - pd3dDevice->SetTexture( 0, m_pTextures[i] ); - } - m_pMesh->DrawSubset( i ); - } - } - - // Then, draw the subsets with alpha - if( bDrawAlphaSubsets && m_bUseMaterials ) - { - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_pMaterials[i].Diffuse.a == 1.0f ) - continue; - - // Set the material and texture - pd3dDevice->SetMaterial( &m_pMaterials[i] ); - pd3dDevice->SetTexture( 0, m_pTextures[i] ); - m_pMesh->DrawSubset( i ); - } - } - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Render( ID3DXEffect* pEffect, - D3DXHANDLE hTexture, - D3DXHANDLE hDiffuse, - D3DXHANDLE hAmbient, - D3DXHANDLE hSpecular, - D3DXHANDLE hEmissive, - D3DXHANDLE hPower, - bool bDrawOpaqueSubsets, - bool bDrawAlphaSubsets ) -{ - if( NULL == m_pMesh ) - return E_FAIL; - - UINT cPasses; - // Frist, draw the subsets without alpha - if( bDrawOpaqueSubsets ) - { - pEffect->Begin( &cPasses, 0 ); - for( UINT p = 0; p < cPasses; ++p ) - { - pEffect->BeginPass( p ); - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_bUseMaterials ) - { - if( m_pMaterials[i].Diffuse.a < 1.0f ) - continue; - if( hTexture ) - pEffect->SetTexture( hTexture, m_pTextures[i] ); - // D3DCOLORVALUE and D3DXVECTOR4 are data-wise identical. - // No conversion is needed. - if( hDiffuse ) - pEffect->SetVector( hDiffuse, ( D3DXVECTOR4* )&m_pMaterials[i].Diffuse ); - if( hAmbient ) - pEffect->SetVector( hAmbient, ( D3DXVECTOR4* )&m_pMaterials[i].Ambient ); - if( hSpecular ) - pEffect->SetVector( hSpecular, ( D3DXVECTOR4* )&m_pMaterials[i].Specular ); - if( hEmissive ) - pEffect->SetVector( hEmissive, ( D3DXVECTOR4* )&m_pMaterials[i].Emissive ); - if( hPower ) - pEffect->SetFloat( hPower, m_pMaterials[i].Power ); - pEffect->CommitChanges(); - } - m_pMesh->DrawSubset( i ); - } - pEffect->EndPass(); - } - pEffect->End(); - } - - // Then, draw the subsets with alpha - if( bDrawAlphaSubsets && m_bUseMaterials ) - { - pEffect->Begin( &cPasses, 0 ); - for( UINT p = 0; p < cPasses; ++p ) - { - pEffect->BeginPass( p ); - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_bUseMaterials ) - { - if( m_pMaterials[i].Diffuse.a == 1.0f ) - continue; - if( hTexture ) - pEffect->SetTexture( hTexture, m_pTextures[i] ); - // D3DCOLORVALUE and D3DXVECTOR4 are data-wise identical. - // No conversion is needed. - if( hDiffuse ) - pEffect->SetVector( hDiffuse, ( D3DXVECTOR4* )&m_pMaterials[i].Diffuse ); - if( hAmbient ) - pEffect->SetVector( hAmbient, ( D3DXVECTOR4* )&m_pMaterials[i].Ambient ); - if( hSpecular ) - pEffect->SetVector( hSpecular, ( D3DXVECTOR4* )&m_pMaterials[i].Specular ); - if( hEmissive ) - pEffect->SetVector( hEmissive, ( D3DXVECTOR4* )&m_pMaterials[i].Emissive ); - if( hPower ) - pEffect->SetFloat( hPower, m_pMaterials[i].Power ); - pEffect->CommitChanges(); - } - m_pMesh->DrawSubset( i ); - } - pEffect->EndPass(); - } - pEffect->End(); - } - - return S_OK; -} diff --git a/FriedLiver/Source/DXUT/Optional/SDKmesh.h b/FriedLiver/Source/DXUT/Optional/SDKmesh.h index 79a41d0a..bed6cad2 100644 --- a/FriedLiver/Source/DXUT/Optional/SDKmesh.h +++ b/FriedLiver/Source/DXUT/Optional/SDKmesh.h @@ -8,10 +8,14 @@ // meets the specific needs of the application. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef _SDKMESH_ -#define _SDKMESH_ + +#undef D3DCOLOR_ARGB +#include //-------------------------------------------------------------------------------------- // Hard Defines for the various structures @@ -40,7 +44,7 @@ template BOOL IsErrorResource( TYPE data ) return FALSE; } //-------------------------------------------------------------------------------------- -// Enumerated Types. These will have mirrors in both D3D9 and D3D11 +// Enumerated Types. //-------------------------------------------------------------------------------------- enum SDKMESH_PRIMITIVE_TYPE { @@ -72,6 +76,8 @@ enum FRAME_TRANSFORM_TYPE //-------------------------------------------------------------------------------------- // Structures. Unions with pointers are forced to 64bit. //-------------------------------------------------------------------------------------- +#pragma pack(push,8) + struct SDKMESH_HEADER { //Basic Info and sizes @@ -107,7 +113,6 @@ struct SDKMESH_VERTEX_BUFFER_HEADER union { UINT64 DataOffset; //(This also forces the union to 64bits) - IDirect3DVertexBuffer9* pVB9; ID3D11Buffer* pVB11; }; }; @@ -120,7 +125,6 @@ struct SDKMESH_INDEX_BUFFER_HEADER union { UINT64 DataOffset; //(This also forces the union to 64bits) - IDirect3DIndexBuffer9* pIB9; ID3D11Buffer* pIB11; }; }; @@ -134,8 +138,8 @@ struct SDKMESH_MESH UINT NumSubsets; UINT NumFrameInfluences; //aka bones - D3DXVECTOR3 BoundingBoxCenter; - D3DXVECTOR3 BoundingBoxExtents; + DirectX::XMFLOAT3 BoundingBoxCenter; + DirectX::XMFLOAT3 BoundingBoxExtents; union { @@ -167,7 +171,7 @@ struct SDKMESH_FRAME UINT ParentFrame; UINT ChildFrame; UINT SiblingFrame; - D3DXMATRIX Matrix; + DirectX::XMFLOAT4X4 Matrix; UINT AnimationDataIndex; //Used to index which set of keyframes transforms this frame }; @@ -183,28 +187,25 @@ struct SDKMESH_MATERIAL char NormalTexture[MAX_TEXTURE_NAME]; char SpecularTexture[MAX_TEXTURE_NAME]; - D3DXVECTOR4 Diffuse; - D3DXVECTOR4 Ambient; - D3DXVECTOR4 Specular; - D3DXVECTOR4 Emissive; - FLOAT Power; + DirectX::XMFLOAT4 Diffuse; + DirectX::XMFLOAT4 Ambient; + DirectX::XMFLOAT4 Specular; + DirectX::XMFLOAT4 Emissive; + float Power; union { UINT64 Force64_1; //Force the union to 64bits - IDirect3DTexture9* pDiffuseTexture9; ID3D11Texture2D* pDiffuseTexture11; }; union { UINT64 Force64_2; //Force the union to 64bits - IDirect3DTexture9* pNormalTexture9; ID3D11Texture2D* pNormalTexture11; }; union { UINT64 Force64_3; //Force the union to 64bits - IDirect3DTexture9* pSpecularTexture9; ID3D11Texture2D* pSpecularTexture11; }; @@ -240,9 +241,9 @@ struct SDKANIMATION_FILE_HEADER struct SDKANIMATION_DATA { - D3DXVECTOR3 Translation; - D3DXVECTOR4 Orientation; - D3DXVECTOR3 Scaling; + DirectX::XMFLOAT3 Translation; + DirectX::XMFLOAT4 Orientation; + DirectX::XMFLOAT3 Scaling; }; struct SDKANIMATION_FRAME_DATA @@ -255,34 +256,31 @@ struct SDKANIMATION_FRAME_DATA }; }; +#pragma pack(pop) + +static_assert( sizeof(D3DVERTEXELEMENT9) == 8, "Direct3D9 Decl structure size incorrect" ); +static_assert( sizeof(SDKMESH_HEADER)== 104, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_VERTEX_BUFFER_HEADER) == 288, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_INDEX_BUFFER_HEADER) == 32, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_MESH) == 224, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_SUBSET) == 144, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_FRAME) == 184, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_MATERIAL) == 1256, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKANIMATION_FILE_HEADER) == 40, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKANIMATION_DATA) == 40, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKANIMATION_FRAME_DATA) == 112, "SDK Mesh structure size incorrect" ); + #ifndef _CONVERTER_APP_ //-------------------------------------------------------------------------------------- // AsyncLoading callbacks //-------------------------------------------------------------------------------------- -typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE9 )( IDirect3DDevice9* pDev, char* szFileName, - IDirect3DTexture9** ppTexture, void* pContext ); -typedef void ( CALLBACK*LPCREATEVERTEXBUFFER9 )( IDirect3DDevice9* pDev, IDirect3DVertexBuffer9** ppBuffer, - UINT iSizeBytes, DWORD Usage, DWORD FVF, D3DPOOL Pool, void* pData, - void* pContext ); -typedef void ( CALLBACK*LPCREATEINDEXBUFFER9 )( IDirect3DDevice9* pDev, IDirect3DIndexBuffer9** ppBuffer, - UINT iSizeBytes, DWORD Usage, D3DFORMAT ibFormat, D3DPOOL Pool, - void* pData, void* pContext ); -struct SDKMESH_CALLBACKS9 -{ - LPCREATETEXTUREFROMFILE9 pCreateTextureFromFile; - LPCREATEVERTEXBUFFER9 pCreateVertexBuffer; - LPCREATEINDEXBUFFER9 pCreateIndexBuffer; - void* pContext; -}; - - -typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE11 )( ID3D11Device* pDev, char* szFileName, - ID3D11ShaderResourceView** ppRV, void* pContext ); -typedef void ( CALLBACK*LPCREATEVERTEXBUFFER11 )( ID3D11Device* pDev, ID3D11Buffer** ppBuffer, - D3D11_BUFFER_DESC BufferDesc, void* pData, void* pContext ); -typedef void ( CALLBACK*LPCREATEINDEXBUFFER11 )( ID3D11Device* pDev, ID3D11Buffer** ppBuffer, - D3D11_BUFFER_DESC BufferDesc, void* pData, void* pContext ); +typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE11 )( _In_ ID3D11Device* pDev, _In_z_ char* szFileName, + _Outptr_ ID3D11ShaderResourceView** ppRV, _In_opt_ void* pContext ); +typedef void ( CALLBACK*LPCREATEVERTEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer, + _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext ); +typedef void ( CALLBACK*LPCREATEINDEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer, + _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext ); struct SDKMESH_CALLBACKS11 { LPCREATETEXTUREFROMFILE11 pCreateTextureFromFile; @@ -302,8 +300,7 @@ class CDXUTSDKMesh //BYTE* m_pBufferData; HANDLE m_hFile; HANDLE m_hFileMappingObject; - CGrowableArray m_MappedPointers; - IDirect3DDevice9* m_pDev9; + std::vector m_MappedPointers; ID3D11Device* m_pDev11; ID3D11DeviceContext* m_pDevContext11; @@ -331,259 +328,129 @@ class CDXUTSDKMesh // Adjacency information (not part of the m_pStaticMeshData, so it must be created and destroyed separately ) SDKMESH_INDEX_BUFFER_HEADER* m_pAdjacencyIndexBufferArray; - //Animation (TODO: Add ability to load/track multiple animation sets) + //Animation SDKANIMATION_FILE_HEADER* m_pAnimationHeader; SDKANIMATION_FRAME_DATA* m_pAnimationFrameData; - D3DXMATRIX* m_pBindPoseFrameMatrices; - D3DXMATRIX* m_pTransformedFrameMatrices; - D3DXMATRIX* m_pWorldPoseFrameMatrices; + DirectX::XMFLOAT4X4* m_pBindPoseFrameMatrices; + DirectX::XMFLOAT4X4* m_pTransformedFrameMatrices; + DirectX::XMFLOAT4X4* m_pWorldPoseFrameMatrices; protected: - void LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pMaterials, - UINT NumMaterials, SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - - void LoadMaterials( IDirect3DDevice9* pd3dDevice, SDKMESH_MATERIAL* pMaterials, - UINT NumMaterials, SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - - HRESULT CreateVertexBuffer( ID3D11Device* pd3dDevice, - SDKMESH_VERTEX_BUFFER_HEADER* pHeader, void* pVertices, - SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - HRESULT CreateVertexBuffer( IDirect3DDevice9* pd3dDevice, - SDKMESH_VERTEX_BUFFER_HEADER* pHeader, void* pVertices, - SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - - HRESULT CreateIndexBuffer( ID3D11Device* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader, - void* pIndices, SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - HRESULT CreateIndexBuffer( IDirect3DDevice9* pd3dDevice, - SDKMESH_INDEX_BUFFER_HEADER* pHeader, void* pIndices, - SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - - virtual HRESULT CreateFromFile( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, - LPCTSTR szFileName, - bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS11* pLoaderCallbacks11 = NULL, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 = NULL ); - - virtual HRESULT CreateFromMemory( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, - BYTE* pData, - UINT DataBytes, - bool bCreateAdjacencyIndices, - bool bCopyStatic, - SDKMESH_CALLBACKS11* pLoaderCallbacks11 = NULL, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 = NULL ); + void LoadMaterials( _In_ ID3D11Device* pd3dDevice, _In_reads_(NumMaterials) SDKMESH_MATERIAL* pMaterials, + _In_ UINT NumMaterials, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + + HRESULT CreateVertexBuffer( _In_ ID3D11Device* pd3dDevice, + _In_ SDKMESH_VERTEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pVertices, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + + HRESULT CreateIndexBuffer( _In_ ID3D11Device* pd3dDevice, + _In_ SDKMESH_INDEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pIndices, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + + virtual HRESULT CreateFromFile( _In_opt_ ID3D11Device* pDev11, + _In_z_ LPCWSTR szFileName, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr ); + + virtual HRESULT CreateFromMemory( _In_opt_ ID3D11Device* pDev11, + _In_reads_(DataBytes) BYTE* pData, + _In_ size_t DataBytes, + _In_ bool bCopyStatic, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr ); //frame manipulation - void TransformBindPoseFrame( UINT iFrame, D3DXMATRIX* pParentWorld ); - void TransformFrame( UINT iFrame, D3DXMATRIX* pParentWorld, double fTime ); - void TransformFrameAbsolute( UINT iFrame, double fTime ); + void TransformBindPoseFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld ); + void TransformFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld, _In_ double fTime ); + void TransformFrameAbsolute( _In_ UINT iFrame, _In_ double fTime ); //Direct3D 11 rendering helpers - void RenderMesh( UINT iMesh, - bool bAdjacent, - ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot, - UINT iNormalSlot, - UINT iSpecularSlot ); - void RenderFrame( UINT iFrame, - bool bAdjacent, - ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot, - UINT iNormalSlot, - UINT iSpecularSlot ); - - - //Direct3D 9 rendering helpers - void RenderMesh( UINT iMesh, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ); - void RenderFrame( UINT iFrame, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ); + void RenderMesh( _In_ UINT iMesh, + _In_ bool bAdjacent, + _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot, + _In_ UINT iNormalSlot, + _In_ UINT iSpecularSlot ); + void RenderFrame( _In_ UINT iFrame, + _In_ bool bAdjacent, + _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot, + _In_ UINT iNormalSlot, + _In_ UINT iSpecularSlot ); public: - CDXUTSDKMesh(); - virtual ~CDXUTSDKMesh(); - - virtual HRESULT Create( ID3D11Device* pDev11, LPCTSTR szFileName, bool bCreateAdjacencyIndices= - false, SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - virtual HRESULT Create( IDirect3DDevice9* pDev9, LPCTSTR szFileName, bool bCreateAdjacencyIndices= - false, SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - virtual HRESULT Create( ID3D11Device* pDev11, BYTE* pData, UINT DataBytes, - bool bCreateAdjacencyIndices=false, bool bCopyStatic=false, - SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - virtual HRESULT Create( IDirect3DDevice9* pDev9, BYTE* pData, UINT DataBytes, - bool bCreateAdjacencyIndices=false, bool bCopyStatic=false, - SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - virtual HRESULT LoadAnimation( WCHAR* szFileName ); - virtual void Destroy(); + CDXUTSDKMesh() noexcept; + virtual ~CDXUTSDKMesh(); - //Frame manipulation - void TransformBindPose( D3DXMATRIX* pWorld ); - void TransformMesh( D3DXMATRIX* pWorld, double fTime ); + virtual HRESULT Create( _In_ ID3D11Device* pDev11, _In_z_ LPCWSTR szFileName, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + virtual HRESULT Create( _In_ ID3D11Device* pDev11, BYTE* pData, size_t DataBytes, _In_ bool bCopyStatic=false, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + virtual HRESULT LoadAnimation( _In_z_ const WCHAR* szFileName ); + virtual void Destroy(); + //Frame manipulation + void TransformBindPose( _In_ DirectX::CXMMATRIX world ) { TransformBindPoseFrame( 0, world ); }; + void TransformMesh( _In_ DirectX::CXMMATRIX world, _In_ double fTime ); //Direct3D 11 Rendering - virtual void Render( ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, - UINT iNormalSlot = INVALID_SAMPLER_SLOT, - UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); - virtual void RenderAdjacent( ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, - UINT iNormalSlot = INVALID_SAMPLER_SLOT, - UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); - - //Direct3D 9 Rendering - virtual void Render( LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse = 0, - D3DXHANDLE htxNormal = 0, - D3DXHANDLE htxSpecular = 0 ); + virtual void Render( _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); + virtual void RenderAdjacent( _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); //Helpers (D3D11 specific) - static D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveType11( SDKMESH_PRIMITIVE_TYPE PrimType ); - DXGI_FORMAT GetIBFormat11( UINT iMesh ); - ID3D11Buffer* GetVB11( UINT iMesh, UINT iVB ); - ID3D11Buffer* GetIB11( UINT iMesh ); - SDKMESH_INDEX_TYPE GetIndexType( UINT iMesh ); + static D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveType11( _In_ SDKMESH_PRIMITIVE_TYPE PrimType ); + DXGI_FORMAT GetIBFormat11( _In_ UINT iMesh ) const; + ID3D11Buffer* GetVB11( _In_ UINT iMesh, _In_ UINT iVB ) const; + ID3D11Buffer* GetIB11( _In_ UINT iMesh ) const; + SDKMESH_INDEX_TYPE GetIndexType( _In_ UINT iMesh ) const; - ID3D11Buffer* GetAdjIB11( UINT iMesh ); - - //Helpers (D3D9 specific) - static D3DPRIMITIVETYPE GetPrimitiveType9( SDKMESH_PRIMITIVE_TYPE PrimType ); - D3DFORMAT GetIBFormat9( UINT iMesh ); - IDirect3DVertexBuffer9* GetVB9( UINT iMesh, UINT iVB ); - IDirect3DIndexBuffer9* GetIB9( UINT iMesh ); + ID3D11Buffer* GetAdjIB11( _In_ UINT iMesh ) const; //Helpers (general) - char* GetMeshPathA(); - WCHAR* GetMeshPathW(); - UINT GetNumMeshes(); - UINT GetNumMaterials(); - UINT GetNumVBs(); - UINT GetNumIBs(); - - ID3D11Buffer* GetVB11At( UINT iVB ); - ID3D11Buffer* GetIB11At( UINT iIB ); - - IDirect3DVertexBuffer9* GetVB9At( UINT iVB ); - IDirect3DIndexBuffer9* GetIB9At( UINT iIB ); - - BYTE* GetRawVerticesAt( UINT iVB ); - BYTE* GetRawIndicesAt( UINT iIB ); - SDKMESH_MATERIAL* GetMaterial( UINT iMaterial ); - SDKMESH_MESH* GetMesh( UINT iMesh ); - UINT GetNumSubsets( UINT iMesh ); - SDKMESH_SUBSET* GetSubset( UINT iMesh, UINT iSubset ); - UINT GetVertexStride( UINT iMesh, UINT iVB ); - UINT GetNumFrames(); - SDKMESH_FRAME* GetFrame( UINT iFrame ); - SDKMESH_FRAME* FindFrame( char* pszName ); - UINT64 GetNumVertices( UINT iMesh, UINT iVB ); - UINT64 GetNumIndices( UINT iMesh ); - D3DXVECTOR3 GetMeshBBoxCenter( UINT iMesh ); - D3DXVECTOR3 GetMeshBBoxExtents( UINT iMesh ); - UINT GetOutstandingResources(); - UINT GetOutstandingBufferResources(); - bool CheckLoadDone(); - bool IsLoaded(); - bool IsLoading(); - void SetLoading( bool bLoading ); - BOOL HadLoadingError(); + const char* GetMeshPathA() const; + const WCHAR* GetMeshPathW() const; + UINT GetNumMeshes() const; + UINT GetNumMaterials() const; + UINT GetNumVBs() const; + UINT GetNumIBs() const; + + ID3D11Buffer* GetVB11At( _In_ UINT iVB ) const; + ID3D11Buffer* GetIB11At( _In_ UINT iIB ) const; + + BYTE* GetRawVerticesAt( _In_ UINT iVB ) const; + BYTE* GetRawIndicesAt( _In_ UINT iIB ) const; + + SDKMESH_MATERIAL* GetMaterial( _In_ UINT iMaterial ) const; + SDKMESH_MESH* GetMesh( _In_ UINT iMesh ) const; + UINT GetNumSubsets( _In_ UINT iMesh ) const; + SDKMESH_SUBSET* GetSubset( _In_ UINT iMesh, _In_ UINT iSubset ) const; + UINT GetVertexStride( _In_ UINT iMesh, _In_ UINT iVB ) const; + UINT GetNumFrames() const; + SDKMESH_FRAME* GetFrame( _In_ UINT iFrame ) const; + SDKMESH_FRAME* FindFrame( _In_z_ const char* pszName ) const; + UINT64 GetNumVertices( _In_ UINT iMesh, _In_ UINT iVB ) const; + UINT64 GetNumIndices( _In_ UINT iMesh ) const; + DirectX::XMVECTOR GetMeshBBoxCenter( _In_ UINT iMesh ) const; + DirectX::XMVECTOR GetMeshBBoxExtents( _In_ UINT iMesh ) const; + UINT GetOutstandingResources() const; + UINT GetOutstandingBufferResources() const; + bool CheckLoadDone(); + bool IsLoaded() const; + bool IsLoading() const; + void SetLoading( _In_ bool bLoading ); + BOOL HadLoadingError() const; //Animation - UINT GetNumInfluences( UINT iMesh ); - const D3DXMATRIX* GetMeshInfluenceMatrix( UINT iMesh, UINT iInfluence ); - UINT GetAnimationKeyFromTime( double fTime ); - const D3DXMATRIX* GetWorldMatrix( UINT iFrameIndex ); - const D3DXMATRIX* GetInfluenceMatrix( UINT iFrameIndex ); - bool GetAnimationProperties( UINT* pNumKeys, FLOAT* pFrameTime ); + UINT GetNumInfluences( _In_ UINT iMesh ) const; + DirectX::XMMATRIX GetMeshInfluenceMatrix( _In_ UINT iMesh, _In_ UINT iInfluence ) const; + UINT GetAnimationKeyFromTime( _In_ double fTime ) const; + DirectX::XMMATRIX GetWorldMatrix( _In_ UINT iFrameIndex ) const; + DirectX::XMMATRIX GetInfluenceMatrix( _In_ UINT iFrameIndex ) const; + bool GetAnimationProperties( _Out_ UINT* pNumKeys, _Out_ float* pFrameTime ) const; }; -//----------------------------------------------------------------------------- -// Name: class CDXUTXFileMesh -// Desc: Class for loading and rendering file-based meshes -//----------------------------------------------------------------------------- -class CDXUTXFileMesh -{ -public: - WCHAR m_strName[512]; - LPD3DXMESH m_pMesh; // Managed mesh - - // Cache of data in m_pMesh for easy access - IDirect3DVertexBuffer9* m_pVB; - IDirect3DIndexBuffer9* m_pIB; - IDirect3DVertexDeclaration9* m_pDecl; - DWORD m_dwNumVertices; - DWORD m_dwNumFaces; - DWORD m_dwBytesPerVertex; - - DWORD m_dwNumMaterials; // Materials for the mesh - D3DMATERIAL9* m_pMaterials; - CHAR (*m_strMaterials )[MAX_PATH]; - IDirect3DBaseTexture9** m_pTextures; - bool m_bUseMaterials; - -public: - // Rendering - HRESULT Render( LPDIRECT3DDEVICE9 pd3dDevice, - bool bDrawOpaqueSubsets = true, - bool bDrawAlphaSubsets = true ); - HRESULT Render( ID3DXEffect* pEffect, - D3DXHANDLE hTexture = NULL, - D3DXHANDLE hDiffuse = NULL, - D3DXHANDLE hAmbient = NULL, - D3DXHANDLE hSpecular = NULL, - D3DXHANDLE hEmissive = NULL, - D3DXHANDLE hPower = NULL, - bool bDrawOpaqueSubsets = true, - bool bDrawAlphaSubsets = true ); - - // Mesh access - LPD3DXMESH GetMesh() - { - return m_pMesh; - } - - // Rendering options - void UseMeshMaterials( bool bFlag ) - { - m_bUseMaterials = bFlag; - } - HRESULT SetFVF( LPDIRECT3DDEVICE9 pd3dDevice, DWORD dwFVF ); - HRESULT SetVertexDecl( LPDIRECT3DDEVICE9 pd3dDevice, const D3DVERTEXELEMENT9* pDecl, - bool bAutoComputeNormals = true, bool bAutoComputeTangents = true, - bool bSplitVertexForOptimalTangents = false ); - - // Initializing - HRESULT RestoreDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice ); - HRESULT InvalidateDeviceObjects(); - - // Creation/destruction - HRESULT Create( LPDIRECT3DDEVICE9 pd3dDevice, LPCWSTR strFilename ); - HRESULT Create( LPDIRECT3DDEVICE9 pd3dDevice, LPD3DXFILEDATA pFileData ); - HRESULT Create( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh* pInMesh, D3DXMATERIAL* pd3dxMaterials, - DWORD dwMaterials ); - HRESULT CreateMaterials( LPCWSTR strPath, IDirect3DDevice9* pd3dDevice, D3DXMATERIAL* d3dxMtrls, - DWORD dwNumMaterials ); - HRESULT Destroy(); - - CDXUTXFileMesh( LPCWSTR strName = L"CDXUTXMeshFile_Mesh" ); - virtual ~CDXUTXFileMesh(); -}; - - -#endif - #endif diff --git a/FriedLiver/Source/DXUT/Optional/SDKmisc.cpp b/FriedLiver/Source/DXUT/Optional/SDKmisc.cpp index 9558f28a..3246eb02 100644 --- a/FriedLiver/Source/DXUT/Optional/SDKmisc.cpp +++ b/FriedLiver/Source/DXUT/Optional/SDKmisc.cpp @@ -3,61 +3,82 @@ // // Various helper functionality that is shared between SDK samples // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "dxut.h" #include "SDKmisc.h" #include "DXUTres.h" -#undef min // use __min instead -#undef max // use __max instead #include "DXUTGui.h" +#include "DDSTextureLoader.h" +#include "WICTextureLoader.h" +#include "ScreenGrab.h" + +using namespace DirectX; + //-------------------------------------------------------------------------------------- // Global/Static Members //-------------------------------------------------------------------------------------- CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache() { // Using an accessor function gives control of the construction order - static CDXUTResourceCache cache; - return cache; + static CDXUTResourceCache* s_cache = nullptr; + if ( !s_cache ) + { +#if defined(DEBUG) || defined(_DEBUG) + int flag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); + _CrtSetDbgFlag( flag & ~_CRTDBG_ALLOC_MEM_DF ); +#endif + s_cache = new CDXUTResourceCache; +#if defined(DEBUG) || defined(_DEBUG) + _CrtSetDbgFlag( flag ); +#endif + } + return *s_cache; } //-------------------------------------------------------------------------------------- // Internal functions forward declarations //-------------------------------------------------------------------------------------- -bool DXUTFindMediaSearchTypicalDirs( __out_ecount(cchSearch) WCHAR* strSearchPath, - __in int cchSearch, - __in LPCWSTR strLeaf, - __in WCHAR* strExePath, - __in WCHAR* strExeName ); -bool DXUTFindMediaSearchParentDirs( __out_ecount(cchSearch) WCHAR* strSearchPath, - __in int cchSearch, - __in WCHAR* strStartAt, - __in WCHAR* strLeafName ); -INT_PTR CALLBACK DisplaySwitchToREFWarningProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ); +bool DXUTFindMediaSearchTypicalDirs( _Out_writes_(cchSearch) WCHAR* strSearchPath, + _In_ int cchSearch, + _In_ LPCWSTR strLeaf, + _In_ const WCHAR* strExePath, + _In_ const WCHAR* strExeName ); +bool DXUTFindMediaSearchParentDirs( _Out_writes_(cchSearch) WCHAR* strSearchPath, + _In_ int cchSearch, + _In_ const WCHAR* strStartAt, + _In_ const WCHAR* strLeafName ); + +INT_PTR CALLBACK DisplaySwitchToREFWarningProc( _In_ HWND hDlg, _In_ UINT message, _In_ WPARAM wParam, _In_ LPARAM lParam ); //-------------------------------------------------------------------------------------- // Shared code for samples to ask user if they want to use a REF device or quit //-------------------------------------------------------------------------------------- -void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) +void WINAPI DXUTDisplaySwitchingToREFWarning() { if( DXUTGetShowMsgBoxOnError() ) { DWORD dwSkipWarning = 0, dwRead = 0, dwWritten = 0; - HANDLE hFile = NULL; + HANDLE hFile = nullptr; // Read previous user settings WCHAR strPath[MAX_PATH]; - SHGetFolderPath( DXUTGetHWND(), CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath ); - wcscat_s( strPath, MAX_PATH, L"\\DXUT\\SkipRefWarning.dat" ); - if( ( hFile = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, - NULL ) ) != INVALID_HANDLE_VALUE ) + if ( SUCCEEDED(SHGetFolderPath(DXUTGetHWND(), CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, strPath)) ) { - ReadFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwRead, NULL ); - CloseHandle( hFile ); + wcscat_s( strPath, MAX_PATH, L"\\DXUT\\SkipRefWarning.dat" ); + if( ( hFile = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, + nullptr ) ) != INVALID_HANDLE_VALUE ) + { + (void)ReadFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwRead, nullptr ); + CloseHandle( hFile ); + } } if( dwSkipWarning == 0 ) @@ -102,10 +123,7 @@ void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) }; LPARAM lParam; - if( ver == DXUT_D3D9_DEVICE ) - lParam = 9; - else - lParam = 11; + lParam = 11; int nResult = ( int )DialogBoxIndirectParam( DXUTGetHINSTANCE(), ( DLGTEMPLATE* )&dtp, DXUTGetHWND(), DisplaySwitchToREFWarningProc, lParam ); @@ -113,15 +131,17 @@ void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) { // Save user settings dwSkipWarning = 1; - SHGetFolderPath( DXUTGetHWND(), CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath ); - wcscat_s( strPath, MAX_PATH, L"\\DXUT" ); - CreateDirectory( strPath, NULL ); - wcscat_s( strPath, MAX_PATH, L"\\SkipRefWarning.dat" ); - if( ( hFile = CreateFile( strPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, - NULL ) ) != INVALID_HANDLE_VALUE ) + if ( SUCCEEDED(SHGetFolderPath(DXUTGetHWND(), CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, strPath)) ) { - WriteFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwWritten, NULL ); - CloseHandle( hFile ); + wcscat_s( strPath, MAX_PATH, L"\\DXUT" ); + CreateDirectory( strPath, nullptr ); + wcscat_s( strPath, MAX_PATH, L"\\SkipRefWarning.dat" ); + if( ( hFile = CreateFile( strPath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, + nullptr ) ) != INVALID_HANDLE_VALUE ) + { + WriteFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwWritten, nullptr ); + CloseHandle( hFile ); + } } } @@ -136,6 +156,7 @@ void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) //-------------------------------------------------------------------------------------- // MsgProc for DXUTDisplaySwitchingToREFWarning() dialog box //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ INT_PTR CALLBACK DisplaySwitchToREFWarningProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ) { switch( message ) @@ -146,7 +167,7 @@ INT_PTR CALLBACK DisplaySwitchToREFWarningProc( HWND hDlg, UINT message, WPARAM SendMessage( GetDlgItem( hDlg, 0x100 ), STM_SETIMAGE, IMAGE_ICON, ( LPARAM )LoadIcon( 0, IDI_QUESTION ) ); WCHAR sz[512]; swprintf_s( sz, 512, - L"This program needs to use the Direct3D %d reference device. This device implements the entire Direct3D %d feature set, but runs very slowly. Do you wish to continue?", lParam, lParam ); + L"This program needs to use the Direct3D %zu reference device. This device implements the entire Direct3D %zu feature set, but runs very slowly. Do you wish to continue?", lParam, lParam ); SetDlgItemText( hDlg, 0x101, sz ); SetDlgItemText( hDlg, IDYES, L"&Yes" ); SetDlgItemText( hDlg, IDNO, L"&No" ); @@ -189,6 +210,7 @@ WCHAR* DXUTMediaSearchPath() } + //-------------------------------------------------------------------------------------- LPCWSTR WINAPI DXUTGetMediaSearchPath() { @@ -197,7 +219,7 @@ LPCWSTR WINAPI DXUTGetMediaSearchPath() //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTSetMediaSearchPath( LPCWSTR strPath ) +HRESULT WINAPI DXUTSetMediaSearchPath( _In_z_ LPCWSTR strPath ) { HRESULT hr; @@ -224,13 +246,14 @@ HRESULT WINAPI DXUTSetMediaSearchPath( LPCWSTR strPath ) // cchDest is the size in WCHARs of strDestPath. Be careful not to // pass in sizeof(strDest) on UNICODE builds. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, LPCWSTR strFilename ) { bool bFound; WCHAR strSearchFor[MAX_PATH]; - if( NULL == strFilename || strFilename[0] == 0 || NULL == strDestPath || cchDest < 10 ) + if( !strFilename || strFilename[0] == 0 || !strDestPath || cchDest < 10 ) return E_INVALIDARG; // Get the exe name, and exe path @@ -242,8 +265,8 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, { 0 }; - WCHAR* strLastSlash = NULL; - GetModuleFileName( NULL, strExePath, MAX_PATH ); + WCHAR* strLastSlash = nullptr; + GetModuleFileName( nullptr, strExePath, MAX_PATH ); strExePath[MAX_PATH - 1] = 0; strLastSlash = wcsrchr( strExePath, TEXT( '\\' ) ); if( strLastSlash ) @@ -275,7 +298,7 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, return S_OK; // Typical directory search again, but also look in a subdir called "\media\" - swprintf_s( strSearchFor, MAX_PATH, L"media\\%s", strFilename ); + swprintf_s( strSearchFor, MAX_PATH, L"media\\%ls", strFilename ); bFound = DXUTFindMediaSearchTypicalDirs( strDestPath, cchDest, strSearchFor, strExePath, strExeName ); if( bFound ) return S_OK; @@ -297,7 +320,7 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, return S_OK; // Search all parent directories starting at .\ and using "media\strFilename" as the leaf name - swprintf_s( strLeafName, MAX_PATH, L"media\\%s", strFilename ); + swprintf_s( strLeafName, MAX_PATH, L"media\\%ls", strFilename ); bFound = DXUTFindMediaSearchParentDirs( strDestPath, cchDest, L".", strLeafName ); if( bFound ) return S_OK; @@ -317,8 +340,9 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, //-------------------------------------------------------------------------------------- // Search a set of typical directories //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWSTR strLeaf, - WCHAR* strExePath, WCHAR* strExeName ) + const WCHAR* strExePath, const WCHAR* strExeName ) { // Typical directories: // .\ @@ -337,42 +361,42 @@ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWST return true; // Search in ..\ - swprintf_s( strSearchPath, cchSearch, L"..\\%s", strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"..\\%ls", strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in ..\..\ - swprintf_s( strSearchPath, cchSearch, L"..\\..\\%s", strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"..\\..\\%ls", strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in ..\..\ - swprintf_s( strSearchPath, cchSearch, L"..\\..\\%s", strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"..\\..\\%ls", strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\ - swprintf_s( strSearchPath, cchSearch, L"%s\\%s", strExePath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\%ls", strExePath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\..\ - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\%s", strExePath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\%ls", strExePath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\..\..\ - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\..\\%s", strExePath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\..\\%ls", strExePath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in "%EXE_DIR%\..\%EXE_NAME%\". This matches the DirectX SDK layout - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\%s\\%s", strExePath, strExeName, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\%ls\\%ls", strExePath, strExeName, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in "%EXE_DIR%\..\..\%EXE_NAME%\". This matches the DirectX SDK layout - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\..\\%s\\%s", strExePath, strExeName, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\..\\%ls\\%ls", strExePath, strExeName, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; @@ -380,7 +404,7 @@ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWST WCHAR* s_strSearchPath = DXUTMediaSearchPath(); if( s_strSearchPath[0] != 0 ) { - swprintf_s( strSearchPath, cchSearch, L"%s%s", s_strSearchPath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls%ls", s_strSearchPath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; } @@ -389,13 +413,13 @@ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWST } - //-------------------------------------------------------------------------------------- // Search parent directories starting at strStartAt, and appending strLeafName // at each parent directory. It stops at the root directory. //-------------------------------------------------------------------------------------- -bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, WCHAR* strStartAt, - WCHAR* strLeafName ) +_Use_decl_annotations_ +bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, const WCHAR* strStartAt, + const WCHAR* strLeafName ) { WCHAR strFullPath[MAX_PATH] = { @@ -409,23 +433,24 @@ bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, WCHAR* { 0 }; - WCHAR* strFilePart = NULL; + WCHAR* strFilePart = nullptr; - GetFullPathName( strStartAt, MAX_PATH, strFullPath, &strFilePart ); - if( strFilePart == NULL ) + if ( !GetFullPathName( strStartAt, MAX_PATH, strFullPath, &strFilePart ) ) return false; - while( strFilePart != NULL && *strFilePart != '\0' ) +#pragma warning( disable : 6102 ) + while( strFilePart && *strFilePart != '\0' ) { - swprintf_s( strFullFileName, MAX_PATH, L"%s\\%s", strFullPath, strLeafName ); + swprintf_s( strFullFileName, MAX_PATH, L"%ls\\%ls", strFullPath, strLeafName ); if( GetFileAttributes( strFullFileName ) != 0xFFFFFFFF ) { wcscpy_s( strSearchPath, cchSearch, strFullFileName ); return true; } - swprintf_s( strSearch, MAX_PATH, L"%s\\..", strFullPath ); - GetFullPathName( strSearch, MAX_PATH, strFullPath, &strFilePart ); + swprintf_s( strSearch, MAX_PATH, L"%ls\\..", strFullPath ); + if ( !GetFullPathName( strSearch, MAX_PATH, strFullPath, &strFilePart ) ) + return false; } return false; @@ -433,1188 +458,483 @@ bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, WCHAR* //-------------------------------------------------------------------------------------- -// CDXUTResourceCache +// Compiles HLSL shaders //-------------------------------------------------------------------------------------- +#if D3D_COMPILER_VERSION < 46 -//-------------------------------------------------------------------------------------- -CDXUTResourceCache::~CDXUTResourceCache() +namespace { - OnDestroyDevice(); - m_TextureCache.RemoveAll(); - m_EffectCache.RemoveAll(); - m_FontCache.RemoveAll(); -} +struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ) -{ - return CreateTextureFromFileEx( pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, - 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppTexture ); -} +typedef std::unique_ptr ScopedHandle; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ) -{ - WCHAR szSrcFile[MAX_PATH]; - MultiByteToWideChar( CP_ACP, 0, pSrcFile, -1, szSrcFile, MAX_PATH ); - szSrcFile[MAX_PATH - 1] = 0; +inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; } - return CreateTextureFromFile( pDevice, szSrcFile, ppTexture ); -} - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCTSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) +class CIncludeHandler : public ID3DInclude + // Not as robust as D3D_COMPILE_STANDARD_FILE_INCLUDE, but it works in most cases { - return CreateTextureFromFileEx( pDevice, pContext, pSrcFile, NULL, NULL, ppOutputRV, bSRGB ); -} +private: + static const unsigned int MAX_INCLUDES = 9; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) -{ - WCHAR szSrcFile[MAX_PATH]; - MultiByteToWideChar( CP_ACP, 0, pSrcFile, -1, szSrcFile, MAX_PATH ); - szSrcFile[MAX_PATH - 1] = 0; + struct sInclude + { + HANDLE hFile; + HANDLE hFileMap; + LARGE_INTEGER FileSize; + void *pMapData; + }; - return CreateTextureFromFile( pDevice, pContext, szSrcFile, ppOutputRV, bSRGB ); -} + struct sInclude m_includeFiles[MAX_INCLUDES]; + size_t m_nIncludes; + bool m_reset; + WCHAR m_workingPath[MAX_PATH]; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Width, - UINT Height, UINT MipLevels, DWORD Usage, D3DFORMAT Format, - D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DTEXTURE9* ppTexture ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) +public: + CIncludeHandler() : m_nIncludes(0), m_reset(false) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_TEXTURE ) + if ( !GetCurrentDirectoryW( MAX_PATH, m_workingPath ) ) + *m_workingPath = 0; + + for ( size_t i = 0; i < MAX_INCLUDES; ++i ) { - // A match is found. Obtain the IDirect3DTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DTexture9, ( LPVOID* )ppTexture ); + m_includeFiles[i].hFile = INVALID_HANDLE_VALUE; + m_includeFiles[i].hFileMap = INVALID_HANDLE_VALUE; + m_includeFiles[i].pMapData = nullptr; } } + virtual ~CIncludeHandler() + { + for ( size_t i = 0; i < m_nIncludes; ++i ) + { + UnmapViewOfFile( m_includeFiles[i].pMapData ); -#if defined(PROFILE) || defined(DEBUG) - CHAR strFileA[MAX_PATH]; - WideCharToMultiByte( CP_ACP, 0, pSrcFile, -1, strFileA, MAX_PATH, NULL, FALSE ); - CHAR* pstrName = strrchr( strFileA, '\\' ); - if( pstrName == NULL ) - pstrName = strFileA; - else - pstrName++; -#endif - - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateTextureFromFileEx( pDevice, pSrcFile, Width, Height, MipLevels, Usage, Format, - Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_TEXTURE; - ( *ppTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - DXUT_SetDebugName( *ppTexture, pstrName ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} - - + if ( m_includeFiles[i].hFileMap != INVALID_HANDLE_VALUE) + CloseHandle( m_includeFiles[i].hFileMap ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFileEx( ID3D11Device* pDevice, ID3D11DeviceContext* pContext, LPCTSTR pSrcFile, - D3DX11_IMAGE_LOAD_INFO* pLoadInfo, ID3DX11ThreadPump* pPump, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) -{ + if ( m_includeFiles[i].hFile != INVALID_HANDLE_VALUE) + CloseHandle( m_includeFiles[i].hFile ); + } - bool is10L9 = DXUTGetDeviceSettings().d3d11.DeviceFeatureLevel < D3D_FEATURE_LEVEL_10_0; - HRESULT hr = S_OK; - D3DX11_IMAGE_LOAD_INFO ZeroInfo; //D3DX11_IMAGE_LOAD_INFO has a default constructor - D3DX11_IMAGE_INFO SrcInfo; + m_nIncludes = 0; - if( !pLoadInfo ) - { - pLoadInfo = &ZeroInfo; + if ( m_reset && *m_workingPath ) + { + SetCurrentDirectoryW( m_workingPath ); + } } - if( !pLoadInfo->pSrcInfo ) + STDMETHOD(Open( D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes ) ) { - D3DX11GetImageInfoFromFile( pSrcFile, NULL, &SrcInfo, NULL ); - pLoadInfo->pSrcInfo = &SrcInfo; + UNREFERENCED_PARAMETER(IncludeType); + UNREFERENCED_PARAMETER(pParentData); - pLoadInfo->Format = pLoadInfo->pSrcInfo->Format; - } + size_t incIndex = m_nIncludes+1; - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) - { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == pLoadInfo->Width && - Entry.Height == pLoadInfo->Height && - Entry.MipLevels == pLoadInfo->MipLevels && - Entry.Usage11 == pLoadInfo->Usage && - Entry.Format == pLoadInfo->Format && - Entry.CpuAccessFlags == pLoadInfo->CpuAccessFlags && - Entry.BindFlags == pLoadInfo->BindFlags && - Entry.MiscFlags == pLoadInfo->MiscFlags ) + // Make sure we have enough room for this include file + if ( incIndex >= MAX_INCLUDES ) + return E_FAIL; + + // try to open the file + m_includeFiles[incIndex].hFile = CreateFileA( pFileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr ); + if( INVALID_HANDLE_VALUE == m_includeFiles[incIndex].hFile ) { - // A match is found. Obtain the IDirect3DTexture9 interface and return that. - return Entry.pSRV11->QueryInterface( __uuidof( ID3D11ShaderResourceView ), ( LPVOID* )ppOutputRV ); + return E_FAIL; } - } -#if defined(PROFILE) || defined(DEBUG) - CHAR strFileA[MAX_PATH]; - WideCharToMultiByte( CP_ACP, 0, pSrcFile, -1, strFileA, MAX_PATH, NULL, FALSE ); - CHAR* pstrName = strrchr( strFileA, '\\' ); - if( pstrName == NULL ) - pstrName = strFileA; - else - pstrName++; -#endif + // Get the file size + GetFileSizeEx( m_includeFiles[incIndex].hFile, &m_includeFiles[incIndex].FileSize ); - //Ready a new entry to the texture cache - //Do this before creating the texture since pLoadInfo may be volatile - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = pLoadInfo->Width; - NewEntry.Height = pLoadInfo->Height; - NewEntry.MipLevels = pLoadInfo->MipLevels; - NewEntry.Usage11 = pLoadInfo->Usage; - // 10L9 can't handle typesless, so we cant make a typesless format - if (is10L9 && bSRGB) { - NewEntry.Format = MAKE_SRGB(pLoadInfo->Format); - }else { - NewEntry.Format = pLoadInfo->Format; - } - NewEntry.CpuAccessFlags = pLoadInfo->CpuAccessFlags; - NewEntry.BindFlags = pLoadInfo->BindFlags; - NewEntry.MiscFlags = pLoadInfo->MiscFlags; + // Use Memory Mapped File I/O for the header data + m_includeFiles[incIndex].hFileMap = CreateFileMappingA( m_includeFiles[incIndex].hFile, nullptr, PAGE_READONLY, m_includeFiles[incIndex].FileSize.HighPart, m_includeFiles[incIndex].FileSize.LowPart, pFileName); + if( !m_includeFiles[incIndex].hFileMap ) + { + if (m_includeFiles[incIndex].hFile != INVALID_HANDLE_VALUE) + CloseHandle( m_includeFiles[incIndex].hFile ); + return E_FAIL; + } - //Create the rexture - ID3D11Texture2D* pRes = NULL; - hr = D3DX11CreateTextureFromFile( pDevice, pSrcFile, pLoadInfo, pPump, ( ID3D11Resource** )&pRes, NULL ); + // Create Map view + *ppData = MapViewOfFile( m_includeFiles[incIndex].hFileMap, FILE_MAP_READ, 0, 0, 0 ); + *pBytes = m_includeFiles[incIndex].FileSize.LowPart; - if( FAILED( hr ) ) - return hr; - D3D11_TEXTURE2D_DESC tex_dsc; - pRes->GetDesc(&tex_dsc); - - - - if (bSRGB ) { - // This is a workaround so that we can load linearly, but sample in SRGB. Right now, we can't load - // as linear since D3DX will try to do conversion on load. Loading as TYPELESS doesn't work either, and - // loading as typed _UNORM doesn't allow us to create an SRGB view. - - // on d3d11 featuer levels this is just a copy, but on 10L9 we must use a cpu side copy with 2 staging resources. - ID3D11Texture2D* unormStaging = NULL; - ID3D11Texture2D* srgbStaging = NULL; - - D3D11_TEXTURE2D_DESC CopyDesc; - pRes->GetDesc( &CopyDesc ); - - pLoadInfo->BindFlags = 0; - pLoadInfo->CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; - pLoadInfo->Depth = 0; - pLoadInfo->Filter = D3DX11_FILTER_LINEAR; - pLoadInfo->FirstMipLevel = 0; - pLoadInfo->Format = CopyDesc.Format; - pLoadInfo->Height = CopyDesc.Height; - pLoadInfo->MipFilter = D3DX11_FILTER_LINEAR; - pLoadInfo->MiscFlags = CopyDesc.MiscFlags; - pLoadInfo->Usage = D3D11_USAGE_STAGING; - pLoadInfo->Width = CopyDesc.Width; - - CopyDesc.BindFlags = 0; - CopyDesc.Usage = D3D11_USAGE_STAGING; - CopyDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; - CopyDesc.Format = MAKE_SRGB(CopyDesc.Format); - - hr = D3DX11CreateTextureFromFile( pDevice, pSrcFile, pLoadInfo, pPump, ( ID3D11Resource** )&unormStaging, NULL ); - DXUT_SetDebugName( unormStaging, "CDXUTResourceCache" ); - - hr = pDevice->CreateTexture2D(&CopyDesc, NULL, &srgbStaging); - DXUT_SetDebugName( srgbStaging, "CDXUTResourceCache" ); - pContext->CopyResource( srgbStaging, unormStaging ); - ID3D11Texture2D* srgbGPU; - - pRes->GetDesc( &CopyDesc ); - CopyDesc.Format = MAKE_SRGB(CopyDesc.Format); - hr = pDevice->CreateTexture2D(&CopyDesc, NULL, &srgbGPU); - pContext->CopyResource( srgbGPU, srgbStaging ); - - SAFE_RELEASE(pRes); - SAFE_RELEASE(srgbStaging); - SAFE_RELEASE(unormStaging); - pRes = srgbGPU; - } + // Success - Increment the include file count + m_nIncludes = incIndex; - DXUT_SetDebugName( pRes, pstrName ); + return S_OK; + } - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - if( bSRGB ) - SRVDesc.Format = MAKE_SRGB( ZeroInfo.Format ); - else - SRVDesc.Format = ZeroInfo.Format; - if( pLoadInfo->pSrcInfo->ResourceDimension == D3D11_RESOURCE_DIMENSION_TEXTURE1D ) + STDMETHOD(Close( LPCVOID pData )) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; - SRVDesc.Texture1D.MostDetailedMip = 0; - SRVDesc.Texture1D.MipLevels = pLoadInfo->pSrcInfo->MipLevels; + UNREFERENCED_PARAMETER(pData); + // Defer Closure until the container destructor + return S_OK; } - else if( pLoadInfo->pSrcInfo->ResourceDimension == D3D11_RESOURCE_DIMENSION_TEXTURE2D ) + + void SetCWD( LPCWSTR pFileName ) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Texture2D.MostDetailedMip = 0; - SRVDesc.Texture2D.MipLevels = pLoadInfo->pSrcInfo->MipLevels; + WCHAR filePath[MAX_PATH]; + wcscpy_s( filePath, MAX_PATH, pFileName ); - if( pLoadInfo->pSrcInfo->MiscFlags & D3D11_RESOURCE_MISC_TEXTURECUBE ) + WCHAR *strLastSlash = wcsrchr( filePath, L'\\' ); + if( strLastSlash ) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; - SRVDesc.TextureCube.MostDetailedMip = 0; - SRVDesc.TextureCube.MipLevels = pLoadInfo->pSrcInfo->MipLevels; + // Chop the exe name from the exe path + *strLastSlash = 0; + m_reset = true; + SetCurrentDirectoryW( filePath ); } } - else if( pLoadInfo->pSrcInfo->ResourceDimension == D3D11_RESOURCE_DIMENSION_TEXTURE3D ) - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; - SRVDesc.Texture3D.MostDetailedMip = 0; - SRVDesc.Texture3D.MipLevels = pLoadInfo->pSrcInfo->MipLevels; - } - if (bSRGB) { - SRVDesc.Format = MAKE_SRGB(tex_dsc.Format); - }else { - SRVDesc.Format = tex_dsc.Format; - } - SRVDesc.Texture2D.MipLevels = tex_dsc.MipLevels; - SRVDesc.Texture2D.MostDetailedMip = 0; - hr = pDevice->CreateShaderResourceView( pRes, &SRVDesc, ppOutputRV ); - pRes->Release(); - if( FAILED( hr ) ) - return hr; - - DXUT_SetDebugName( *ppOutputRV, pstrName ); - - ( *ppOutputRV )->QueryInterface( __uuidof( ID3D11ShaderResourceView ), ( LPVOID* )&NewEntry.pSRV11 ); - - m_TextureCache.Add( NewEntry ); - - return S_OK; -} - +}; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, LPDIRECT3DTEXTURE9* ppTexture ) -{ - return CreateTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, - D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, - D3DX_DEFAULT, 0, NULL, NULL, ppTexture ); -} +}; // namespace +#endif -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, UINT Width, UINT Height, UINT MipLevels, - DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO* pSrcInfo, - PALETTEENTRY* pPalette, LPDIRECT3DTEXTURE9* ppTexture ) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCompileFromFile( LPCWSTR pFileName, + const D3D_SHADER_MACRO* pDefines, + LPCSTR pEntrypoint, LPCSTR pTarget, + UINT Flags1, UINT Flags2, + ID3DBlob** ppCode ) { - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) - { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_TEXTURE ) - { - // A match is found. Obtain the IDirect3DTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DTexture9, ( LPVOID* )ppTexture ); - } - } - HRESULT hr; + WCHAR str[MAX_PATH]; + V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, pFileName ) ); + +#if defined( DEBUG ) || defined( _DEBUG ) + // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. + // Setting this flag improves the shader debugging experience, but still allows + // the shaders to be optimized and to run exactly the way they will run in + // the release configuration of this program. + Flags1 |= D3DCOMPILE_DEBUG; +#endif - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, Width, Height, MipLevels, Usage, - Format, Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppTexture ); - if( FAILED( hr ) ) - return hr; + ID3DBlob* pErrorBlob = nullptr; - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_TEXTURE; - ( *ppTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} +#if D3D_COMPILER_VERSION >= 46 + hr = D3DCompileFromFile( str, pDefines, D3D_COMPILE_STANDARD_FILE_INCLUDE, + pEntrypoint, pTarget, Flags1, Flags2, + ppCode, &pErrorBlob ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateCubeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ) -{ - return CreateCubeTextureFromFileEx( pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, 0, - D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppCubeTexture ); -} +#else + ScopedHandle hFile( safe_handle( CreateFileW( str, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr ) ) ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateCubeTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Size, - UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, - DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) + if ( !hFile ) + return HRESULT_FROM_WIN32( GetLastError() ); + + FILE_STANDARD_INFO fileInfo; + if ( !GetFileInformationByHandleEx( hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo) ) ) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == Size && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_CUBETEXTURE ) - { - // A match is found. Obtain the IDirect3DCubeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DCubeTexture9, ( LPVOID* )ppCubeTexture ); - } + return HRESULT_FROM_WIN32( GetLastError() ); } - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateCubeTextureFromFileEx( pDevice, pSrcFile, Size, MipLevels, Usage, Format, Pool, Filter, - MipFilter, ColorKey, pSrcInfo, pPalette, ppCubeTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = Size; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_CUBETEXTURE; - ( *ppCubeTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} + if ( !fileInfo.EndOfFile.LowPart || fileInfo.EndOfFile.HighPart > 0 ) + return E_FAIL; + std::unique_ptr fxData; + fxData.reset( new (std::nothrow) char[ fileInfo.EndOfFile.LowPart ] ); + if ( !fxData ) + return E_OUTOFMEMORY; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateCubeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ) -{ - return CreateCubeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, - 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppCubeTexture ); -} + DWORD BytesRead = 0; + if ( !ReadFile( hFile.get(), fxData.get(), fileInfo.EndOfFile.LowPart, &BytesRead, nullptr ) ) + return HRESULT_FROM_WIN32( GetLastError() ); + if (BytesRead < fileInfo.EndOfFile.LowPart) + return E_FAIL; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateCubeTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, UINT Size, UINT MipLevels, - DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) + char pSrcName[MAX_PATH]; + int result = WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS, str, -1, pSrcName, MAX_PATH, nullptr, FALSE ); + if ( !result ) + return E_FAIL; + + const CHAR* pstrName = strrchr( pSrcName, '\\' ); + if (!pstrName) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.Width == Size && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_CUBETEXTURE ) - { - // A match is found. Obtain the IDirect3DCubeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DCubeTexture9, ( LPVOID* )ppCubeTexture ); - } + pstrName = pSrcName; } - - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateCubeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, Size, MipLevels, Usage, Format, - Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppCubeTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.Width = Size; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_CUBETEXTURE; - ( *ppCubeTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateVolumeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ) -{ - return CreateVolumeTextureFromFileEx( pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, - 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppVolumeTexture ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateVolumeTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Width, - UINT Height, UINT Depth, UINT MipLevels, DWORD Usage, - D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DVOLUMETEXTURE9* ppTexture ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) + else { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.Depth == Depth && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_VOLUMETEXTURE ) - { - // A match is found. Obtain the IDirect3DVolumeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DVolumeTexture9, ( LPVOID* )ppTexture ); - } + pstrName++; } - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateVolumeTextureFromFileEx( pDevice, pSrcFile, Width, Height, Depth, MipLevels, Usage, Format, - Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.Depth = Depth; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_VOLUMETEXTURE; - ( *ppTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} + std::unique_ptr includes( new (std::nothrow) CIncludeHandler ); + if ( !includes ) + return E_OUTOFMEMORY; + includes->SetCWD( str ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateVolumeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ) -{ - return CreateVolumeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, - D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppVolumeTexture ); -} + hr = D3DCompile( fxData.get(), BytesRead, pstrName, pDefines, includes.get(), + pEntrypoint, pTarget, Flags1, Flags2, + ppCode, &pErrorBlob ); +#endif -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateVolumeTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, UINT Width, UINT Height, - UINT Depth, UINT MipLevels, DWORD Usage, - D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) +#pragma warning( suppress : 6102 ) + if ( pErrorBlob ) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.Depth == Depth && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_VOLUMETEXTURE ) - { - // A match is found. Obtain the IDirect3DVolumeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DVolumeTexture9, ( LPVOID* )ppVolumeTexture ); - } + OutputDebugStringA( reinterpret_cast( pErrorBlob->GetBufferPointer() ) ); + pErrorBlob->Release(); } - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateVolumeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, Width, Height, Depth, MipLevels, - Usage, - Format, Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, - ppVolumeTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.Depth = Depth; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_VOLUMETEXTURE; - ( *ppVolumeTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; + return hr; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateFont( LPDIRECT3DDEVICE9 pDevice, UINT Height, UINT Width, UINT Weight, - UINT MipLevels, BOOL Italic, DWORD CharSet, DWORD OutputPrecision, - DWORD Quality, DWORD PitchAndFamily, LPCTSTR pFacename, LPD3DXFONT* ppFont ) -{ - D3DXFONT_DESCW Desc; - - Desc.Height = Height; - Desc.Width = Width; - Desc.Weight = Weight; - Desc.MipLevels = MipLevels; - Desc.Italic = Italic; - Desc.CharSet = ( BYTE )CharSet; - Desc.OutputPrecision = ( BYTE )OutputPrecision; - Desc.Quality = ( BYTE )Quality; - Desc.PitchAndFamily = ( BYTE )PitchAndFamily; - wcscpy_s( Desc.FaceName, LF_FACESIZE, pFacename ); - - return CreateFontIndirect( pDevice, &Desc, ppFont ); -} - - +// Texture utilities //-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateFontIndirect( LPDIRECT3DDEVICE9 pDevice, CONST D3DXFONT_DESC *pDesc, LPD3DXFONT *ppFont ) - { - // Search the cache for a matching entry. - for( int i = 0; i < m_FontCache.GetSize(); ++i ) - { - DXUTCache_Font &Entry = m_FontCache[i]; - - if( Entry.Width == pDesc->Width && - Entry.Height == pDesc->Height && - Entry.Weight == pDesc->Weight && - Entry.MipLevels == pDesc->MipLevels && - Entry.Italic == pDesc->Italic && - Entry.CharSet == pDesc->CharSet && - Entry.OutputPrecision == pDesc->OutputPrecision && - Entry.Quality == pDesc->Quality && - Entry.PitchAndFamily == pDesc->PitchAndFamily && - CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, - Entry.FaceName, -1, - pDesc->FaceName, -1 ) == CSTR_EQUAL ) - { - // A match is found. Increment the reference and return the ID3DXFont object. - Entry.pFont->AddRef(); - *ppFont = Entry.pFont; - return S_OK; - } - } - HRESULT hr; +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateShaderResourceViewFromFile( ID3D11Device* d3dDevice, const wchar_t* szFileName, ID3D11ShaderResourceView** textureView ) +{ + if ( !d3dDevice || !szFileName || !textureView ) + return E_INVALIDARG; - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateFontIndirect( pDevice, pDesc, ppFont ); - if( FAILED( hr ) ) + WCHAR str[MAX_PATH]; + HRESULT hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ); + if ( FAILED(hr) ) return hr; - DXUTCache_Font NewEntry; - ( D3DXFONT_DESC & )NewEntry = *pDesc; - NewEntry.pFont = *ppFont; - NewEntry.pFont->AddRef(); - - m_FontCache.Add( NewEntry ); - return S_OK; -} - + WCHAR ext[_MAX_EXT]; + _wsplitpath_s( str, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateEffectFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - const D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, DWORD Flags, - LPD3DXEFFECTPOOL pPool, LPD3DXEFFECT* ppEffect, - LPD3DXBUFFER* ppCompilationErrors ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) + if ( _wcsicmp( ext, L".dds" ) == 0 ) { - DXUTCache_Effect& Entry = m_EffectCache[i]; - - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.dwFlags == Flags ) - { - // A match is found. Increment the ref coutn and return the ID3DXEffect object. - *ppEffect = Entry.pEffect; - ( *ppEffect )->AddRef(); - return S_OK; - } + hr = DirectX::CreateDDSTextureFromFile( d3dDevice, str, nullptr, textureView ); } - - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. -#ifdef D3DXFX_LARGEADDRESS_HANDLE - Flags |= D3DXFX_LARGEADDRESSAWARE; -#endif - - hr = D3DXCreateEffectFromFile( pDevice, pSrcFile, pDefines, pInclude, Flags, pPool, ppEffect, - ppCompilationErrors ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Effect NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.dwFlags = Flags; - NewEntry.pEffect = *ppEffect; - NewEntry.pEffect->AddRef(); - - m_EffectCache.Add( NewEntry ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateEffectFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, const D3DXMACRO* pDefines, - LPD3DXINCLUDE pInclude, DWORD Flags, LPD3DXEFFECTPOOL pPool, - LPD3DXEFFECT* ppEffect, LPD3DXBUFFER* ppCompilationErrors ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) + else { - DXUTCache_Effect& Entry = m_EffectCache[i]; - - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.dwFlags == Flags ) - { - // A match is found. Increment the ref coutn and return the ID3DXEffect object. - *ppEffect = Entry.pEffect; - ( *ppEffect )->AddRef(); - return S_OK; - } + hr = DirectX::CreateWICTextureFromFile( d3dDevice, nullptr, str, nullptr, textureView ); } - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. -#ifdef D3DXFX_LARGEADDRESS_HANDLE - Flags |= D3DXFX_LARGEADDRESSAWARE; -#endif - - hr = D3DXCreateEffectFromResource( pDevice, hSrcModule, pSrcResource, pDefines, pInclude, Flags, - pPool, ppEffect, ppCompilationErrors ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Effect NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.dwFlags = Flags; - NewEntry.pEffect = *ppEffect; - NewEntry.pEffect->AddRef(); - - m_EffectCache.Add( NewEntry ); - return S_OK; + return hr; } - -//-------------------------------------------------------------------------------------- -// Device event callbacks -//-------------------------------------------------------------------------------------- - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnCreateDevice( IDirect3DDevice9* pd3dDevice ) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateTextureFromFile( ID3D11Device* d3dDevice, const wchar_t* szFileName, ID3D11Resource** texture ) { - return S_OK; -} + if ( !d3dDevice || !szFileName || !texture ) + return E_INVALIDARG; + WCHAR str[MAX_PATH]; + HRESULT hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ); + if ( FAILED(hr) ) + return hr; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnResetDevice( IDirect3DDevice9* pd3dDevice ) -{ - // Call OnResetDevice on all effect and font objects - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) - m_EffectCache[i].pEffect->OnResetDevice(); - for( int i = 0; i < m_FontCache.GetSize(); ++i ) - m_FontCache[i].pFont->OnResetDevice(); + WCHAR ext[_MAX_EXT]; + _wsplitpath_s( str, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT ); + if ( _wcsicmp( ext, L".dds" ) == 0 ) + { + hr = DirectX::CreateDDSTextureFromFile( d3dDevice, str, texture, nullptr ); + } + else + { + hr = DirectX::CreateWICTextureFromFile( d3dDevice, nullptr, str, texture, nullptr ); + } - return S_OK; + return hr; } - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnLostDevice() +_Use_decl_annotations_ +HRESULT WINAPI DXUTSaveTextureToFile( ID3D11DeviceContext* pContext, ID3D11Resource* pSource, bool usedds, const wchar_t* szFileName ) { - // Call OnLostDevice on all effect and font objects - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) - m_EffectCache[i].pEffect->OnLostDevice(); - for( int i = 0; i < m_FontCache.GetSize(); ++i ) - m_FontCache[i].pFont->OnLostDevice(); - - // Release all the default pool textures - for( int i = m_TextureCache.GetSize() - 1; i >= 0; --i ) - if( m_TextureCache[i].Pool9 == D3DPOOL_DEFAULT ) - { - SAFE_RELEASE( m_TextureCache[i].pTexture9 ); - m_TextureCache.Remove( i ); // Remove the entry - } - - return S_OK; -} + if ( !pContext || !pSource || !szFileName ) + return E_INVALIDARG; + HRESULT hr; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnDestroyDevice() -{ - // Release all resources - for( int i = m_EffectCache.GetSize() - 1; i >= 0; --i ) + if ( usedds ) { - SAFE_RELEASE( m_EffectCache[i].pEffect ); - m_EffectCache.Remove( i ); + hr = DirectX::SaveDDSTextureToFile( pContext, pSource, szFileName ); } - for( int i = m_FontCache.GetSize() - 1; i >= 0; --i ) - { - SAFE_RELEASE( m_FontCache[i].pFont ); - m_FontCache.Remove( i ); - } - for( int i = m_TextureCache.GetSize() - 1; i >= 0; --i ) + else { - SAFE_RELEASE( m_TextureCache[i].pTexture9 ); - SAFE_RELEASE( m_TextureCache[i].pSRV11 ); - m_TextureCache.Remove( i ); + hr = DirectX::SaveWICTextureToFile( pContext, pSource, GUID_ContainerFormatBmp, szFileName ); } - return S_OK; + return hr; } //-------------------------------------------------------------------------------------- // Desc: Returns a view matrix for rendering to a face of a cubemap. //-------------------------------------------------------------------------------------- -D3DXMATRIX WINAPI DXUTGetCubeMapViewMatrix( DWORD dwFace ) +XMMATRIX WINAPI DXUTGetCubeMapViewMatrix( _In_ DWORD dwFace ) { - D3DXVECTOR3 vEyePt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); - D3DXVECTOR3 vLookDir; - D3DXVECTOR3 vUpDir; - - switch( dwFace ) + static const XMVECTORF32 s_vLookDir[] = { - case D3DCUBEMAP_FACE_POSITIVE_X: - vLookDir = D3DXVECTOR3( 1.0f, 0.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - case D3DCUBEMAP_FACE_NEGATIVE_X: - vLookDir = D3DXVECTOR3( -1.0f, 0.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - case D3DCUBEMAP_FACE_POSITIVE_Y: - vLookDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 0.0f, -1.0f ); - break; - case D3DCUBEMAP_FACE_NEGATIVE_Y: - vLookDir = D3DXVECTOR3( 0.0f, -1.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); - break; - case D3DCUBEMAP_FACE_POSITIVE_Z: - vLookDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - case D3DCUBEMAP_FACE_NEGATIVE_Z: - vLookDir = D3DXVECTOR3( 0.0f, 0.0f, -1.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - } + { 1.0f, 0.0f, 0.0f, 0.0f }, + { -1.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, -1.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + }; - // Set the view transform for this cubemap surface - D3DXMATRIXA16 mView; - D3DXMatrixLookAtLH( &mView, &vEyePt, &vLookDir, &vUpDir ); - return mView; -} + static const XMVECTORF32 s_vUpDir[] = + { + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + }; + static_assert( _countof(s_vLookDir) == _countof(s_vUpDir), "arrays mismatch" ); -//-------------------------------------------------------------------------------------- -CDXUTLineManager::CDXUTLineManager() -{ - m_pd3dDevice = NULL; - m_pD3DXLine = NULL; -} - + if ( dwFace >= _countof(s_vLookDir) + || dwFace >= _countof(s_vUpDir) ) + return XMMatrixIdentity(); -//-------------------------------------------------------------------------------------- -CDXUTLineManager::~CDXUTLineManager() -{ - OnDeletedDevice(); + // Set the view transform for this cubemap surface + return XMMatrixLookAtLH( g_XMZero, s_vLookDir[ dwFace ], s_vUpDir[ dwFace ] ); } -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnCreatedDevice( IDirect3DDevice9* pd3dDevice ) -{ - m_pd3dDevice = pd3dDevice; - - HRESULT hr; - hr = D3DXCreateLine( m_pd3dDevice, &m_pD3DXLine ); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} - +//====================================================================================== +// CDXUTResourceCache +//====================================================================================== -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnResetDevice() +CDXUTResourceCache::~CDXUTResourceCache() { - if( m_pD3DXLine ) - m_pD3DXLine->OnResetDevice(); - - return S_OK; + OnDestroyDevice(); } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnRender() +_Use_decl_annotations_ +HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCWSTR pSrcFile, + ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) { - HRESULT hr; - if( NULL == m_pD3DXLine ) + if ( !ppOutputRV ) return E_INVALIDARG; - bool bDrawingHasBegun = false; - float fLastWidth = 0.0f; - bool bLastAntiAlias = false; + *ppOutputRV = nullptr; - for( int i = 0; i < m_LinesList.GetSize(); i++ ) + for( auto it = m_TextureCache.cbegin(); it != m_TextureCache.cend(); ++it ) { - LINE_NODE* pLineNode = m_LinesList.GetAt( i ); - if( pLineNode ) + if( !wcscmp( it->wszSource, pSrcFile ) + && it->bSRGB == bSRGB + && it->pSRV11 ) { - if( !bDrawingHasBegun || - fLastWidth != pLineNode->fWidth || - bLastAntiAlias != pLineNode->bAntiAlias ) - { - if( bDrawingHasBegun ) - { - hr = m_pD3DXLine->End(); - if( FAILED( hr ) ) - return hr; - } - - m_pD3DXLine->SetWidth( pLineNode->fWidth ); - m_pD3DXLine->SetAntialias( pLineNode->bAntiAlias ); - - fLastWidth = pLineNode->fWidth; - bLastAntiAlias = pLineNode->bAntiAlias; - - hr = m_pD3DXLine->Begin(); - if( FAILED( hr ) ) - return hr; - bDrawingHasBegun = true; - } - - hr = m_pD3DXLine->Draw( pLineNode->pVertexList, pLineNode->dwVertexListCount, pLineNode->Color ); - if( FAILED( hr ) ) - return hr; + it->pSRV11->AddRef(); + *ppOutputRV = it->pSRV11; + return S_OK; } } - if( bDrawingHasBegun ) - { - hr = m_pD3DXLine->End(); - if( FAILED( hr ) ) - return hr; - } - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnLostDevice() -{ - if( m_pD3DXLine ) - m_pD3DXLine->OnLostDevice(); - - return S_OK; -} + WCHAR ext[_MAX_EXT]; + _wsplitpath_s( pSrcFile, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT ); - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnDeletedDevice() -{ - RemoveAllLines(); - SAFE_RELEASE( m_pD3DXLine ); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::AddLine( int* pnLineID, D3DXVECTOR2* pVertexList, DWORD dwVertexListCount, D3DCOLOR Color, - float fWidth, float fScaleRatio, bool bAntiAlias ) -{ - if( pVertexList == NULL || dwVertexListCount == 0 ) - return E_INVALIDARG; - - LINE_NODE* pLineNode = new LINE_NODE; - if( pLineNode == NULL ) - return E_OUTOFMEMORY; - ZeroMemory( pLineNode, sizeof( LINE_NODE ) ); - - pLineNode->nLineID = m_LinesList.GetSize(); - pLineNode->Color = Color; - pLineNode->fWidth = fWidth; - pLineNode->bAntiAlias = bAntiAlias; - pLineNode->dwVertexListCount = dwVertexListCount; - - if( pnLineID ) - *pnLineID = pLineNode->nLineID; - - pLineNode->pVertexList = new D3DXVECTOR2[dwVertexListCount]; - if( pLineNode->pVertexList == NULL ) + HRESULT hr; + if ( _wcsicmp( ext, L".dds" ) == 0 ) { - delete pLineNode; - return E_OUTOFMEMORY; + hr = DirectX::CreateDDSTextureFromFileEx( pDevice, pSrcFile, 0, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, bSRGB, + nullptr, ppOutputRV, nullptr ); } - for( DWORD i = 0; i < dwVertexListCount; i++ ) + else { - pLineNode->pVertexList[i] = pVertexList[i] * fScaleRatio; + hr = DirectX::CreateWICTextureFromFileEx( pDevice, pContext, pSrcFile, 0, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, bSRGB, + nullptr, ppOutputRV ); } - m_LinesList.Add( pLineNode ); + if ( FAILED(hr) ) + return hr; + + DXUTCache_Texture entry; + wcscpy_s( entry.wszSource, MAX_PATH, pSrcFile ); + entry.bSRGB = bSRGB; + entry.pSRV11 = *ppOutputRV; + entry.pSRV11->AddRef(); + m_TextureCache.push_back( entry ); return S_OK; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::AddRect( int* pnLineID, RECT rc, D3DCOLOR Color, float fWidth, float fScaleRatio, - bool bAntiAlias ) +_Use_decl_annotations_ +HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCSTR pSrcFile, + ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) { - if( fWidth > 2.0f ) - { - D3DXVECTOR2 vertexList[8]; - - vertexList[0].x = ( float )rc.left; - vertexList[0].y = ( float )rc.top - ( fWidth / 2.0f ); - - vertexList[1].x = ( float )rc.left; - vertexList[1].y = ( float )rc.bottom + ( fWidth / 2.0f ); - - vertexList[2].x = ( float )rc.left; - vertexList[2].y = ( float )rc.bottom - 0.5f; - - vertexList[3].x = ( float )rc.right; - vertexList[3].y = ( float )rc.bottom - 0.5f; - - vertexList[4].x = ( float )rc.right; - vertexList[4].y = ( float )rc.bottom + ( fWidth / 2.0f ); - - vertexList[5].x = ( float )rc.right; - vertexList[5].y = ( float )rc.top - ( fWidth / 2.0f ); - - vertexList[6].x = ( float )rc.right; - vertexList[6].y = ( float )rc.top; - - vertexList[7].x = ( float )rc.left; - vertexList[7].y = ( float )rc.top; - - return AddLine( pnLineID, vertexList, 8, Color, fWidth, fScaleRatio, bAntiAlias ); - } - else - { - D3DXVECTOR2 vertexList[5]; - vertexList[0].x = ( float )rc.left; - vertexList[0].y = ( float )rc.top; - - vertexList[1].x = ( float )rc.left; - vertexList[1].y = ( float )rc.bottom; - - vertexList[2].x = ( float )rc.right; - vertexList[2].y = ( float )rc.bottom; - - vertexList[3].x = ( float )rc.right; - vertexList[3].y = ( float )rc.top; - - vertexList[4].x = ( float )rc.left; - vertexList[4].y = ( float )rc.top; + WCHAR szSrcFile[MAX_PATH]; + MultiByteToWideChar( CP_ACP, 0, pSrcFile, -1, szSrcFile, MAX_PATH ); + szSrcFile[MAX_PATH - 1] = 0; - return AddLine( pnLineID, vertexList, 5, Color, fWidth, fScaleRatio, bAntiAlias ); - } + return CreateTextureFromFile( pDevice, pContext, szSrcFile, ppOutputRV, bSRGB ); } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::RemoveLine( int nLineID ) -{ - for( int i = 0; i < m_LinesList.GetSize(); i++ ) - { - LINE_NODE* pLineNode = m_LinesList.GetAt( i ); - if( pLineNode && pLineNode->nLineID == nLineID ) - { - SAFE_DELETE_ARRAY( pLineNode->pVertexList ); - delete pLineNode; - m_LinesList.SetAt( i, NULL ); - } - } - - return S_OK; -} +// Device event callbacks +//-------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::RemoveAllLines() +HRESULT CDXUTResourceCache::OnDestroyDevice() { - for( int i = 0; i < m_LinesList.GetSize(); i++ ) + // Release all resources + for( size_t j = 0; j < m_TextureCache.size(); ++j ) { - LINE_NODE* pLineNode = m_LinesList.GetAt( i ); - if( pLineNode ) - { - SAFE_DELETE_ARRAY( pLineNode->pVertexList ); - delete pLineNode; - } + SAFE_RELEASE( m_TextureCache[ j ].pSRV11 ); } - m_LinesList.RemoveAll(); + m_TextureCache.clear(); + m_TextureCache.shrink_to_fit(); return S_OK; } -//-------------------------------------------------------------------------------------- -CDXUTTextHelper::CDXUTTextHelper( ID3DXFont* pFont9, ID3DXSprite* pSprite9, int nLineHeight ) -{ - Init( pFont9, pSprite9, nLineHeight ); -} +//====================================================================================== +// CDXUTTextHelper +//====================================================================================== -CDXUTTextHelper::CDXUTTextHelper( ID3D11Device* pd3d11Device, ID3D11DeviceContext* pd3d11DeviceContext, CDXUTDialogResourceManager* pManager, int nLineHeight ) +_Use_decl_annotations_ +CDXUTTextHelper::CDXUTTextHelper( ID3D11Device* pd3d11Device, ID3D11DeviceContext* pd3d11DeviceContext, CDXUTDialogResourceManager* pManager, int nLineHeight ) : + m_clr(0, 0, 0, 0), + m_pt{ 0, 0 }, + m_nLineHeight{}, + m_pd3d11Device(nullptr), + m_pd3d11DeviceContext(nullptr), + m_pManager(nullptr) { - Init( NULL, NULL, nLineHeight ); + Init( nLineHeight ); + m_pd3d11Device = pd3d11Device; m_pd3d11DeviceContext = pd3d11DeviceContext; m_pManager = pManager; } + CDXUTTextHelper::~CDXUTTextHelper() { } + //-------------------------------------------------------------------------------------- -void CDXUTTextHelper::Init( ID3DXFont* pFont9, ID3DXSprite* pSprite9, - int nLineHeight ) +void CDXUTTextHelper::Init( _In_ int nLineHeight ) { - m_pFont9 = pFont9; - m_pSprite9 = pSprite9; - m_clr = D3DXCOLOR( 1, 1, 1, 1 ); + m_clr = DirectX::XMFLOAT4( 1, 1, 1, 1 ); m_pt.x = 0; m_pt.y = 0; m_nLineHeight = nLineHeight; - m_pd3d11Device = NULL; - m_pd3d11DeviceContext = NULL; - m_pManager = NULL; + m_pd3d11Device = nullptr; + m_pd3d11DeviceContext = nullptr; + m_pManager = nullptr; // Create a blend state if a sprite is passed in } //-------------------------------------------------------------------------------------- -HRESULT CDXUTTextHelper::DrawFormattedTextLine( const WCHAR* strMsg, ... ) +HRESULT CDXUTTextHelper::DrawFormattedTextLine( _In_z_ const WCHAR* strMsg, ... ) { WCHAR strBuffer[512]; @@ -1629,19 +949,16 @@ HRESULT CDXUTTextHelper::DrawFormattedTextLine( const WCHAR* strMsg, ... ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTTextHelper::DrawTextLine( const WCHAR* strMsg ) +HRESULT CDXUTTextHelper::DrawTextLine( _In_z_ const WCHAR* strMsg ) { - if( NULL == m_pFont9 && NULL == m_pd3d11DeviceContext ) + if( !m_pd3d11DeviceContext ) return DXUT_ERR_MSGBOX( L"DrawTextLine", E_INVALIDARG ); HRESULT hr = S_OK; RECT rc; SetRect( &rc, m_pt.x, m_pt.y, 0, 0 ); - if( m_pFont9 ) - hr = m_pFont9->DrawText( m_pSprite9, strMsg, -1, &rc, DT_NOCLIP, m_clr ); - else if( m_pd3d11DeviceContext ) - DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, - (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); + DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, + (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); if( FAILED( hr ) ) return DXTRACE_ERR_MSGBOX( L"DrawText", hr ); @@ -1652,7 +969,9 @@ HRESULT CDXUTTextHelper::DrawTextLine( const WCHAR* strMsg ) } -HRESULT CDXUTTextHelper::DrawFormattedTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg, ... ) +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTTextHelper::DrawFormattedTextLine( const RECT& rc, const WCHAR* strMsg, ... ) { WCHAR strBuffer[512]; @@ -1662,21 +981,20 @@ HRESULT CDXUTTextHelper::DrawFormattedTextLine( RECT& rc, DWORD dwFlags, const W strBuffer[511] = L'\0'; va_end( args ); - return DrawTextLine( rc, dwFlags, strBuffer ); + return DrawTextLine( rc, strBuffer ); } -HRESULT CDXUTTextHelper::DrawTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg ) +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTTextHelper::DrawTextLine( const RECT& rc, const WCHAR* strMsg ) { - if( NULL == m_pFont9 && NULL == m_pd3d11DeviceContext ) + if( !m_pd3d11DeviceContext ) return DXUT_ERR_MSGBOX( L"DrawTextLine", E_INVALIDARG ); HRESULT hr = S_OK; - if( m_pFont9 ) - hr = m_pFont9->DrawText( m_pSprite9, strMsg, -1, &rc, dwFlags, m_clr ); - else if( m_pd3d11DeviceContext ) - DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, - (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); + DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, + (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); if( FAILED( hr ) ) return DXTRACE_ERR_MSGBOX( L"DrawText", hr ); @@ -1690,9 +1008,6 @@ HRESULT CDXUTTextHelper::DrawTextLine( RECT& rc, DWORD dwFlags, const WCHAR* str //-------------------------------------------------------------------------------------- void CDXUTTextHelper::Begin() { - if( m_pSprite9 ) - m_pSprite9->Begin( D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE ); - if( m_pd3d11DeviceContext ) { m_pManager->StoreD3D11State( m_pd3d11DeviceContext ); @@ -1701,11 +1016,11 @@ void CDXUTTextHelper::Begin() } + + +//-------------------------------------------------------------------------------------- void CDXUTTextHelper::End() { - if( m_pSprite9 ) - m_pSprite9->End(); - if( m_pd3d11DeviceContext ) { m_pManager->RestoreD3D11State( m_pd3d11DeviceContext ); diff --git a/FriedLiver/Source/DXUT/Optional/SDKmisc.h b/FriedLiver/Source/DXUT/Optional/SDKmisc.h index ec7de8e0..37814043 100644 --- a/FriedLiver/Source/DXUT/Optional/SDKmisc.h +++ b/FriedLiver/Source/DXUT/Optional/SDKmisc.h @@ -3,159 +3,44 @@ // // Various helper functionality that is shared between SDK samples // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef SDKMISC_H -#define SDKMISC_H - //----------------------------------------------------------------------------- // Resource cache for textures, fonts, meshs, and effects. // Use DXUTGetGlobalResourceCache() to access the global cache //----------------------------------------------------------------------------- -enum DXUTCACHE_SOURCELOCATION -{ - DXUTCACHE_LOCATION_FILE, - DXUTCACHE_LOCATION_RESOURCE -}; - struct DXUTCache_Texture { - DXUTCACHE_SOURCELOCATION Location; WCHAR wszSource[MAX_PATH]; - HMODULE hSrcModule; - UINT Width; - UINT Height; - UINT Depth; - UINT MipLevels; - UINT MiscFlags; - union - { - DWORD Usage9; - D3D11_USAGE Usage11; - }; - union - { - D3DFORMAT Format9; - DXGI_FORMAT Format; - }; - union - { - D3DPOOL Pool9; - UINT CpuAccessFlags; - }; - union - { - D3DRESOURCETYPE Type9; - UINT BindFlags; - }; - IDirect3DBaseTexture9* pTexture9; + bool bSRGB; ID3D11ShaderResourceView* pSRV11; - DXUTCache_Texture() - { - pTexture9 = NULL; - pSRV11 = NULL; - } -}; - -struct DXUTCache_Font : public D3DXFONT_DESC -{ - ID3DXFont* pFont; -}; - -struct DXUTCache_Effect -{ - DXUTCACHE_SOURCELOCATION Location; - WCHAR wszSource[MAX_PATH]; - HMODULE hSrcModule; - DWORD dwFlags; - ID3DXEffect* pEffect; + DXUTCache_Texture() noexcept : + wszSource{}, + bSRGB(false), + pSRV11(nullptr) + { + } }; class CDXUTResourceCache { public: - ~CDXUTResourceCache(); - - HRESULT CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ); - HRESULT CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ); - HRESULT CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCTSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB=false ); - HRESULT CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB=false ); - HRESULT CreateTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Width, - UINT Height, UINT MipLevels, DWORD Usage, D3DFORMAT Format, - D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DTEXTURE9* ppTexture ); - HRESULT CreateTextureFromFileEx( ID3D11Device* pDevice, ID3D11DeviceContext* pContext, LPCTSTR pSrcFile, - D3DX11_IMAGE_LOAD_INFO* pLoadInfo, ID3DX11ThreadPump* pPump, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ); - HRESULT CreateTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, LPDIRECT3DTEXTURE9* ppTexture ); - HRESULT CreateTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, UINT Width, UINT Height, UINT MipLevels, - DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO* pSrcInfo, - PALETTEENTRY* pPalette, LPDIRECT3DTEXTURE9* ppTexture ); - HRESULT CreateCubeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ); - HRESULT CreateCubeTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Size, - UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, - DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ); - HRESULT CreateCubeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ); - HRESULT CreateCubeTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, UINT Size, UINT MipLevels, - DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ); - HRESULT CreateVolumeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ); - HRESULT CreateVolumeTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Width, - UINT Height, UINT Depth, UINT MipLevels, DWORD Usage, - D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DVOLUMETEXTURE9* ppTexture ); - HRESULT CreateVolumeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ); - HRESULT CreateVolumeTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, UINT Width, UINT Height, - UINT Depth, UINT MipLevels, DWORD Usage, - D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, - DWORD MipFilter, D3DCOLOR ColorKey, - D3DXIMAGE_INFO* pSrcInfo, PALETTEENTRY* pPalette, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ); - HRESULT CreateFont( LPDIRECT3DDEVICE9 pDevice, UINT Height, UINT Width, UINT Weight, - UINT MipLevels, BOOL Italic, DWORD CharSet, DWORD OutputPrecision, - DWORD Quality, DWORD PitchAndFamily, LPCTSTR pFacename, LPD3DXFONT* ppFont ); - HRESULT CreateFontIndirect( LPDIRECT3DDEVICE9 pDevice, CONST D3DXFONT_DESC *pDesc, LPD3DXFONT *ppFont ); - HRESULT CreateEffectFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - const D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, DWORD Flags, - LPD3DXEFFECTPOOL pPool, LPD3DXEFFECT* ppEffect, - LPD3DXBUFFER* ppCompilationErrors ); - HRESULT CreateEffectFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, const D3DXMACRO* pDefines, - LPD3DXINCLUDE pInclude, DWORD Flags, LPD3DXEFFECTPOOL pPool, - LPD3DXEFFECT* ppEffect, LPD3DXBUFFER* ppCompilationErrors ); + ~CDXUTResourceCache(); + HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCWSTR pSrcFile, + _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false ); + HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCSTR pSrcFile, + _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false ); public: - HRESULT OnCreateDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnResetDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnLostDevice(); - HRESULT OnDestroyDevice(); + HRESULT OnDestroyDevice(); protected: friend CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache(); @@ -163,15 +48,11 @@ class CDXUTResourceCache friend HRESULT WINAPI DXUTReset3DEnvironment(); friend void WINAPI DXUTCleanup3DEnvironment( bool bReleaseSettings ); - CDXUTResourceCache() - { - } + CDXUTResourceCache() = default; - CGrowableArray m_TextureCache; - CGrowableArray m_EffectCache; - CGrowableArray m_FontCache; + std::vector m_TextureCache; }; - + CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache(); @@ -182,187 +63,70 @@ class CDXUTDialogResourceManager; class CDXUTTextHelper { public: - CDXUTTextHelper( ID3DXFont* pFont9 = NULL, ID3DXSprite* pSprite9 = NULL, - int nLineHeight = 15 ); - CDXUTTextHelper( ID3D11Device* pd3d11Device, ID3D11DeviceContext* pd3dDeviceContext, CDXUTDialogResourceManager* pManager, int nLineHeight ); - ~CDXUTTextHelper(); + CDXUTTextHelper( _In_ ID3D11Device* pd3d11Device, _In_ ID3D11DeviceContext* pd3dDeviceContext, _In_ CDXUTDialogResourceManager* pManager, _In_ int nLineHeight ); + ~CDXUTTextHelper(); - void Init( ID3DXFont* pFont9 = NULL, ID3DXSprite* pSprite9 = NULL, - int nLineHeight = 15 ); + void Init( _In_ int nLineHeight = 15 ); - void SetInsertionPos( int x, int y ) - { - m_pt.x = x; m_pt.y = y; - } - void SetForegroundColor( D3DXCOLOR clr ) + void SetInsertionPos( _In_ int x, _In_ int y ) { - m_clr = clr; + m_pt.x = x; + m_pt.y = y; } + void SetForegroundColor( _In_ DirectX::XMFLOAT4 clr ) { m_clr = clr; } + void SetForegroundColor( _In_ DirectX::FXMVECTOR clr ) { XMStoreFloat4( &m_clr, clr ); } void Begin(); - HRESULT DrawFormattedTextLine( const WCHAR* strMsg, ... ); - HRESULT DrawTextLine( const WCHAR* strMsg ); - HRESULT DrawFormattedTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg, ... ); - HRESULT DrawTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg ); + HRESULT DrawFormattedTextLine( _In_z_ const WCHAR* strMsg, ... ); + HRESULT DrawTextLine( _In_z_ const WCHAR* strMsg ); + HRESULT DrawFormattedTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg, ... ); + HRESULT DrawTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg ); void End(); protected: - ID3DXFont* m_pFont9; - ID3DXSprite* m_pSprite9; - D3DXCOLOR m_clr; + DirectX::XMFLOAT4 m_clr; POINT m_pt; int m_nLineHeight; - // D3D11 font - ID3D11Device* m_pd3d11Device; - ID3D11DeviceContext* m_pd3d11DeviceContext; - CDXUTDialogResourceManager* m_pManager; -}; - - -//-------------------------------------------------------------------------------------- -// Manages a persistent list of lines and draws them using ID3DXLine -//-------------------------------------------------------------------------------------- -class CDXUTLineManager -{ -public: - CDXUTLineManager(); - ~CDXUTLineManager(); - - HRESULT OnCreatedDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnResetDevice(); - HRESULT OnRender(); - HRESULT OnLostDevice(); - HRESULT OnDeletedDevice(); - - HRESULT AddLine( int* pnLineID, D3DXVECTOR2* pVertexList, DWORD dwVertexListCount, D3DCOLOR Color, float fWidth, - float fScaleRatio, bool bAntiAlias ); - HRESULT AddRect( int* pnLineID, RECT rc, D3DCOLOR Color, float fWidth, float fScaleRatio, bool bAntiAlias ); - HRESULT RemoveLine( int nLineID ); - HRESULT RemoveAllLines(); - -protected: - struct LINE_NODE - { - int nLineID; - D3DCOLOR Color; - float fWidth; - bool bAntiAlias; - float fScaleRatio; - D3DXVECTOR2* pVertexList; - DWORD dwVertexListCount; - }; - - CGrowableArray m_LinesList; - IDirect3DDevice9* m_pd3dDevice; - ID3DXLine* m_pD3DXLine; + // D3D11 font + ID3D11Device* m_pd3d11Device; + ID3D11DeviceContext* m_pd3d11DeviceContext; + CDXUTDialogResourceManager* m_pManager; }; //-------------------------------------------------------------------------------------- // Shared code for samples to ask user if they want to use a REF device or quit //-------------------------------------------------------------------------------------- -void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ); +void WINAPI DXUTDisplaySwitchingToREFWarning(); //-------------------------------------------------------------------------------------- // Tries to finds a media file by searching in common locations //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTFindDXSDKMediaFileCch( __out_ecount(cchDest) WCHAR* strDestPath, - __in int cchDest, - __in LPCWSTR strFilename ); -HRESULT WINAPI DXUTSetMediaSearchPath( LPCWSTR strPath ); +HRESULT WINAPI DXUTFindDXSDKMediaFileCch( _Out_writes_(cchDest) WCHAR* strDestPath, + _In_ int cchDest, + _In_z_ LPCWSTR strFilename ); +HRESULT WINAPI DXUTSetMediaSearchPath( _In_z_ LPCWSTR strPath ); LPCWSTR WINAPI DXUTGetMediaSearchPath(); //-------------------------------------------------------------------------------------- -// Returns a view matrix for rendering to a face of a cubemap. +// Compiles HLSL shaders //-------------------------------------------------------------------------------------- -D3DXMATRIX WINAPI DXUTGetCubeMapViewMatrix( DWORD dwFace ); - +HRESULT WINAPI DXUTCompileFromFile( _In_z_ LPCWSTR pFileName, + _In_reads_opt_(_Inexpressible_(pDefines->Name != NULL)) const D3D_SHADER_MACRO* pDefines, + _In_z_ LPCSTR pEntrypoint, _In_z_ LPCSTR pTarget, + _In_ UINT Flags1, _In_ UINT Flags2, + _Outptr_ ID3DBlob** ppCode ); //-------------------------------------------------------------------------------------- -// Simple helper stack class +// Texture utilities //-------------------------------------------------------------------------------------- -template class CDXUTStack -{ -private: - UINT m_MemorySize; - UINT m_NumElements; - T* m_pData; - - bool EnsureStackSize( UINT64 iElements ) - { - if( m_MemorySize > iElements ) - return true; - - T* pTemp = new T[ ( size_t )( iElements * 2 + 256 ) ]; - if( !pTemp ) - return false; - - if( m_NumElements ) - { - CopyMemory( pTemp, m_pData, ( size_t )( m_NumElements * sizeof( T ) ) ); - } - - if( m_pData ) delete []m_pData; - m_pData = pTemp; - return true; - } - -public: - CDXUTStack() - { - m_pData = NULL; m_NumElements = 0; m_MemorySize = 0; - } - ~CDXUTStack() - { - if( m_pData ) delete []m_pData; - } - - UINT GetCount() - { - return m_NumElements; - } - T GetAt( UINT i ) - { - return m_pData[i]; - } - T GetTop() - { - if( m_NumElements < 1 ) - return NULL; - - return m_pData[ m_NumElements - 1 ]; - } +HRESULT WINAPI DXUTCreateShaderResourceViewFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11ShaderResourceView** textureView ); +HRESULT WINAPI DXUTCreateTextureFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11Resource** texture ); +HRESULT WINAPI DXUTSaveTextureToFile( _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _In_ bool usedds, _In_z_ const wchar_t* szFileName ); - T GetRelative( INT i ) - { - INT64 iVal = m_NumElements - 1 + i; - if( iVal < 0 ) - return NULL; - return m_pData[ iVal ]; - } - - bool Push( T pElem ) - { - if( !EnsureStackSize( m_NumElements + 1 ) ) - return false; - - m_pData[m_NumElements] = pElem; - m_NumElements++; - - return true; - } - - T Pop() - { - if( m_NumElements < 1 ) - return NULL; - - m_NumElements --; - return m_pData[m_NumElements]; - } -}; - - -#endif +//-------------------------------------------------------------------------------------- +// Returns a view matrix for rendering to a face of a cubemap. +//-------------------------------------------------------------------------------------- +DirectX::XMMATRIX WINAPI DXUTGetCubeMapViewMatrix( _In_ DWORD dwFace ); diff --git a/FriedLiver/Source/DXUT/Optional/directx.ico b/FriedLiver/Source/DXUT/Optional/directx.ico new file mode 100644 index 00000000..bc43c1b2 Binary files /dev/null and b/FriedLiver/Source/DXUT/Optional/directx.ico differ diff --git a/FriedLiver/Source/DepthSensing/DX11PhongLighting.cpp b/FriedLiver/Source/DepthSensing/DX11PhongLighting.cpp index ac38a2b5..683cb28b 100644 --- a/FriedLiver/Source/DepthSensing/DX11PhongLighting.cpp +++ b/FriedLiver/Source/DepthSensing/DX11PhongLighting.cpp @@ -207,7 +207,7 @@ void DX11PhongLighting::render(ID3D11DeviceContext* pd3dDeviceContext, ID3D11Sha if(FAILED(hr)) return; cbConstant *cbufferConstant = (cbConstant*)mappedResource.pData; cbufferConstant->useMaterial = useMaterial ? 1 : 0; - cbufferConstant->overlayColor = D3DXVECTOR3(overlayColor.x, overlayColor.y, overlayColor.z); + cbufferConstant->overlayColor = DirectX::XMFLOAT3(overlayColor.x, overlayColor.y, overlayColor.z); pd3dDeviceContext->Unmap(s_ConstantBuffer, 0); // copy lightbuffer to gpu diff --git a/FriedLiver/Source/DepthSensing/DX11PhongLighting.h b/FriedLiver/Source/DepthSensing/DX11PhongLighting.h index 7f82e19f..3dcb56bd 100644 --- a/FriedLiver/Source/DepthSensing/DX11PhongLighting.h +++ b/FriedLiver/Source/DepthSensing/DX11PhongLighting.h @@ -10,28 +10,28 @@ class DX11PhongLighting struct ConstantBufferLight : ConstantBufferBase { - D3DXVECTOR4 lightAmbient; - D3DXVECTOR4 lightDiffuse; - D3DXVECTOR4 lightSpecular; + DirectX::XMFLOAT4 lightAmbient; + DirectX::XMFLOAT4 lightDiffuse; + DirectX::XMFLOAT4 lightSpecular; - D3DXVECTOR3 lightDirection; + DirectX::XMFLOAT3 lightDirection; float materialShininess; - D3DXVECTOR4 materialAmbient; - D3DXVECTOR4 materialSpecular; - D3DXVECTOR4 materialDiffuse; + DirectX::XMFLOAT4 materialAmbient; + DirectX::XMFLOAT4 materialSpecular; + DirectX::XMFLOAT4 materialDiffuse; void SetDefault() { // default light settings - lightAmbient = D3DXVECTOR4(GlobalAppState::get().s_lightAmbient.getData()); - lightDiffuse = D3DXVECTOR4(GlobalAppState::get().s_lightDiffuse.getData()); - lightSpecular = D3DXVECTOR4(GlobalAppState::get().s_lightSpecular.getData()); - lightDirection = D3DXVECTOR3(GlobalAppState::get().s_lightDirection.getData()); + lightAmbient = DirectX::XMFLOAT4(GlobalAppState::get().s_lightAmbient.getData()); + lightDiffuse = DirectX::XMFLOAT4(GlobalAppState::get().s_lightDiffuse.getData()); + lightSpecular = DirectX::XMFLOAT4(GlobalAppState::get().s_lightSpecular.getData()); + lightDirection = DirectX::XMFLOAT3(GlobalAppState::get().s_lightDirection.getData()); - materialAmbient = D3DXVECTOR4(GlobalAppState::get().s_materialAmbient.getData()); - materialSpecular = D3DXVECTOR4(GlobalAppState::get().s_materialSpecular.getData()); - materialDiffuse = D3DXVECTOR4(GlobalAppState::get().s_materialDiffuse.getData()); + materialAmbient = DirectX::XMFLOAT4(GlobalAppState::get().s_materialAmbient.getData()); + materialSpecular = DirectX::XMFLOAT4(GlobalAppState::get().s_materialSpecular.getData()); + materialDiffuse = DirectX::XMFLOAT4(GlobalAppState::get().s_materialDiffuse.getData()); materialShininess = GlobalAppState::get().s_materialShininess; } }; @@ -71,7 +71,7 @@ class DX11PhongLighting struct cbConstant { unsigned int useMaterial; - D3DXVECTOR3 overlayColor; + DirectX::XMFLOAT3 overlayColor; }; static ID3D11Buffer* s_ConstantBuffer; diff --git a/FriedLiver/Source/DepthSensing/DX11QuadDrawer.cpp b/FriedLiver/Source/DepthSensing/DX11QuadDrawer.cpp index b850a47d..c9d3320e 100644 --- a/FriedLiver/Source/DepthSensing/DX11QuadDrawer.cpp +++ b/FriedLiver/Source/DepthSensing/DX11QuadDrawer.cpp @@ -105,10 +105,10 @@ HRESULT DX11QuadDrawer::OnD3D11CreateDevice( ID3D11Device* pd3dDevice ) SimpleVertex vertices[] = { - { D3DXVECTOR3( -1.0f, -1.0f, 0.0f ), D3DXVECTOR2( 0.0f, 1.0f ) }, - { D3DXVECTOR3( 1.0f, -1.0f, 0.0f ), D3DXVECTOR2( 1.0f, 1.0f ) }, - { D3DXVECTOR3( 1.0f, 1.0f, 0.0f ), D3DXVECTOR2( 1.0f, 0.0f ) }, - { D3DXVECTOR3( -1.0f, 1.0f, 0.0f ), D3DXVECTOR2( 0.0f, 0.0f ) } + { DirectX::XMFLOAT3( -1.0f, -1.0f, 0.0f ), DirectX::XMFLOAT2( 0.0f, 1.0f ) }, + { DirectX::XMFLOAT3( 1.0f, -1.0f, 0.0f ), DirectX::XMFLOAT2( 1.0f, 1.0f ) }, + { DirectX::XMFLOAT3( 1.0f, 1.0f, 0.0f ), DirectX::XMFLOAT2( 1.0f, 0.0f ) }, + { DirectX::XMFLOAT3( -1.0f, 1.0f, 0.0f ), DirectX::XMFLOAT2( 0.0f, 0.0f ) } }; D3D11_BUFFER_DESC desc; @@ -262,7 +262,7 @@ void DX11QuadDrawer::OnD3D11DestroyDevice() cutilSafeCall(cudaGraphicsUnregisterResource(s_dCuda2)); } -HRESULT DX11QuadDrawer::RenderQuadDynamicDEPTHasHSV(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const float* d_data, float minDepth, float maxDepth, unsigned int width, unsigned int height, float scale /*= 1.0f*/, D3DXVECTOR2 Pow2Ratios /*= D3DXVECTOR2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) +HRESULT DX11QuadDrawer::RenderQuadDynamicDEPTHasHSV(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const float* d_data, float minDepth, float maxDepth, unsigned int width, unsigned int height, float scale /*= 1.0f*/, DirectX::XMFLOAT2 Pow2Ratios /*= DirectX::XMFLOAT2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) { //TODO this function is not very efficient... float4* d_dataFloat4; @@ -274,7 +274,7 @@ HRESULT DX11QuadDrawer::RenderQuadDynamicDEPTHasHSV(ID3D11Device* pd3dDevice, ID } -HRESULT DX11QuadDrawer::RenderQuadDynamicUCHAR4(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const uchar4* d_data, unsigned int width, unsigned int height, float scale /*= 1.0f*/, D3DXVECTOR2 Pow2Ratios /*= D3DXVECTOR2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) +HRESULT DX11QuadDrawer::RenderQuadDynamicUCHAR4(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const uchar4* d_data, unsigned int width, unsigned int height, float scale /*= 1.0f*/, DirectX::XMFLOAT2 Pow2Ratios /*= DirectX::XMFLOAT2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) { //TODO this function is not very efficient... float4* d_dataFloat4; @@ -286,7 +286,7 @@ HRESULT DX11QuadDrawer::RenderQuadDynamicUCHAR4(ID3D11Device* pd3dDevice, ID3D11 } -HRESULT DX11QuadDrawer::RenderQuadDynamic(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale /*= 1.0f */, D3DXVECTOR2 Pow2Ratios /*= D3DXVECTOR2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) +HRESULT DX11QuadDrawer::RenderQuadDynamic(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale /*= 1.0f */, DirectX::XMFLOAT2 Pow2Ratios /*= DirectX::XMFLOAT2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) { HRESULT hr = S_OK; @@ -329,7 +329,7 @@ HRESULT DX11QuadDrawer::RenderQuadDynamic(ID3D11Device* pd3dDevice, ID3D11Device return hr; } -void DX11QuadDrawer::RenderQuadHelper(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, cudaGraphicsResource* pCuda, ID3D11ShaderResourceView* pTmpTextureSRV, unsigned int size, float scale, D3DXVECTOR2 Pow2Ratios , ID3D11PixelShader* pixelShader) +void DX11QuadDrawer::RenderQuadHelper(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, cudaGraphicsResource* pCuda, ID3D11ShaderResourceView* pTmpTextureSRV, unsigned int size, float scale, DirectX::XMFLOAT2 Pow2Ratios , ID3D11PixelShader* pixelShader) { cudaArray* in_array; cutilSafeCall(cudaGraphicsMapResources(1, &pCuda, 0)); // Map DX texture to Cuda @@ -339,7 +339,7 @@ void DX11QuadDrawer::RenderQuadHelper(ID3D11DeviceContext* pd3dDeviceContext, fl RenderQuad(pd3dDeviceContext, pTmpTextureSRV, scale, Pow2Ratios, pixelShader); } -void DX11QuadDrawer::RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale /*= 1.0f */, D3DXVECTOR2 Pow2Ratios /*= float2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) +void DX11QuadDrawer::RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale /*= 1.0f */, DirectX::XMFLOAT2 Pow2Ratios /*= float2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) { if(nChannels == 4) { @@ -359,7 +359,7 @@ void DX11QuadDrawer::RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, float* d } } -void DX11QuadDrawer::RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, ID3D11ShaderResourceView* srv, float scale /*= 1.0f */, D3DXVECTOR2 Pow2Ratios /*= float2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) +void DX11QuadDrawer::RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, ID3D11ShaderResourceView* srv, float scale /*= 1.0f */, DirectX::XMFLOAT2 Pow2Ratios /*= float2(1.0f, 1.0f)*/, ID3D11PixelShader* pixelShader /*= NULL*/) { D3D11_MAPPED_SUBRESOURCE MappedResource; pd3dDeviceContext->Map( s_pcbVSPowTwoRatios, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ); @@ -412,7 +412,7 @@ void DX11QuadDrawer::RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, ID3D11Sh pd3dDeviceContext->PSSetShaderResources(10, 1, srvNULL); } -void DX11QuadDrawer::RenderQuad( ID3D11DeviceContext* pd3dDeviceContext, ID3D11PixelShader* pixelShader, ID3D11ShaderResourceView** srvs, UINT numShaderResourceViews, D3DXVECTOR2 Pow2Ratios /*= float2(1.0f, 1.0f)*/ ) +void DX11QuadDrawer::RenderQuad( ID3D11DeviceContext* pd3dDeviceContext, ID3D11PixelShader* pixelShader, ID3D11ShaderResourceView** srvs, UINT numShaderResourceViews, DirectX::XMFLOAT2 Pow2Ratios /*= float2(1.0f, 1.0f)*/ ) { D3D11_MAPPED_SUBRESOURCE MappedResource; pd3dDeviceContext->Map( s_pcbVSPowTwoRatios, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ); diff --git a/FriedLiver/Source/DepthSensing/DX11QuadDrawer.h b/FriedLiver/Source/DepthSensing/DX11QuadDrawer.h index 8c038e3f..5e46845a 100644 --- a/FriedLiver/Source/DepthSensing/DX11QuadDrawer.h +++ b/FriedLiver/Source/DepthSensing/DX11QuadDrawer.h @@ -7,15 +7,15 @@ #include struct SimpleVertex { - D3DXVECTOR3 pos; - D3DXVECTOR2 pex; + DirectX::XMFLOAT3 pos; + DirectX::XMFLOAT2 pex; }; struct CB_QUAD { - D3DXMATRIX mWorldViewProjection; + DirectX::XMFLOAT4X4 mWorldViewProjection; UINT width; UINT height; - D3DXVECTOR2 dummy; + DirectX::XMFLOAT2 dummy; }; class DX11QuadDrawer @@ -27,17 +27,17 @@ class DX11QuadDrawer static HRESULT OnD3D11CreateDevice(ID3D11Device* pd3dDevice); static void OnD3D11DestroyDevice(); - static HRESULT RenderQuadDynamicDEPTHasHSV(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const float* d_data, float minDepth, float maxDepth, unsigned int width, unsigned int height, float scale = 1.0f, D3DXVECTOR2 Pow2Ratios = D3DXVECTOR2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); - static HRESULT RenderQuadDynamicUCHAR4(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const uchar4* d_data, unsigned int width, unsigned int height, float scale = 1.0f, D3DXVECTOR2 Pow2Ratios = D3DXVECTOR2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); - static HRESULT RenderQuadDynamic(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale = 1.0f, D3DXVECTOR2 Pow2Ratios = D3DXVECTOR2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); + static HRESULT RenderQuadDynamicDEPTHasHSV(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const float* d_data, float minDepth, float maxDepth, unsigned int width, unsigned int height, float scale = 1.0f, DirectX::XMFLOAT2 Pow2Ratios = DirectX::XMFLOAT2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); + static HRESULT RenderQuadDynamicUCHAR4(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, const uchar4* d_data, unsigned int width, unsigned int height, float scale = 1.0f, DirectX::XMFLOAT2 Pow2Ratios = DirectX::XMFLOAT2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); + static HRESULT RenderQuadDynamic(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale = 1.0f, DirectX::XMFLOAT2 Pow2Ratios = DirectX::XMFLOAT2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); - static void RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale = 1.0f , D3DXVECTOR2 Pow2Ratios = D3DXVECTOR2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL ); - static void RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, ID3D11PixelShader* pixelShader, ID3D11ShaderResourceView** srvs, UINT numShaderResourceViews, D3DXVECTOR2 Pow2Ratios = D3DXVECTOR2(1.0f, 1.0f)); - static void RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, ID3D11ShaderResourceView* srv, float scale = 1.0f, D3DXVECTOR2 Pow2Ratios = D3DXVECTOR2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); + static void RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, unsigned int nChannels, unsigned int width, unsigned int height, float scale = 1.0f , DirectX::XMFLOAT2 Pow2Ratios = DirectX::XMFLOAT2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL ); + static void RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, ID3D11PixelShader* pixelShader, ID3D11ShaderResourceView** srvs, UINT numShaderResourceViews, DirectX::XMFLOAT2 Pow2Ratios = DirectX::XMFLOAT2(1.0f, 1.0f)); + static void RenderQuad(ID3D11DeviceContext* pd3dDeviceContext, ID3D11ShaderResourceView* srv, float scale = 1.0f, DirectX::XMFLOAT2 Pow2Ratios = DirectX::XMFLOAT2(1.0f, 1.0f), ID3D11PixelShader* pixelShader = NULL); private: - static void RenderQuadHelper(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, cudaGraphicsResource* pCuda, ID3D11ShaderResourceView* pTmpTextureSRV, unsigned int size, float scale, D3DXVECTOR2 Pow2Ratios , ID3D11PixelShader* pixelShader); + static void RenderQuadHelper(ID3D11DeviceContext* pd3dDeviceContext, float* d_data, cudaGraphicsResource* pCuda, ID3D11ShaderResourceView* pTmpTextureSRV, unsigned int size, float scale, DirectX::XMFLOAT2 Pow2Ratios , ID3D11PixelShader* pixelShader); static ID3D11InputLayout* s_VertexLayout; static ID3D11Buffer* s_VertexBuffer; diff --git a/FriedLiver/Source/DepthSensing/DX11RGBDRenderer.h b/FriedLiver/Source/DepthSensing/DX11RGBDRenderer.h index b09b1e7a..b9568602 100644 --- a/FriedLiver/Source/DepthSensing/DX11RGBDRenderer.h +++ b/FriedLiver/Source/DepthSensing/DX11RGBDRenderer.h @@ -10,10 +10,10 @@ struct CB_RGBDRenderer { - D3DXMATRIX m_mIntrinsicInverse; - D3DXMATRIX m_mExtrinsic; //model-view - D3DXMATRIX m_mIntrinsicNew; //for 'real-world' depth range - D3DXMATRIX m_mProjection; //for graphics rendering + DirectX::XMFLOAT4X4 m_mIntrinsicInverse; + DirectX::XMFLOAT4X4 m_mExtrinsic; //model-view + DirectX::XMFLOAT4X4 m_mIntrinsicNew; //for 'real-world' depth range + DirectX::XMFLOAT4X4 m_mProjection; //for graphics rendering unsigned int m_uScreenWidth; unsigned int m_uScreenHeight; diff --git a/FriedLiver/Source/DepthSensing/DX11Utils.cpp b/FriedLiver/Source/DepthSensing/DX11Utils.cpp index a746409f..26beaad7 100644 --- a/FriedLiver/Source/DepthSensing/DX11Utils.cpp +++ b/FriedLiver/Source/DepthSensing/DX11Utils.cpp @@ -170,8 +170,8 @@ HRESULT CompileShaderFromFile( WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR sz dwShaderFlags |= pCompilerFlags; ID3DBlob* pErrorBlob; - hr = D3DX11CompileFromFile( str, pDefines, NULL, szEntryPoint, szShaderModel, - dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL ); + hr = D3DCompileFromFile( str, pDefines, NULL, szEntryPoint, szShaderModel, + dwShaderFlags, 0, ppBlobOut, &pErrorBlob); if( FAILED(hr) ) { if( pErrorBlob != NULL ) @@ -386,7 +386,7 @@ void LoadCamera( CModelViewerCamera &camera, const char* filename ) std::ifstream file; file.open(filename); if (file.is_open() && file.good()) { - D3DXVECTOR3 eye, lookAt; + DirectX::XMFLOAT3 eye, lookAt; D3DXQUATERNION world, view; file >> eye.x >> eye.y >> eye.z; diff --git a/FriedLiver/Source/DepthSensing/DepthSensing.cpp b/FriedLiver/Source/DepthSensing/DepthSensing.cpp index f9b71dd5..eccf4554 100644 --- a/FriedLiver/Source/DepthSensing/DepthSensing.cpp +++ b/FriedLiver/Source/DepthSensing/DepthSensing.cpp @@ -8,7 +8,8 @@ #include #include -#include +#include +#include #include "DX11Utils.h" #include "GlobalAppState.h" @@ -134,7 +135,7 @@ int startDepthSensing(OnlineBundler* bundler, RGBDSensor* sensor, CUDAImageManag DXUTInit(true, true); // Parse the command line, show msgboxes on error, and an extra cmd line param to force REF for now DXUTSetCursorSettings(true, true); // Show the cursor and clip it when in full screen - DXUTCreateWindow(GlobalAppState::get().s_windowWidth, GlobalAppState::get().s_windowHeight, L"Fried Liver", false); + DXUTCreateWindow(L"Fried Liver", NULL, NULL, NULL, GlobalAppState::get().s_windowWidth, GlobalAppState::get().s_windowHeight); DXUTSetIsInGammaCorrectMode(false); //gamma fix (for kinect color) @@ -155,11 +156,9 @@ bool CALLBACK ModifyDeviceSettings(DXUTDeviceSettings* pDeviceSettings, void* pU if (s_bFirstTime) { s_bFirstTime = false; - if ((DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF) || - (DXUT_D3D11_DEVICE == pDeviceSettings->ver && - pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE)) + if (pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE) { - DXUTDisplaySwitchingToREFWarning(pDeviceSettings->ver); + DXUTDisplaySwitchingToREFWarning(); } } @@ -182,11 +181,11 @@ void RenderText() { g_pTxtHelper->Begin(); g_pTxtHelper->SetInsertionPos(2, 0); - g_pTxtHelper->SetForegroundColor(D3DXCOLOR(1.0f, 1.0f, 0.0f, 1.0f)); + g_pTxtHelper->SetForegroundColor(DirectX::XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f)); g_pTxtHelper->DrawTextLine(DXUTGetFrameStats(DXUTIsVsyncEnabled())); g_pTxtHelper->DrawTextLine(DXUTGetDeviceStats()); if (!g_bRenderHelp) { - g_pTxtHelper->SetForegroundColor(D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f)); + g_pTxtHelper->SetForegroundColor(DirectX::XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)); g_pTxtHelper->DrawTextLine(L"\tPress F1 for help"); } g_pTxtHelper->End(); @@ -201,7 +200,7 @@ void RenderHelp() { g_pTxtHelper->Begin(); g_pTxtHelper->SetInsertionPos(2, 40); - g_pTxtHelper->SetForegroundColor(D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)); + g_pTxtHelper->SetForegroundColor(DirectX::XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)); g_pTxtHelper->DrawTextLine(L"Controls "); g_pTxtHelper->DrawTextLine(L" \tF1:\t Hide help"); g_pTxtHelper->DrawTextLine(L" \tF2:\t Screenshot"); @@ -441,7 +440,7 @@ void CALLBACK OnKeyboard(UINT nChar, bool bKeyDown, bool bAltDown, void* pUserCo break; case VK_F2: swprintf_s(sz, 200, L"screenshot%d.bmp", whichScreenshot++); - DXUTSnapD3D11Screenshot(sz, D3DX11_IFF_BMP); + DXUTSnapD3D11Screenshot(sz, false); std::wcout << std::wstring(sz) << std::endl; break; case '\t': @@ -606,9 +605,9 @@ HRESULT CALLBACK OnD3D11CreateDevice(ID3D11Device* pd3dDevice, const DXGI_SURFAC V_RETURN(g_RGBDRenderer.OnD3D11CreateDevice(pd3dDevice, GlobalAppState::get().s_rayCastWidth, GlobalAppState::get().s_rayCastHeight)); V_RETURN(g_CustomRenderTarget.OnD3D11CreateDevice(pd3dDevice, GlobalAppState::get().s_rayCastWidth, GlobalAppState::get().s_rayCastHeight, formats)); - D3DXVECTOR3 vecEye(0.0f, 0.0f, 0.0f); - D3DXVECTOR3 vecAt(0.0f, 0.0f, 1.0f); - g_Camera.SetViewParams(&vecEye, &vecAt); + DirectX::XMFLOAT3 vecEye(0.0f, 0.0f, 0.0f); + DirectX::XMFLOAT3 vecAt(0.0f, 0.0f, 1.0f); + g_Camera.SetViewParams(XMLoadFloat3(&vecEye), XMLoadFloat3(&vecAt)); g_sceneRep = new CUDASceneRepHashSDF(CUDASceneRepHashSDF::parametersFromGlobalAppState(GlobalAppState::get())); @@ -700,10 +699,10 @@ HRESULT CALLBACK OnD3D11ResizedSwapChain(ID3D11Device* pd3dDevice, IDXGISwapChai //g_Camera.SetRotateButtons(true, false, false); float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height; - //D3DXVECTOR3 vecEye ( 0.0f, 0.0f, 0.0f ); - //D3DXVECTOR3 vecAt ( 0.0f, 0.0f, 1.0f ); + //DirectX::XMFLOAT3 vecEye ( 0.0f, 0.0f, 0.0f ); + //DirectX::XMFLOAT3 vecAt ( 0.0f, 0.0f, 1.0f ); //g_Camera.SetViewParams( &vecEye, &vecAt ); - g_Camera.SetProjParams(D3DX_PI / 4, fAspectRatio, 0.1f, 10.0f); + g_Camera.SetProjParams(3.141592654f / 4, fAspectRatio, 0.1f, 10.0f); V_RETURN(DX11PhongLighting::OnResize(pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height)); @@ -782,7 +781,9 @@ void visualizeFrame(ID3D11DeviceContext* pd3dImmediateContext, ID3D11Device* pd3 pd3dImmediateContext->ClearRenderTargetView(pRTV, ClearColor); pd3dImmediateContext->ClearDepthStencilView(pDSV, D3D11_CLEAR_DEPTH, 1.0f, 0); - mat4f view = MatrixConversion::toMlib(*g_Camera.GetViewMatrix()); + DirectX::XMFLOAT4X4 temp; + DirectX::XMStoreFloat4x4(&temp, g_Camera.GetViewMatrix()); + mat4f view = MatrixConversion::toMlib(temp); view.setIdentity(); //wanna disable that for the video.. mat4f t = mat4f::identity(); t(1, 1) *= -1.0f; view = t * view * t; //t is self-inverse diff --git a/FriedLiver/Source/PrimeSenseSensor.h b/FriedLiver/Source/PrimeSenseSensor.h index 9d4daeb7..4c5a8a44 100644 --- a/FriedLiver/Source/PrimeSenseSensor.h +++ b/FriedLiver/Source/PrimeSenseSensor.h @@ -32,11 +32,15 @@ class PrimeSenseSensor : public RGBDSensor bool processDepth(); - //! Processes the Kinect color data + //! Processes the PrimeSense color data bool processColor() { return true; } + + std::string getSensorName() const { + return "PrimeSense"; + } protected: //! reads depth and color from the sensor diff --git a/FriedLiver/Source/SiftGPU/MatrixConversion.h b/FriedLiver/Source/SiftGPU/MatrixConversion.h index e1924de4..a7527832 100644 --- a/FriedLiver/Source/SiftGPU/MatrixConversion.h +++ b/FriedLiver/Source/SiftGPU/MatrixConversion.h @@ -31,13 +31,13 @@ namespace MatrixConversion } // dx/cuda conversion - static vec3f toMlib(const D3DXVECTOR3& v) { + static vec3f toMlib(const DirectX::XMFLOAT3& v) { return vec3f(v.x, v.y, v.z); } - static vec4f toMlib(const D3DXVECTOR4& v) { + static vec4f toMlib(const DirectX::XMFLOAT4& v) { return vec4f(v.x, v.y, v.z, v.w); } - static mat4f toMlib(const D3DXMATRIX& m) { + static mat4f toMlib(const DirectX::XMFLOAT4X4& m) { mat4f c((const float*)&m); return c.getTranspose(); } diff --git a/FriedLiver/Source/SiftGPU/ProgramCU.cu b/FriedLiver/Source/SiftGPU/ProgramCU.cu index 963cb0d0..601928e9 100644 --- a/FriedLiver/Source/SiftGPU/ProgramCU.cu +++ b/FriedLiver/Source/SiftGPU/ProgramCU.cu @@ -979,23 +979,22 @@ void __global__ ComputeOrientation_Kernel(float4* d_list, //filter the vote const float one_third = 1.0 / 3.0; __shared__ float vote_tmp[36]; - if (tidx < 36) { - volatile float* source = vote; - volatile float* target = vote_tmp; -#pragma unroll - for (int i = 0; i < 6; i++) { - const unsigned int m = (tidx + 36 - 1) % 36; - const unsigned int c = (tidx); - const unsigned int p = (tidx + 1) % 36; - target[tidx] = (source[m] + source[c] + source[p])*one_third; - - __syncthreads(); - volatile float *tmp = source; - source = target; - target = tmp; - } - } + volatile float* source = vote; + volatile float* target = vote_tmp; +#pragma unroll + for (int i = 0; i < 6; i++) { + const unsigned int m = (tidx + 36 - 1) % 36; + const unsigned int c = (tidx); + const unsigned int p = (tidx + 1) % 36; + if (tidx < 36) + target[tidx] = (source[m] + source[c] + source[p])*one_third; + + __syncthreads(); + volatile float *tmp = source; + source = target; + target = tmp; + } // if (num_orientation == 1) // { @@ -1022,7 +1021,7 @@ void __global__ ComputeOrientation_Kernel(float4* d_list, //__syncthreads(); <- not quite sure if we need that ( probably not ) - max_vote = warpReduceMax(max_vote); + max_vote = warpReduceMax(max_vote); const unsigned int numWarps = (COMPUTE_ORIENTATION_BLOCK + 32 - 1) / 32; __shared__ float sMax[numWarps]; @@ -1036,9 +1035,8 @@ void __global__ ComputeOrientation_Kernel(float4* d_list, __syncthreads(); } - - max_vote = sMax[0]; + float vote_threshold = max_vote * 0.8f; @@ -1100,8 +1098,8 @@ void __global__ ComputeOrientation_Kernel(float4* d_list, __syncthreads(); if (tidx == 0) { weights[maxIndex] = -1.0f; - __syncthreads(); } + __syncthreads(); // 2nd reduction to compute 2nd max weight for (unsigned int stride = COMPUTE_ORIENTATION_BLOCK / 2; stride > 0; stride /= 2) { diff --git a/FriedLiver/Source/SiftGPU/SiftPyramid.cpp b/FriedLiver/Source/SiftGPU/SiftPyramid.cpp index c4fe4c6c..a5a85af9 100644 --- a/FriedLiver/Source/SiftGPU/SiftPyramid.cpp +++ b/FriedLiver/Source/SiftGPU/SiftPyramid.cpp @@ -193,7 +193,7 @@ void SiftPyramid::RunSIFT(float* d_colorData, const float* d_depthData) if (GlobalUtil::_EnableDetailedTimings) { _timer->startEvent("GetFeatureOrientations"); } - GetFeatureOrientations(); + GetFeatureOrientations(); if (GlobalUtil::_EnableDetailedTimings) { _timer->endEvent(); } diff --git a/FriedLiver/Source/SiftGPU/cudaUtil.h b/FriedLiver/Source/SiftGPU/cudaUtil.h index 27a3e527..59d6f1ce 100644 --- a/FriedLiver/Source/SiftGPU/cudaUtil.h +++ b/FriedLiver/Source/SiftGPU/cudaUtil.h @@ -13,56 +13,112 @@ #define cudaAssert(condition) if (!(condition)) { printf("ASSERT: %s %s\n", #condition, __FILE__); } //#define cudaAssert(condition) -#if defined(__CUDA_ARCH__) +# if defined(__CUDA_ARCH__) #define __CONDITIONAL_UNROLL__ #pragma unroll -#else +# else #define __CONDITIONAL_UNROLL__ -#endif +# endif + +# if __CUDACC_VER_MAJOR__ >= 9 +// Note: From CUDA 9, warp-level api has changed. Turing cards will hang forever if warp-level operation not treated correctly. +// (https://devblogs.nvidia.com/using-cuda-warp-level-primitives/) +// (https://github.com/opencv/opencv/pull/13658/commits/970293a229ef314603ffaf77fc62495bf849aba8) -#ifdef __CUDACC__ -__inline__ __device__ +#define FULL_MASK 0xffffffff + +__forceinline__ __device__ float warpReduceSum(float val) { - for (int offset = warpSize / 2; offset > 0; offset /= 2) - val += __shfl_down(val, offset); - return val; + unsigned mask = __ballot_sync(FULL_MASK, threadIdx.x < warpSize); + for (int offset = warpSize / 2; offset > 0; offset /= 2) + val += __shfl_down_sync(mask, val, offset); + return val; } -__inline__ __device__ +__forceinline__ __device__ float warpReduceMax(float val) { - for (int offset = 32 / 2; offset > 0; offset /= 2) { - val = max(val, __shfl_down(val, offset, 32)); - } - return val; + unsigned mask = __ballot_sync(FULL_MASK, threadIdx.x < warpSize); + for (int offset = warpSize / 2; offset > 0; offset /= 2) { + float temp = __shfl_down_sync(mask, val, offset); + val = max(val, temp); + } + return val; } -__inline__ __device__ +__forceinline__ __device__ float warpReduceMin(float val) { - for (int offset = 32 / 2; offset > 0; offset /= 2) { - val = min(val, __shfl_down(val, offset, 32)); - } - return val; + unsigned mask = __ballot_sync(FULL_MASK, threadIdx.x < warpSize); + for (int offset = warpSize / 2; offset > 0; offset /= 2) { + val = min(val, __shfl_down_sync(mask, val, offset)); + } + return val; } -__inline__ __device__ +__forceinline__ __device__ float warpReduceSumAll(float val) { - for (int offset = 32 / 2; offset > 0; offset /= 2) { - val += __shfl_xor(val, offset, 32); - } - return val; + unsigned mask = __ballot_sync(FULL_MASK, threadIdx.x < warpSize); + for (int offset = warpSize / 2; offset > 0; offset /= 2) { + val += __shfl_xor_sync(mask, val, offset); + } + return val; } -__inline__ __device__ +__forceinline__ __device__ float warpReduceMaxAll(float val) { - for (int offset = 32 / 2; offset > 0; offset /= 2) { - val = max(val, __shfl_xor(val, offset, 32)); - } - return val; + unsigned mask = __ballot_sync(FULL_MASK, threadIdx.x < warpSize); + for (int offset = warpSize / 2; offset > 0; offset /= 2) { + val = max(val, __shfl_xor_sync(mask, val, offset)); + } + return val; } -__inline__ __device__ +__forceinline__ __device__ float warpReduceMinAll(float val) { - for (int offset = 32 / 2; offset > 0; offset /= 2) { - val = min(val, __shfl_xor(val, offset, 32)); - } - return val; + unsigned mask = __ballot_sync(FULL_MASK, threadIdx.x < warpSize); + for (int offset = warpSize / 2; offset > 0; offset /= 2) { + val = min(val, __shfl_xor_sync(mask, val, offset)); + } + return val; } -#endif +# elif __CUDACC__ // __CUDACC_VER_MAJOR__ < 9 +//__inline__ __device__ +//float warpReduceSum(float val) { +// for (int offset = warpSize / 2; offset > 0; offset /= 2) +// val += __shfl_down(val, offset); +// return val; +//} +//__inline__ __device__ +//float warpReduceMax(float val) { +// for (int offset = 32 / 2; offset > 0; offset /= 2) { +// val = max(val, __shfl_down(val, offset, 32)); +// } +// return val; +//} +//__inline__ __device__ +//float warpReduceMin(float val) { +// for (int offset = 32 / 2; offset > 0; offset /= 2) { +// val = min(val, __shfl_down(val, offset, 32)); +// } +// return val; +//} +// +//__inline__ __device__ +//float warpReduceSumAll(float val) { +// for (int offset = 32 / 2; offset > 0; offset /= 2) { +// val += __shfl_xor(val, offset, 32); +// } +// return val; +//} +//__inline__ __device__ +//float warpReduceMaxAll(float val) { +// for (int offset = 32 / 2; offset > 0; offset /= 2) { +// val = max(val, __shfl_xor(val, offset, 32)); +// } +// return val; +//} +//__inline__ __device__ +//float warpReduceMinAll(float val) { +// for (int offset = 32 / 2; offset > 0; offset /= 2) { +// val = min(val, __shfl_xor(val, offset, 32)); +// } +// return val; +//} +# endif #endif diff --git a/FriedLiver/Source/mLib.h b/FriedLiver/Source/mLib.h index 63202f41..2bc2fea3 100644 --- a/FriedLiver/Source/mLib.h +++ b/FriedLiver/Source/mLib.h @@ -1,4 +1,4 @@ - +#pragma once // // mLib config options // @@ -11,7 +11,6 @@ // mLib includes // - #include "mLibCore.h" #include "mLibFreeImage.h" #include "mLibDepthCamera.h" diff --git a/FriedLiver/zParametersDefault.txt b/FriedLiver/zParametersDefault.txt index b57f56a1..72be9447 100644 --- a/FriedLiver/zParametersDefault.txt +++ b/FriedLiver/zParametersDefault.txt @@ -1,5 +1,5 @@ // 0=Kinect; 1=PrimeSense; 2=KinectOne; 3=BinaryDumpReader; 4=NetworkSensor; 5=IntelSensor; 6=RealSense; 7=StructureSensor; 8=SensorDataReader (for offline processing) -s_sensorIdx = 7; +s_sensorIdx = 8; s_numSolveFramesBeforeExit = 30;//-1 //#frames to run after solve done, then saves and exits; -1 to stop after no more reintegration ops @@ -45,8 +45,8 @@ s_SDFIntegrationWeightSample = 1; //weight for an integrated depth value s_SDFIntegrationWeightMax = 99999999; //maximum integration weight for a voxel // s_SDFBlockSize is pound defined (SDF_BLOCK_SIZE) // s_hashBucketSize is pound defined (HASH_BUCKET_SIZE) -s_hashNumBuckets = 800000; //smaller voxels require more space -s_hashNumSDFBlocks = 200000;//100000; //smaller voxels require more space +s_hashNumBuckets = 400000; //smaller voxels require more space +s_hashNumSDFBlocks = 100000;//100000; //smaller voxels require more space s_hashMaxCollisionLinkedListSize = 7; // raycast diff --git a/README.md b/README.md index 93b5cabc..189b2c65 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,36 @@ # BundleFusion -![BundleFusion](img/teaser.jpg) +![BundleFusion](img/test.gif) -You are free to use this code with proper attribution in non-commercial applications (Please see [License.txt](License.txt)). +This is a modern port for [BundleFusion](http://graphics.stanford.edu/projects/bundlefusion/). Since DirectX SDK has been deprecated and Nvidia changed some CUDA apis, original BundleFusion code would not run smoothly on latest platforms. For example, code compiled in VS2017 does not run in Release mode. Also, the original code hangs on GPU synchronize function if you use new volta/turing GPUs. -More information about this project can be found in our [paper](https://arxiv.org/pdf/1604.01093.pdf) and [project website](http://graphics.stanford.edu/projects/bundlefusion/). +The license is the same with original BundleFusion. (Please see [License.txt](LICENSE.txt)). ## Installation -The code was developed under VS2013, and tested with a Structure Sensor. +The modified code was tested under VS2017 with CUDA10.1 and a RTX2060. Requirements: -- DirectX SDK June 2010 -- NVIDIA CUDA 7.0 -- our research library mLib, a git submodule in external/mLib +- Windows SDK (Install it from your Visual Studio) +- DirectX SDK **IS NOT NEEDED** +- NVIDIA CUDA 10.1 +- research library mLib, a git submodule in external/mLib - mLib external libraries can be downloaded [here](http://kaldir.vc.in.tum.de/mLib/mLibExternal.zip) -Optional: -- Kinect SDK (2.0 and above) -- Prime sense SDK - - -## Citation: +Default file tree: ``` -@article{dai2017bundlefusion, - title={BundleFusion: Real-time Globally Consistent 3D Reconstruction using On-the-fly Surface Re-integration}, - author={Dai, Angela and Nie{\ss}ner, Matthias and Zoll{\"o}fer, Michael and Izadi, Shahram and Theobalt, Christian}, - journal={ACM Transactions on Graphics 2017 (TOG)}, - year={2017} -} +BundleFusion-master +├──BundleFusion +│ │──data +│ │──external +│ │──FriedLiver +│ └──img +└──mlibExternal + │──include + │──libsLinux + │──libsOSX + └──libsWindows ``` +Put sequence.sens in BundleFusion-master/BundleFusion/data/. -## Contact: -If you have any questions, please email Angela Dai at adai@cs.stanford.edu. - - - -We are also looking for active participation in this open source effort making large-scale 3D scanning publically accessible. Please contact us :) +## End +You may star me if you find it useful. :) diff --git a/README.md.old b/README.md.old new file mode 100644 index 00000000..93b5cabc --- /dev/null +++ b/README.md.old @@ -0,0 +1,38 @@ +# BundleFusion + +![BundleFusion](img/teaser.jpg) + +You are free to use this code with proper attribution in non-commercial applications (Please see [License.txt](License.txt)). + +More information about this project can be found in our [paper](https://arxiv.org/pdf/1604.01093.pdf) and [project website](http://graphics.stanford.edu/projects/bundlefusion/). + +## Installation +The code was developed under VS2013, and tested with a Structure Sensor. + +Requirements: +- DirectX SDK June 2010 +- NVIDIA CUDA 7.0 +- our research library mLib, a git submodule in external/mLib +- mLib external libraries can be downloaded [here](http://kaldir.vc.in.tum.de/mLib/mLibExternal.zip) + +Optional: +- Kinect SDK (2.0 and above) +- Prime sense SDK + + +## Citation: +``` +@article{dai2017bundlefusion, + title={BundleFusion: Real-time Globally Consistent 3D Reconstruction using On-the-fly Surface Re-integration}, + author={Dai, Angela and Nie{\ss}ner, Matthias and Zoll{\"o}fer, Michael and Izadi, Shahram and Theobalt, Christian}, + journal={ACM Transactions on Graphics 2017 (TOG)}, + year={2017} +} +``` + +## Contact: +If you have any questions, please email Angela Dai at adai@cs.stanford.edu. + + + +We are also looking for active participation in this open source effort making large-scale 3D scanning publically accessible. Please contact us :) diff --git a/img/test.gif b/img/test.gif new file mode 100644 index 00000000..91fa5251 Binary files /dev/null and b/img/test.gif differ