Updated samples for the 2210 GDK release. (#16)

* Updated samples for the 2210 GDK release.

* Moved samples list to the wiki.

* Updated readme to use wiki links for samples list.
This commit is contained in:
Scott Matloff 2022-11-03 13:15:17 -07:00 коммит произвёл GitHub
Родитель db9c945689
Коммит aa45b831e7
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
757 изменённых файлов: 32626 добавлений и 11449 удалений

Просмотреть файл

@ -974,6 +974,8 @@ void ATG::Help::RestoreDevice(ID3D11DeviceContext* context)
);
}
const DDS_LOADER_FLAGS loadFlags = m_linearColors ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT;
#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)
wchar_t buff[MAX_PATH];
DX::FindMediaFile(buff, MAX_PATH, L"SegoeUI_18.spritefont");
@ -986,21 +988,21 @@ void ATG::Help::RestoreDevice(ID3D11DeviceContext* context)
m_spriteFonts[SEGOE_UI_36PT] = std::make_unique<SpriteFont>(device.Get(), buff);
DX::FindMediaFile(buff, MAX_PATH, L"callout_circle.dds");
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), buff, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, m_linearColors, nullptr, m_circleTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), buff, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, loadFlags, nullptr, m_circleTex.ReleaseAndGetAddressOf()));
DX::FindMediaFile(buff, MAX_PATH, L"gamepad.dds");
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), buff, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, m_linearColors, nullptr, m_gamepadTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), buff, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, loadFlags, nullptr, m_gamepadTex.ReleaseAndGetAddressOf()));
DX::FindMediaFile(buff, MAX_PATH, L"ATGSampleBackground.DDS");
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), buff, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, m_linearColors, nullptr, m_backgroundTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), buff, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, loadFlags, nullptr, m_backgroundTex.ReleaseAndGetAddressOf()));
#else
m_spriteFonts[SEGOE_UI_18PT] = std::make_unique<SpriteFont>(device.Get(), L"SegoeUI_18.spritefont");
m_spriteFonts[SEGOE_UI_22PT] = std::make_unique<SpriteFont>(device.Get(), L"SegoeUI_22.spritefont");
m_spriteFonts[SEGOE_UI_36PT] = std::make_unique<SpriteFont>(device.Get(), L"SegoeUI_36.spritefont");
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), L"callout_circle.dds", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, m_linearColors, nullptr, m_circleTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), L"gamepad.dds", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, m_linearColors, nullptr, m_gamepadTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), L"ATGSampleBackground.DDS", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, m_linearColors, nullptr, m_backgroundTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), L"callout_circle.dds", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, loadFlags, nullptr, m_circleTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), L"gamepad.dds", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, loadFlags, nullptr, m_gamepadTex.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(CreateDDSTextureFromFileEx(device.Get(), L"ATGSampleBackground.DDS", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, loadFlags, nullptr, m_backgroundTex.ReleaseAndGetAddressOf()));
#endif
}
#endif

Просмотреть файл

@ -69,18 +69,17 @@ namespace
namespace DirectX
{
namespace Internal
inline namespace DX12
{
// Reuse the WIC factory function from the DirectX Tool Kit. For implementation details, see WICTextureLoader.cpp
#if defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
extern IWICImagingFactory2* GetWIC();
#else
extern IWICImagingFactory* GetWIC();
#endif
namespace Internal
{
// Reuse the WIC factory function from the DirectX Tool Kit. For implementation details, see WICTextureLoader.cpp
extern IWICImagingFactory2* GetWIC();
}
}
}
using namespace DirectX::Internal;
using namespace DirectX::DX12::Internal;
// --------------------------------------------------------------------------------
// FrontPanelDisplay methods

Просмотреть файл

@ -14,7 +14,6 @@
#include <sysinfoapi.h>
#undef max
#undef min
#include "intrin.h"
#if defined(_GAMING_XBOX)
#include <xsystem.h>
@ -41,7 +40,7 @@ namespace
std::wstring g_processorName; // The general processor name. This can be changed by the user to allow easier usage in their code
std::wstring g_trueProcessorName; // The actual name of the processor as returned by the OS
uint64_t g_processMask = 0; // In general all the cores that exist on the processor, when >64 this will be bound to the group the process is assigned to
std::vector<uint32_t> g_numLogicalCores; // How many logical cores exist, if not hyperthreaded == number of physical cores
std::vector<uint32_t> g_numLogicalCores; // How many logical cores exist, if SMT is not supported == number of physical cores
std::vector<uint64_t> g_availableCoresMask; // Which cores are actually available to the caller, for example ERA does not allow the 8th core to be used, index is groupID
#if !defined(_XBOX_ONE) // we don't use this on ERA because GetLogicalProcessorInfoEx and GetLogicalProcessorInformation is not supported
@ -65,7 +64,7 @@ namespace
SYSTEM_INFO g_systemInfo; // Cached copy of data from GetSystemInfo
std::vector<ATG::UniqueProcessorMask> g_topLevelCacheMask; // For each top level cache the mask of cores that share id. This tends to be processors that have several internal clusters, for example Durango has two clusters
std::map<ATG::ProcessorGroupID, std::vector<std::pair<bool, uint64_t>>> g_physicalCores; // For each physical core a mask of the logical cores that map to that physical core and a flag for whether it's hyperthreaded
std::map<ATG::ProcessorGroupID, std::vector<std::pair<bool, uint64_t>>> g_physicalCores; // For each physical core a mask of the logical cores that map to that physical core and a flag for whether it has support for SMT
std::vector <ATG::CacheInformation> g_caches; // A list of each cache present on the processor, L1, L2, L3, Instruction, Data, and Trace (haven't seen this on any processor yet)
double g_rdtscpFrequencySeconds; // The frequency in seconds of the __rdtscp, measured automatically at startup
@ -315,15 +314,32 @@ void ATG::GetCacheInformation(const UniqueProcessorMask& coreMask, std::vector<C
}
}
uint32_t ATG::GetProcessorFamily()
{
int CPUInfo[4] = { -1 };
#ifdef __clang__
__cpuid(1, CPUInfo[0], CPUInfo[1], CPUInfo[2], CPUInfo[3]);
#else
__cpuid(CPUInfo, 1);
#endif
return static_cast<uint32_t> (((CPUInfo[0] & 0xf00) >> 8) + ((CPUInfo[0] & 0x0ff00000) >> 20));
}
bool ATG::SetupProcessorData()
{
if (g_trueProcessorName.size())
return true;
#if !defined(_XBOX_ONE) && !defined(_GAMING_XBOX) // Xbox doesn't have this registry entry
g_osProcessorInfo.bufferSize = 0;
g_osProcessorInfo.rawData = nullptr;
wchar_t processorName[256] = {};
DWORD dataSize = sizeof(wchar_t) * 256;
RegGetValueW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", L"ProcessorNameString", RRF_RT_REG_SZ, nullptr, processorName, &dataSize);
g_trueProcessorName = processorName;
{
wchar_t processorName[256];
DWORD dataSize = sizeof(wchar_t) * 256;
RegGetValueW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", L"ProcessorNameString", RRF_RT_REG_SZ, nullptr, processorName, &dataSize);
g_trueProcessorName = processorName;
}
#elif defined(_GAMING_XBOX)
XSystemDeviceType info;
info = XSystemGetDeviceType();
@ -410,7 +426,7 @@ bool ATG::SetupProcessorData()
ParseOSProcessorInfo();
#if defined(_GAMING_XBOX)
if (ATG::IsHyperThreaded())
if (ATG::IsSMTSupported())
g_trueProcessorName += L"_SMT";
g_processorName = g_trueProcessorName;
#endif
@ -500,7 +516,7 @@ void ATG::LogProcessorInfo(const std::wstring& logName)
swprintf_s(buffer, 256, L"%s_procInfo", g_trueProcessorName.c_str());
fileName = buffer;
}
ATG::FileLogger procLog(fileName, false);
ATG::FileLogger procLog(fileName, false, false, false, true, true);
#if !defined(_GAMING_XBOX)
wchar_t buffer[256];
@ -531,7 +547,7 @@ void ATG::LogProcessorInfo(const std::wstring& logName)
case RelationProcessorCore:
procLog.Log(L"Processor Core");
if (procInfo->Processor.Flags == LTP_PC_SMT)
procLog.Log(L" Core is hyper threaded");
procLog.Log(L" Core supports SMT");
if (procInfo->Processor.EfficiencyClass != 0)
procLog.Log(L" Core efficiency class is set");
for (uint32_t i = 0; i < procInfo->Processor.GroupCount; i++)
@ -658,7 +674,7 @@ void ATG::LogProcessorInfo(const std::wstring& logName)
case RelationProcessorCore:
procLog.Log(L"Processor Core");
if (procInfo->ProcessorCore.Flags == 1)
procLog.Log(L" Core is hyper threaded");
procLog.Log(L" Core supports SMT");
swprintf(buffer, 256, L" CoreMask - %016I64x", procInfo->ProcessorMask);
procLog.Log(buffer);
break;
@ -691,7 +707,7 @@ void ATG::LogCoreTests(const std::wstring& suffix, const std::wstring& logName)
swprintf_s(buffer, 256, L"%s_coreTests_%s", g_trueProcessorName.c_str(), suffix.c_str());
fileName = buffer;
}
ATG::FileLogger testLog(fileName, false);
ATG::FileLogger testLog(fileName, false, false, false, true, true);
size_t numTests = g_representativeCoreTests.size();
for (size_t i = 0; i < numTests; i++)
{
@ -776,7 +792,7 @@ namespace
testNames.push_back(L"all_cores");
// one logical per physical
if (ATG::IsHyperThreaded())
if (ATG::IsSMTSupported())
{
uint64_t oneLogicalMask = 0;
for (const auto& iter : cpuSets)
@ -814,7 +830,7 @@ namespace
}
// single physical core, one per cluster
if (minLowCacheCores > 1) // this means hyperthreaded
if (minLowCacheCores > 1) // this means SMT is supported
{
for (const auto& cluster : cpuSets)
{
@ -935,7 +951,7 @@ namespace
}
}
// cross cluster tests, pick one physical core even if hyperthreaded
// cross cluster tests, pick one physical core even if SMT is supported
{
for (const auto& outerCluster : cpuSets)
{
@ -976,21 +992,21 @@ namespace
testNames.clear();
constexpr uint32_t s_maxSingleCores = 4u;
bool hyperThreaded = false;
bool smtSupported = false;
uint64_t allCoresMask(0);
wchar_t tempBuffer[256];
for (const auto& iter : g_physicalCores[groupID])
{
allCoresMask |= iter.second;
if (iter.first)
hyperThreaded = true;
smtSupported = true;
}
coreTests.push_back(allCoresMask); // do everything
testNames.push_back(L"all_cores");
// physical cores
{
const uint32_t numSingle = std::min(ATG::GetNumPhysicalCores(groupID), s_maxSingleCores);
const uint32_t coreDelta = std::max<uint32_t>(hyperThreaded ? 2U : 1U, static_cast<uint32_t> ((((float)ATG::GetTotalNumCores(groupID)) / numSingle) + 0.5f)); // assume hyperthreaded are only 2 cores per physical
const uint32_t coreDelta = std::max<uint32_t>(smtSupported ? 2U : 1U, static_cast<uint32_t> ((((float)ATG::GetTotalNumCores(groupID)) / numSingle) + 0.5f)); // assume SMT supported are only 2 cores per physical
uint64_t curMask = 0;
for (uint32_t i = 0; i < numSingle; i++, curMask += coreDelta)
{
@ -999,10 +1015,10 @@ namespace
testNames.push_back(tempBuffer);
}
}
if (hyperThreaded)
if (smtSupported)
{
const uint32_t numSingle = std::min(ATG::GetNumPhysicalCores(groupID), s_maxSingleCores);
const uint32_t coreDelta = std::max<uint32_t>(2, ATG::GetTotalNumCores(groupID) / numSingle); // assume hyperthreaded are only 2 cores per physical. Code below will set the mask correctly
const uint32_t coreDelta = std::max<uint32_t>(2, ATG::GetTotalNumCores(groupID) / numSingle); // assume SMT supported are only 2 cores per physical. Code below will set the mask correctly
uint64_t curMask = 0;
for (uint32_t i = 0; i < numSingle; i++, curMask += coreDelta)
{
@ -1015,7 +1031,6 @@ namespace
if (g_dieMask.size() > 1) // numa nodes will show up here
{
// all cores in a cluster
uint32_t curCluster = 0;
for (const auto& iter : g_dieMask)
{
if (iter.second.groupID != groupID)
@ -1023,11 +1038,9 @@ namespace
coreTests.push_back(iter.second.coreMask);
swprintf_s(tempBuffer, 256, L"full_cluster_0x%llx", iter.second.coreMask);
testNames.push_back(tempBuffer);
curCluster++;
}
// two cores in a cluster
curCluster = 0;
for (const auto& iter : g_dieMask)
{
if (iter.second.groupID != groupID)
@ -1040,14 +1053,12 @@ namespace
swprintf_s(tempBuffer, 256, L"within_cluster_physical_0x%llx", (1ULL << lowBitIndex) | (1ULL << highBitIndex));
testNames.push_back(tempBuffer);
if (hyperThreaded)
if (smtSupported)
{
coreTests.push_back(ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << lowBitIndex, groupID)) | ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << highBitIndex, groupID)));
swprintf_s(tempBuffer, 256, L"within_cluster_hyper_0x%llx", ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << lowBitIndex, groupID)) | ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << highBitIndex, groupID)));
swprintf_s(tempBuffer, 256, L"within_cluster_SMT_0x%llx", ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << lowBitIndex, groupID)) | ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << highBitIndex, groupID)));
testNames.push_back(tempBuffer);
}
curCluster++;
}
// one physical on all combinations of 2 clusters
@ -1073,7 +1084,7 @@ namespace
_BitScanForward64(&outerBitIndex, outer->second.coreMask);
_BitScanForward64(&innerBitIndex, inner->second.coreMask);
if (hyperThreaded)
if (smtSupported)
{
coreTests.push_back(ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << outerBitIndex, groupID)) | ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << innerBitIndex, groupID)));
swprintf_s(tempBuffer, 256, L"cross_cluster_logical_0x%llx", ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << outerBitIndex, groupID)) | ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << innerBitIndex, groupID)));
@ -1091,7 +1102,7 @@ namespace
// half the cores in a single
const uint32_t halfLogical = ATG::GetNumLogicalCores(groupID) / 2;
uint64_t lowMask(0), highMask(0);
for (uint32_t i = 0; i < halfLogical; i += hyperThreaded ? 2 : 1)
for (uint32_t i = 0; i < halfLogical; i += smtSupported ? 2 : 1)
{
lowMask |= ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << i, groupID));
highMask |= ATG::GetLogicalProcessorMask(ATG::UniqueProcessorMask(1ULL << (halfLogical + i), groupID));
@ -1105,7 +1116,7 @@ namespace
testNames.push_back(tempBuffer);
// two physical cores
if (hyperThreaded && (ATG::GetNumPhysicalCores(groupID) >= 4)) // just assume 2 cores in a hyperthread and at least 4 physical cores
if (smtSupported && (ATG::GetNumPhysicalCores(groupID) >= 4)) // just assume 2 cores in a SMT supported and at least 4 physical cores
{
coreTests.push_back(0x05);
swprintf_s(tempBuffer, 256, L"first two physical 0x05");
@ -1115,8 +1126,8 @@ namespace
swprintf_s(tempBuffer, 256, L"second two physical 0xA0");
testNames.push_back(tempBuffer);
}
// handle 2 physical hyperthreaded cores
if (hyperThreaded && (ATG::GetNumPhysicalCores(groupID) == 2))
// handle 2 physical SMT cores
if (smtSupported && (ATG::GetNumPhysicalCores(groupID) == 2))
{
coreTests.push_back(0x05);
swprintf_s(tempBuffer, 256, L"Two physical_0x05");
@ -1309,7 +1320,6 @@ namespace
g_numLogicalCores.resize(groupCount, 0);
g_availableCoresMask.resize(groupCount, 0);
uint32_t entries = 0;
data = g_osProcessorInfo.rawData;
dataLeft = g_osProcessorInfo.bufferSize;
while (dataLeft)
@ -1367,7 +1377,6 @@ namespace
}
dataLeft -= procInfo->Size;
data = data + procInfo->Size;
entries++;
}
#endif

Просмотреть файл

@ -21,6 +21,8 @@ namespace ATG
using ProcessorGroupID = uint16_t;
using ProcessorNumaNodeID = uint32_t;
constexpr uint32_t JAGUAR_PROCESSOR_FAMILY = 0x16;
constexpr uint32_t ZEN2_PROCESSOR_FAMILY = 0x17;
struct UniqueProcessorMask
{
@ -86,7 +88,7 @@ namespace ATG
uint32_t GetTotalNumCores(ProcessorGroupID groupID = 0);
uint64_t GetAvailableCoresMask(ProcessorGroupID groupID = 0);
inline bool IsHyperThreaded(ProcessorGroupID groupID = 0) { return GetNumPhysicalCores(groupID) < GetNumLogicalCores(groupID); }
inline bool IsSMTSupported(ProcessorGroupID groupID = 0) { return GetNumPhysicalCores(groupID) < GetNumLogicalCores(groupID); }
double GetRDTSCPFrequencySeconds();
double GetRDTSCPFrequencyMilliseconds();
double GetRDTSCPFrequencyMicroseconds();
@ -94,6 +96,7 @@ namespace ATG
const std::wstring& GetProcessorName(); // will be the override value which is initially the true name
const std::wstring& GetTrueProcessorName();
void SetProcessorName(const std::wstring& overrideName);
uint32_t GetProcessorFamily();
uint64_t GetLogicalProcessorMask(uint64_t coreMask); // adjusts the mask to cover all logical processors

Просмотреть файл

@ -10,103 +10,109 @@
#include <cassert>
#include <cstdint>
#include "intrin.h"
#include <intrin.h>
namespace ATG
{
double CalcRDTSCPFrequency();
extern double s_rdtscpFrequencySecs;
extern double s_rdtscpFrequencyMS;
extern double s_rdtscpFrequencyUS;
double CalcRDTSCPFrequency();
extern double s_rdtscpFrequencySecs;
extern double s_rdtscpFrequencyMS;
extern double s_rdtscpFrequencyUS;
extern double s_rdtscpFrequencyNS;
class RDTSCPStopWatch
{
private:
uint64_t m_startTimeRaw;
uint64_t m_stopTimeRaw;
bool m_running;
class RDTSCPStopWatch
{
private:
uint64_t m_startTimeRaw;
uint64_t m_stopTimeRaw;
bool m_running;
public:
public:
RDTSCPStopWatch() :m_startTimeRaw(0), m_stopTimeRaw(0), m_running(false) {}
void Start()
{
assert(!m_running);
m_running = true;
m_stopTimeRaw = 0;
uint32_t tempAux;
m_startTimeRaw = __rdtscp(&tempAux);
}
double Stop()
{
assert(m_running);
uint32_t tempAux;
m_stopTimeRaw = __rdtscp(&tempAux);
m_running = false;
return GetTotalSeconds();
}
RDTSCPStopWatch() :m_startTimeRaw(0), m_stopTimeRaw(0), m_running(false) {}
void Reset()
{
m_startTimeRaw = 0;
m_stopTimeRaw = 0;
}
bool IsRunning() const noexcept { return m_running; }
void Start()
{
assert(!m_running);
m_running = true;
m_stopTimeRaw = 0;
uint32_t tempAux;
m_startTimeRaw = __rdtscp(&tempAux);
}
double Stop()
{
assert(m_running);
uint32_t tempAux;
m_stopTimeRaw = __rdtscp(&tempAux);
m_running = false;
return GetTotalSeconds();
}
static double GetFrequencyMilliseconds() { return s_rdtscpFrequencyMS; }
void Reset()
{
uint32_t tempAux;
m_startTimeRaw = __rdtscp(&tempAux);
m_stopTimeRaw = 0;
}
double GetCurrentSeconds() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return static_cast<double>(temp - m_startTimeRaw) / s_rdtscpFrequencySecs;
}
double GetCurrentMilliseconds() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return static_cast<double>(temp - m_startTimeRaw) / s_rdtscpFrequencyMS;
}
double GetCurrentMicroseconds() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return static_cast<double>(temp - m_startTimeRaw) / s_rdtscpFrequencyUS;
}
uint64_t GetCurrentRaw() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return temp - m_startTimeRaw;
}
static double GetFrequencyMilliseconds() { return s_rdtscpFrequencyMS; }
static double GetFrequencyMicroseconds() { return s_rdtscpFrequencyUS; }
static double GetFrequencyNanoseconds() { return s_rdtscpFrequencyNS; }
double GetTotalSeconds() const
{
assert(!m_running);
return static_cast<double>(m_stopTimeRaw - m_startTimeRaw) / s_rdtscpFrequencySecs;
}
double GetTotalMilliseconds() const
{
assert(!m_running);
return static_cast<double>(m_stopTimeRaw - m_startTimeRaw) / s_rdtscpFrequencyMS;
}
double GetTotalMicroseconds() const
{
assert(!m_running);
return static_cast<double>(m_stopTimeRaw - m_startTimeRaw) / s_rdtscpFrequencyUS;
}
double GetCurrentSeconds() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return static_cast<double>(temp - m_startTimeRaw) / s_rdtscpFrequencySecs;
}
double GetCurrentMilliseconds() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return static_cast<double>(temp - m_startTimeRaw) / s_rdtscpFrequencyMS;
}
double GetCurrentMicroseconds() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return static_cast<double>(temp - m_startTimeRaw) / s_rdtscpFrequencyUS;
}
uint64_t GetCurrentRaw() const
{
assert(m_running);
uint32_t tempAux;
uint64_t temp;
temp = __rdtscp(&tempAux);
return temp - m_startTimeRaw;
}
uint64_t GetTotalRaw() const
{
assert(!m_running);
return m_stopTimeRaw - m_startTimeRaw;
}
};
double GetTotalSeconds() const
{
assert(!m_running);
return static_cast<double>(m_stopTimeRaw - m_startTimeRaw) / s_rdtscpFrequencySecs;
}
double GetTotalMilliseconds() const
{
assert(!m_running);
return static_cast<double>(m_stopTimeRaw - m_startTimeRaw) / s_rdtscpFrequencyMS;
}
double GetTotalMicroseconds() const
{
assert(!m_running);
return static_cast<double>(m_stopTimeRaw - m_startTimeRaw) / s_rdtscpFrequencyUS;
}
uint64_t GetTotalRaw() const
{
assert(!m_running);
return m_stopTimeRaw - m_startTimeRaw;
}
};
}

Просмотреть файл

@ -15,6 +15,7 @@ namespace ATG
double s_rdtscpFrequencySecs = CalcRDTSCPFrequency(); // force init at startup
double s_rdtscpFrequencyMS; // CalcRDTSCPFrequency auto sets these
double s_rdtscpFrequencyUS; // CalcRDTSCPFrequency auto sets these
double s_rdtscpFrequencyNS; // CalcRDTSCPFrequency auto sets these
double CalcRDTSCPFrequency()
{
@ -64,8 +65,9 @@ namespace ATG
SetThreadPriority(GetCurrentThread(), currentPriority);
s_rdtscpFrequencySecs = (rdtscFrequencyIdle + rdtscFrequencyLoad) / 2.0; // the numbers should be close to identical so just average
s_rdtscpFrequencyMS = s_rdtscpFrequencySecs / 1000;
s_rdtscpFrequencyUS = s_rdtscpFrequencySecs / 1000000;
s_rdtscpFrequencyMS = s_rdtscpFrequencySecs / 1000.0;
s_rdtscpFrequencyUS = s_rdtscpFrequencySecs / 1000000.0;
s_rdtscpFrequencyNS = s_rdtscpFrequencySecs / 1000000000.0;
return s_rdtscpFrequencySecs;
}

Просмотреть файл

@ -11,26 +11,28 @@
namespace ATG
{
template<typename randomSize>
randomSize GetRandomValue(randomSize range)
{
static std::random_device randomDevice;
static std::mt19937_64 randomEngine(randomDevice());
template<typename randomSize>
randomSize GetRandomValue(randomSize range)
{
if (range == 0)
return range;
static std::random_device randomDevice;
static std::mt19937_64 randomEngine(randomDevice());
using distribution = typename std::conditional< std::is_floating_point_v<randomSize>, std::uniform_real_distribution<randomSize>, std::uniform_int_distribution<randomSize>>::type;
static distribution randomValue(0, std::numeric_limits<randomSize>::max());
using distribution = typename std::conditional< std::is_floating_point_v<randomSize>, std::uniform_real_distribution<randomSize>, std::uniform_int_distribution<randomSize>>::type;
static distribution randomValue(0, std::numeric_limits<randomSize>::max());
randomSize toret = randomValue(randomEngine);
if (std::is_floating_point_v<randomSize>)
{
toret /= std::numeric_limits<randomSize>::max();
toret *= range;
}
else
{
randomSize temp = toret / range;
toret -= (temp * range);
}
return toret;
}
randomSize toret = randomValue(randomEngine);
if (std::is_floating_point_v<randomSize>)
{
toret /= std::numeric_limits<randomSize>::max();
toret *= range;
}
else
{
randomSize temp = toret / range;
toret -= (temp * range);
}
return toret;
}
}

Просмотреть файл

@ -198,7 +198,7 @@ Texture::Texture(ID3D11Device* device, const wchar_t* fileName, bool forceSRGB)
ThrowIfFailed(
CreateDDSTextureFromFileEx( device, fileName, 0,
D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0,
forceSRGB,
forceSRGB ? DDS_LOADER_FORCE_SRGB : DDS_LOADER_DEFAULT,
resource.GetAddressOf(), resourceView.GetAddressOf(), &m_alphaMode)
);
}

Просмотреть файл

@ -11,11 +11,9 @@
#include "ATGColors.h"
namespace DirectX {
class SpriteBatch;
class DescriptorHeap;
enum SpriteEffects : uint32_t;
}
#include "DescriptorHeap.h"
#include "SpriteBatch.h"
namespace ATG
{

Просмотреть файл

@ -7,7 +7,6 @@
#pragma once
#include <cassert>
#include <chrono>
namespace ATG
@ -33,7 +32,7 @@ namespace ATG
UserEventLockable(const UserEventLockable&) = delete;
UserEventLockable& operator=(const UserEventLockable&) = delete;
UserEventLockable(bool initialState = true) : m_threadsWaiting(0), m_eventFlag(static_cast<uint32_t> (initialState ? 1 : 0)) { }
UserEventLockable(bool initialState = true) noexcept : m_threadsWaiting(0), m_eventFlag(initialState ? 1 : 0u) { }
UserEventLockable(UserEventLockable&& rhs) = default;
~UserEventLockable() { }
@ -143,7 +142,7 @@ namespace ATG
UserSemaphoreLockable(UserSemaphoreLockable&& rhs) = delete;
UserSemaphoreLockable& operator=(const UserSemaphoreLockable&&) = delete;
UserSemaphoreLockable(uint32_t intialValue) : m_threadsWaiting(0), m_semaphore(intialValue) { }
UserSemaphoreLockable(uint32_t intialValue) noexcept : m_threadsWaiting(0), m_semaphore(intialValue) { }
~UserSemaphoreLockable() { }
void lock()
@ -173,6 +172,7 @@ namespace ATG
const uint32_t newValue = currentValue - 1; // locking only reduces the count by 1
if (InterlockedCompareExchange(&m_semaphore, newValue, currentValue) == currentValue)
return true;
_mm_pause();
}
}
@ -185,6 +185,7 @@ namespace ATG
const uint32_t newValue = currentValue + releaseCount;
if (InterlockedCompareExchange(&m_semaphore, newValue, currentValue) == currentValue)
break;
_mm_pause();
}
if (m_threadsWaiting) // only call WakeByAddress if there is a high probability of a thread actually waiting.
@ -241,29 +242,100 @@ namespace ATG
//////////////////////////////////////////////////////////////////////////
///
/// Event object that attempts to stay at user level as much as possible
/// The object will only go to kernel mode if there is actually a thread waiting on the event
/// This allows for the maximum performance.
/// UserBarrier object that attempts to stay at user level as much as possible
/// The object will only go to kernel mode if requested and it's waiting for more threads to hit the barrier
/// The enterBarrier call can be set to pure spin to allow all waiting threads to exit as soon as possible
/// If threads spin care must be taken that no other threads are running on the same core to avoid extremely long waits
/// The threadOwner template parameter provides protection so only a single thread can call reset, the initial thread to enter the barrier
///
//////////////////////////////////////////////////////////////////////////
template<bool threadOwner>
class UserBarrier
{
private:
std::atomic<uint64_t> m_barrierValue;
uint64_t m_initialValue;
UserEventLockable<true> m_blockEvent;
uint32_t m_threadOwnerID;
public:
/// The UserBarrier cannot be copied
UserBarrier(const UserBarrier&) = delete;
UserBarrier& operator=(const UserBarrier&) = delete;
UserBarrier(uint64_t initialValue = 1) noexcept : m_barrierValue(initialValue), m_initialValue(initialValue), m_blockEvent(false), m_threadOwnerID(0) { }
UserBarrier(UserBarrier&& rhs) = default;
~UserBarrier() { }
void clearOwner() { m_threadOwnerID = 0; }
bool enterBarrier(bool block = false)
{
assert(m_barrierValue != 0);
if (threadOwner)
{
if (m_threadOwnerID == 0)
m_threadOwnerID = GetCurrentThreadId();
}
uint64_t myValue = m_barrierValue.fetch_sub(1);
if (myValue == 1)
{
m_blockEvent.SetEvent();
return true;
}
else if (block)
{
m_blockEvent.lock();
}
else
{
while (m_barrierValue.load() != 0) { _mm_pause(); }
}
return false;
}
bool reset() { return reset(m_initialValue); }
bool reset(uint64_t newValue)
{
if (threadOwner)
{
if (m_threadOwnerID != GetCurrentThreadId())
{
if (InterlockedCompareExchange(&m_threadOwnerID, GetCurrentThreadId(), 0) != 0)
return false;
}
}
m_initialValue = newValue;
m_barrierValue = newValue;
m_blockEvent.SetEvent();
m_blockEvent.ResetEvent();
return true;
}
};
//////////////////////////////////////////////////////////////////////////
///
/// MonitorXMwaitXLockable object that attempts to stay at user level as much as possible
/// Spin lock implemented using the monitorx/mwaitx instructions
/// This class will stay in user-mode the entire time
/// Interfaces follow the C++11 TimeLockable concept
/// The template parameter on manual reset is used to allow the compiler to optimize out the conditional
///
//////////////////////////////////////////////////////////////////////////
#if !defined(__clang__) || defined (__MWAITX__) //NOTE: Clang explictly only includes this intrinsic if __MWAITX__ is defined and it needs to be defined in the pch file before the x86intrin.h is included
#pragma warning (push)
#pragma warning (disable: 4324)
#pragma warning (disable: 4324) // structure was padded
class alignas(64) MonitorXMwaitXLockable
{
private:
uint32_t m_eventFlag; // the current event flag, interlocks are used on it for thread safety
uint32_t m_owningThread;
char unusedForceSizeBlock[56]; // force size to be 64 bytes
public:
/// The UserSemaphoreLockable cannot be copied
/// The MonitorXMwaitXLockable cannot be copied
MonitorXMwaitXLockable(const MonitorXMwaitXLockable&) = delete;
MonitorXMwaitXLockable& operator=(const MonitorXMwaitXLockable&) = delete;
MonitorXMwaitXLockable(bool initialState = false) : m_eventFlag(static_cast<uint32_t> (initialState ? 1 : 0)), m_owningThread(0), unusedForceSizeBlock{ } { }
MonitorXMwaitXLockable(bool initialState = false) noexcept : m_eventFlag(initialState ? 1u : 0), m_owningThread(0) {}
MonitorXMwaitXLockable(MonitorXMwaitXLockable&& rhs) = default;
~MonitorXMwaitXLockable() { }
@ -334,78 +406,5 @@ namespace ATG
}
};
#pragma warning (pop)
#endif // !__clang__ || __MWAITX__
//////////////////////////////////////////////////////////////////////////
///
/// Event object that attempts to stay at user level as much as possible
/// The object will only go to kernel mode if there is actually a thread waiting on the event
/// This allows for the maximum performance.
/// Interfaces follow the C++11 TimeLockable concept
/// The template parameter on manual reset is used to allow the compiler to optimize out the conditional
///
//////////////////////////////////////////////////////////////////////////
template<bool threadOwner>
class UserBarrier
{
private:
std::atomic<uint64_t> m_barrierValue;
uint64_t m_initialValue;
UserEventLockable<true> m_blockEvent;
uint32_t m_threadOwnerID;
public:
/// The UserBarrier cannot be copied
UserBarrier(const UserBarrier&) = delete;
UserBarrier& operator=(const UserBarrier&) = delete;
UserBarrier(uint64_t initialValue = 1) : m_barrierValue(initialValue), m_initialValue(initialValue), m_blockEvent(false), m_threadOwnerID(0) { }
UserBarrier(UserBarrier&& rhs) = default;
~UserBarrier() { }
void clearOwner() { m_threadOwnerID = 0; }
bool enterBarrier(bool block = false)
{
assert(m_barrierValue != 0);
if (threadOwner)
{
if (m_threadOwnerID == 0)
m_threadOwnerID = GetCurrentThreadId();
}
uint64_t myValue = m_barrierValue.fetch_sub(1);
if (myValue == 1)
{
m_blockEvent.SetEvent();
return true;
}
else if (block)
{
m_blockEvent.lock();
}
else
{
while (m_barrierValue.load() != 0);
}
return false;
}
bool reset() { return reset(m_initialValue); }
bool reset(uint64_t newValue)
{
if (threadOwner)
{
if (m_threadOwnerID != GetCurrentThreadId())
{
if (InterlockedCompareExchange(&m_threadOwnerID, GetCurrentThreadId(), 0) != 0)
return false;
}
}
m_initialValue = newValue;
m_barrierValue = newValue;
m_blockEvent.SetEvent();
m_blockEvent.ResetEvent();
return true;
}
};
#endif
}

Просмотреть файл

@ -76,7 +76,12 @@ struct CD3DX12_VIEWPORT : public D3D12_VIEWPORT
FLOAT minDepth = D3D12_MIN_DEPTH,
FLOAT maxDepth = D3D12_MAX_DEPTH ) noexcept
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pResource->GetDesc(&tmpDesc);
#endif
const UINT64 SubresourceWidth = Desc.Width >> mipSlice;
const UINT64 SubresourceHeight = Desc.Height >> mipSlice;
switch (Desc.Dimension)
@ -2040,7 +2045,12 @@ inline UINT64 GetRequiredIntermediateSize(
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources) noexcept
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
UINT64 RequiredSize = 0;
ID3D12Device* pDevice = nullptr;
@ -2066,8 +2076,14 @@ inline UINT64 UpdateSubresources(
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) noexcept
{
// Minor validation
#if defined(_MSC_VER) || !defined(_WIN32)
const auto IntermediateDesc = pIntermediate->GetDesc();
const auto DestinationDesc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc1, tmpDesc2;
const auto& IntermediateDesc = *pIntermediate->GetDesc(&tmpDesc1);
const auto& DestinationDesc = *pDestinationResource->GetDesc(&tmpDesc2);
#endif
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > SIZE_T(-1) ||
@ -2125,8 +2141,14 @@ inline UINT64 UpdateSubresources(
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_INFO* pSrcData) noexcept
{
// Minor validation
#if defined(_MSC_VER) || !defined(_WIN32)
const auto IntermediateDesc = pIntermediate->GetDesc();
const auto DestinationDesc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc1, tmpDesc2;
const auto& IntermediateDesc = *pIntermediate->GetDesc(&tmpDesc1);
const auto& DestinationDesc = *pDestinationResource->GetDesc(&tmpDesc2);
#endif
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > SIZE_T(-1) ||
@ -2194,7 +2216,12 @@ inline UINT64 UpdateSubresources(
auto pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
auto pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
@ -2232,7 +2259,12 @@ inline UINT64 UpdateSubresources(
auto pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
auto pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
@ -2260,7 +2292,12 @@ inline UINT64 UpdateSubresources(
UINT NumRows[MaxSubresources];
UINT64 RowSizesInBytes[MaxSubresources];
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize);
@ -2287,7 +2324,12 @@ inline UINT64 UpdateSubresources(
UINT NumRows[MaxSubresources];
UINT64 RowSizesInBytes[MaxSubresources];
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize);
@ -4071,20 +4113,20 @@ public:
D3D12_BARRIER_SUBRESOURCE_RANGE{ Subresource, 0, 0, 0, 0, 0 }
{}
CD3DX12_BARRIER_SUBRESOURCE_RANGE(
UINT FirstMipLevel,
UINT NumMips,
UINT FirstArraySlice,
UINT NumArraySlices,
UINT FirstPlane = 0,
UINT NumPlanes = 1) noexcept :
UINT firstMipLevel,
UINT numMips,
UINT firstArraySlice,
UINT numArraySlices,
UINT firstPlane = 0,
UINT numPlanes = 1) noexcept :
D3D12_BARRIER_SUBRESOURCE_RANGE
{
FirstMipLevel,
NumMips,
FirstArraySlice,
NumArraySlices,
FirstPlane,
NumPlanes
firstMipLevel,
numMips,
firstArraySlice,
numArraySlices,
firstPlane,
numPlanes
}
{}
};

Просмотреть файл

@ -45,6 +45,7 @@ using namespace ATG;
class ATGTelemetry
{
public:
bool m_bHCInitialized{ false };
~ATGTelemetry()
{
#if _GAMING_XBOX
@ -56,6 +57,14 @@ public:
#endif
}
void Cleanup()
{
if (m_bHCInitialized)
{
HCCleanup();
}
}
void SendTelemetry()
{
#if _GAMING_XBOX
@ -86,6 +95,7 @@ private:
{
return;
}
m_bHCInitialized = true;
auto *async = new XAsyncBlock{};
async->queue = nullptr;
@ -464,4 +474,13 @@ void ATG::SendLaunchTelemetry()
s_atgTelem->SendTelemetry();
}
void ATG::CleanupTelemetry()
{
if (s_atgTelem)
{
s_atgTelem->Cleanup();
}
s_atgTelem = nullptr;
}
#endif

Просмотреть файл

@ -20,8 +20,10 @@ namespace ATG
#ifdef ATG_ENABLE_TELEMETRY
// Sends sample launch telemetry
void SendLaunchTelemetry();
void CleanupTelemetry();
#else
void SendLaunchTelemetry() {};
void CleanupTelemetry() {};
#endif
}
}

Просмотреть файл

@ -822,9 +822,63 @@ void SoundEffectInstanceBase::Apply3D(const X3DAUDIO_LISTENER& listener, const X
//======================================================================================
// AudioEmitter helper
// AudioListener/Emitter helpers
//======================================================================================
namespace
{
inline bool IsValid(const X3DAUDIO_CONE& cone) noexcept
{
// These match the validation ranges in X3DAudio.
if (cone.InnerAngle < 0.f || cone.InnerAngle > X3DAUDIO_2PI)
return false;
if (cone.OuterAngle < 0.f || cone.OuterAngle > X3DAUDIO_2PI)
return false;
if (cone.InnerAngle > cone.OuterAngle)
return false;
if (cone.InnerVolume < 0.f || cone.InnerVolume > 2.f)
return false;
if (cone.OuterVolume < 0.f || cone.OuterVolume > 2.f)
return false;
if (cone.InnerLPF < 0.f || cone.InnerLPF > 1.f)
return false;
if (cone.OuterLPF < 0.f || cone.OuterLPF > 1.f)
return false;
if (cone.InnerReverb < 0.f || cone.InnerReverb > 2.f)
return false;
if (cone.OuterReverb < 0.f || cone.OuterReverb > 2.f)
return false;
return true;
}
}
void AudioListener::SetCone(const X3DAUDIO_CONE& listenerCone)
{
if (!::IsValid(listenerCone))
throw std::invalid_argument("X3DAUDIO_CONE values out of range");
ListenerCone = listenerCone;
pCone = &ListenerCone;
}
void AudioEmitter::SetCone(const X3DAUDIO_CONE& emitterCone)
{
if (!::IsValid(emitterCone))
throw std::invalid_argument("X3DAUDIO_CONE values out of range");
EmitterCone = emitterCone;
pCone = &EmitterCone;
}
namespace
{
// **Note these constants came from xact3d3.h in the legacy DirectX SDK**
@ -891,3 +945,17 @@ void AudioEmitter::EnableDefaultMultiChannel(unsigned int channels, float radius
memset(EmitterAzimuths, 0, sizeof(float) * size_t(channels));
}
}
namespace
{
// **Note these match the defaults from xact3d3.h in the legacy DirectX SDK**
constexpr X3DAUDIO_DISTANCE_CURVE_POINT c_defaultCurvePoints[2] = { { 0.0f, 1.0f }, { 1.0f, 1.0f } };
constexpr X3DAUDIO_DISTANCE_CURVE c_defaultCurve = { const_cast<X3DAUDIO_DISTANCE_CURVE_POINT*>(c_defaultCurvePoints), 2 };
}
void AudioEmitter::EnableDefaultCurves() noexcept
{
pVolumeCurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&c_defaultCurve);
pLFECurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&c_defaultCurve);
pLPFDirectCurve = pLPFReverbCurve = pReverbCurve = nullptr;
}

Просмотреть файл

@ -435,6 +435,7 @@
<ConformanceMode>true</ConformanceMode>
<AdditionalOptions>/Zc:__cplusplus /ZH:SHA_256 %(AdditionalOptions)</AdditionalOptions>
<ExternalWarningLevel>Level4</ExternalWarningLevel>
<GuardEHContMetadata>true</GuardEHContMetadata>
</ClCompile>
<FXCompile>
<ShaderModel>6.0</ShaderModel>
@ -464,6 +465,7 @@
<ConformanceMode>true</ConformanceMode>
<AdditionalOptions>/Zc:__cplusplus /ZH:SHA_256 %(AdditionalOptions)</AdditionalOptions>
<ExternalWarningLevel>Level4</ExternalWarningLevel>
<GuardEHContMetadata>true</GuardEHContMetadata>
</ClCompile>
<FXCompile>
<ShaderModel>6.0</ShaderModel>

Просмотреть файл

@ -113,6 +113,7 @@
<ConformanceMode>true</ConformanceMode>
<AdditionalOptions>/Zc:__cplusplus /ZH:SHA_256 %(AdditionalOptions)</AdditionalOptions>
<ExternalWarningLevel>Level4</ExternalWarningLevel>
<GuardEHContMetadata>true</GuardEHContMetadata>
</ClCompile>
<FXCompile>
<ShaderModel>6.0</ShaderModel>
@ -142,6 +143,7 @@
<ConformanceMode>true</ConformanceMode>
<AdditionalOptions>/Zc:__cplusplus /ZH:SHA_256 %(AdditionalOptions)</AdditionalOptions>
<ExternalWarningLevel>Level4</ExternalWarningLevel>
<GuardEHContMetadata>true</GuardEHContMetadata>
</ClCompile>
<FXCompile>
<ShaderModel>6.0</ShaderModel>

Просмотреть файл

@ -434,10 +434,12 @@ namespace DirectX
//----------------------------------------------------------------------------------
struct AudioListener : public X3DAUDIO_LISTENER
{
AudioListener() noexcept
{
memset(this, 0, sizeof(X3DAUDIO_LISTENER));
X3DAUDIO_CONE ListenerCone;
AudioListener() noexcept :
X3DAUDIO_LISTENER{},
ListenerCone{}
{
OrientFront.z = -1.f;
OrientTop.y = 1.f;
@ -486,8 +488,8 @@ namespace DirectX
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up);
}
// Updates velocity and orientation by tracking changes in position over time.
void XM_CALLCONV Update(FXMVECTOR newPos, XMVECTOR upDir, float dt) noexcept
// Updates velocity and orientation by tracking changes in position over time...
{
if (dt > 0.f)
{
@ -511,19 +513,27 @@ namespace DirectX
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), newPos);
}
}
void __cdecl SetOmnidirectional() noexcept
{
pCone = nullptr;
}
void __cdecl SetCone(const X3DAUDIO_CONE& listenerCone);
};
//----------------------------------------------------------------------------------
struct AudioEmitter : public X3DAUDIO_EMITTER
{
float EmitterAzimuths[XAUDIO2_MAX_AUDIO_CHANNELS];
X3DAUDIO_CONE EmitterCone;
float EmitterAzimuths[XAUDIO2_MAX_AUDIO_CHANNELS];
AudioEmitter() noexcept :
X3DAUDIO_EMITTER{},
EmitterCone{},
EmitterAzimuths{}
{
memset(this, 0, sizeof(X3DAUDIO_EMITTER));
OrientFront.z = -1.f;
OrientTop.y =
@ -580,8 +590,8 @@ namespace DirectX
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up);
}
// Updates velocity and orientation by tracking changes in position over time.
void XM_CALLCONV Update(FXMVECTOR newPos, XMVECTOR upDir, float dt) noexcept
// Updates velocity and orientation by tracking changes in position over time...
{
if (dt > 0.f)
{
@ -606,7 +616,19 @@ namespace DirectX
}
}
void __cdecl SetOmnidirectional() noexcept
{
pCone = nullptr;
}
// Only used for single-channel emitters.
void __cdecl SetCone(const X3DAUDIO_CONE& emitterCone);
// Set multi-channel emitter azimuths based on speaker configuration geometry.
void __cdecl EnableDefaultMultiChannel(unsigned int channels, float radius = 1.f);
// Set default volume, LFE, LPF, and reverb curves.
void __cdecl EnableDefaultCurves() noexcept;
};

Просмотреть файл

@ -25,71 +25,74 @@
namespace DirectX
{
class CommonStates
inline namespace DX12
{
public:
explicit CommonStates(_In_ ID3D12Device* device);
CommonStates(CommonStates&&) noexcept;
CommonStates& operator = (CommonStates&&) noexcept;
CommonStates(const CommonStates&) = delete;
CommonStates& operator = (const CommonStates&) = delete;
virtual ~CommonStates();
// Blend states.
static const D3D12_BLEND_DESC Opaque;
static const D3D12_BLEND_DESC AlphaBlend;
static const D3D12_BLEND_DESC Additive;
static const D3D12_BLEND_DESC NonPremultiplied;
// Depth stencil states.
static const D3D12_DEPTH_STENCIL_DESC DepthNone;
static const D3D12_DEPTH_STENCIL_DESC DepthDefault;
static const D3D12_DEPTH_STENCIL_DESC DepthRead;
static const D3D12_DEPTH_STENCIL_DESC DepthReverseZ;
static const D3D12_DEPTH_STENCIL_DESC DepthReadReverseZ;
// Rasterizer states.
static const D3D12_RASTERIZER_DESC CullNone;
static const D3D12_RASTERIZER_DESC CullClockwise;
static const D3D12_RASTERIZER_DESC CullCounterClockwise;
static const D3D12_RASTERIZER_DESC Wireframe;
// Static sampler states.
static const D3D12_STATIC_SAMPLER_DESC StaticPointWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticPointClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticLinearWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticLinearClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
// Sampler states.
D3D12_GPU_DESCRIPTOR_HANDLE PointWrap() const;
D3D12_GPU_DESCRIPTOR_HANDLE PointClamp() const;
D3D12_GPU_DESCRIPTOR_HANDLE LinearWrap() const;
D3D12_GPU_DESCRIPTOR_HANDLE LinearClamp() const;
D3D12_GPU_DESCRIPTOR_HANDLE AnisotropicWrap() const;
D3D12_GPU_DESCRIPTOR_HANDLE AnisotropicClamp() const;
// These index into the heap returned by SamplerDescriptorHeap
enum class SamplerIndex
class CommonStates
{
PointWrap,
PointClamp,
LinearWrap,
LinearClamp,
AnisotropicWrap,
AnisotropicClamp,
Count
public:
explicit CommonStates(_In_ ID3D12Device* device);
CommonStates(CommonStates&&) noexcept;
CommonStates& operator = (CommonStates&&) noexcept;
CommonStates(const CommonStates&) = delete;
CommonStates& operator = (const CommonStates&) = delete;
virtual ~CommonStates();
// Blend states.
static const D3D12_BLEND_DESC Opaque;
static const D3D12_BLEND_DESC AlphaBlend;
static const D3D12_BLEND_DESC Additive;
static const D3D12_BLEND_DESC NonPremultiplied;
// Depth stencil states.
static const D3D12_DEPTH_STENCIL_DESC DepthNone;
static const D3D12_DEPTH_STENCIL_DESC DepthDefault;
static const D3D12_DEPTH_STENCIL_DESC DepthRead;
static const D3D12_DEPTH_STENCIL_DESC DepthReverseZ;
static const D3D12_DEPTH_STENCIL_DESC DepthReadReverseZ;
// Rasterizer states.
static const D3D12_RASTERIZER_DESC CullNone;
static const D3D12_RASTERIZER_DESC CullClockwise;
static const D3D12_RASTERIZER_DESC CullCounterClockwise;
static const D3D12_RASTERIZER_DESC Wireframe;
// Static sampler states.
static const D3D12_STATIC_SAMPLER_DESC StaticPointWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticPointClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticLinearWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticLinearClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicWrap(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
static const D3D12_STATIC_SAMPLER_DESC StaticAnisotropicClamp(unsigned int shaderRegister, D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, unsigned int registerSpace = 0) noexcept;
// Sampler states.
D3D12_GPU_DESCRIPTOR_HANDLE PointWrap() const;
D3D12_GPU_DESCRIPTOR_HANDLE PointClamp() const;
D3D12_GPU_DESCRIPTOR_HANDLE LinearWrap() const;
D3D12_GPU_DESCRIPTOR_HANDLE LinearClamp() const;
D3D12_GPU_DESCRIPTOR_HANDLE AnisotropicWrap() const;
D3D12_GPU_DESCRIPTOR_HANDLE AnisotropicClamp() const;
// These index into the heap returned by SamplerDescriptorHeap
enum class SamplerIndex
{
PointWrap,
PointClamp,
LinearWrap,
LinearClamp,
AnisotropicWrap,
AnisotropicClamp,
Count
};
ID3D12DescriptorHeap* Heap() const noexcept;
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
ID3D12DescriptorHeap* Heap() const noexcept;
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
}

Просмотреть файл

@ -48,13 +48,17 @@ namespace DirectX
};
#endif
enum DDS_LOADER_FLAGS : uint32_t
inline namespace DX12
{
DDS_LOADER_DEFAULT = 0,
DDS_LOADER_FORCE_SRGB = 0x1,
DDS_LOADER_MIP_AUTOGEN = 0x8,
DDS_LOADER_MIP_RESERVE = 0x10,
};
enum DDS_LOADER_FLAGS : uint32_t
{
DDS_LOADER_DEFAULT = 0,
DDS_LOADER_FORCE_SRGB = 0x1,
DDS_LOADER_IGNORE_SRGB = 0x2,
DDS_LOADER_MIP_AUTOGEN = 0x8,
DDS_LOADER_MIP_RESERVE = 0x10,
};
}
// Standard version
HRESULT __cdecl LoadDDSTextureFromMemory(
@ -153,7 +157,10 @@ namespace DirectX
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#endif
DEFINE_ENUM_FLAG_OPERATORS(DDS_LOADER_FLAGS);
inline namespace DX12
{
DEFINE_ENUM_FLAG_OPERATORS(DDS_LOADER_FLAGS);
}
#ifdef __clang__
#pragma clang diagnostic pop

Просмотреть файл

@ -139,7 +139,12 @@ namespace DirectX
// Helper for obtaining texture size
inline XMUINT2 GetTextureSize(_In_ ID3D12Resource* tex) noexcept
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto desc = tex->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& desc = *tex->GetDesc(&tmpDesc);
#endif
return XMUINT2(static_cast<uint32_t>(desc.Width), static_cast<uint32_t>(desc.Height));
}
@ -281,32 +286,35 @@ namespace DirectX
std::vector<D3D12_RESOURCE_BARRIER> mBarriers;
};
// Helper to check for power-of-2
template<typename T>
constexpr bool IsPowerOf2(T x) noexcept { return ((x != 0) && !(x & (x - 1))); }
// Helpers for aligning values by a power of 2
template<typename T>
inline T AlignDown(T size, size_t alignment) noexcept
inline namespace DX12
{
if (alignment > 0)
{
assert(((alignment - 1) & alignment) == 0);
auto mask = static_cast<T>(alignment - 1);
return size & ~mask;
}
return size;
}
// Helper to check for power-of-2
template<typename T>
constexpr bool IsPowerOf2(T x) noexcept { return ((x != 0) && !(x & (x - 1))); }
template<typename T>
inline T AlignUp(T size, size_t alignment) noexcept
{
if (alignment > 0)
// Helpers for aligning values by a power of 2
template<typename T>
inline T AlignDown(T size, size_t alignment) noexcept
{
assert(((alignment - 1) & alignment) == 0);
auto mask = static_cast<T>(alignment - 1);
return (size + mask) & ~mask;
if (alignment > 0)
{
assert(((alignment - 1) & alignment) == 0);
auto mask = static_cast<T>(alignment - 1);
return size & ~mask;
}
return size;
}
template<typename T>
inline T AlignUp(T size, size_t alignment) noexcept
{
if (alignment > 0)
{
assert(((alignment - 1) & alignment) == 0);
auto mask = static_cast<T>(alignment - 1);
return (size + mask) & ~mask;
}
return size;
}
return size;
}
}

Просмотреть файл

@ -67,6 +67,7 @@ namespace DirectX
const D3D12_SHADER_BYTECODE& pixelShader,
_Outptr_ ID3D12PipelineState** pPipelineState) const;
#if defined(_MSC_VER) || !defined(_WIN32)
D3D12_GRAPHICS_PIPELINE_STATE_DESC GetDesc() const noexcept
{
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
@ -84,6 +85,28 @@ namespace DirectX
psoDesc.NodeMask = renderTargetState.nodeMask;
return psoDesc;
}
#else
D3D12_GRAPHICS_PIPELINE_STATE_DESC* GetDesc(_Out_ D3D12_GRAPHICS_PIPELINE_STATE_DESC* psoDesc) const noexcept
{
if (!psoDesc)
return nullptr;
*psoDesc = {};
psoDesc->BlendState = blendDesc;
psoDesc->SampleMask = renderTargetState.sampleMask;
psoDesc->RasterizerState = rasterizerDesc;
psoDesc->DepthStencilState = depthStencilDesc;
psoDesc->InputLayout = inputLayout;
psoDesc->IBStripCutValue = stripCutValue;
psoDesc->PrimitiveTopologyType = primitiveTopology;
psoDesc->NumRenderTargets = renderTargetState.numRenderTargets;
memcpy(psoDesc->RTVFormats, renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT);
psoDesc->DSVFormat = renderTargetState.dsvFormat;
psoDesc->SampleDesc = renderTargetState.sampleDesc;
psoDesc->NodeMask = renderTargetState.nodeMask;
return psoDesc;
}
#endif
uint32_t ComputeHash() const noexcept;

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -19,76 +19,80 @@
namespace DirectX
{
class IEffect;
class ResourceUploadBatch;
class GeometricPrimitive
inline namespace DX12
{
public:
GeometricPrimitive(GeometricPrimitive&&) = default;
GeometricPrimitive& operator= (GeometricPrimitive&&) = default;
class IEffect;
GeometricPrimitive(GeometricPrimitive const&) = delete;
GeometricPrimitive& operator= (GeometricPrimitive const&) = delete;
class GeometricPrimitive
{
public:
GeometricPrimitive(GeometricPrimitive&&) = default;
GeometricPrimitive& operator= (GeometricPrimitive&&) = default;
virtual ~GeometricPrimitive();
GeometricPrimitive(GeometricPrimitive const&) = delete;
GeometricPrimitive& operator= (GeometricPrimitive const&) = delete;
using VertexType = VertexPositionNormalTexture;
using VertexCollection = std::vector<VertexType>;
using IndexCollection = std::vector<uint16_t>;
virtual ~GeometricPrimitive();
// Factory methods.
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCube(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateBox(const XMFLOAT3& size, bool rhcoords = true, bool invertn = false, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateSphere(float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateGeoSphere(float diameter = 1, size_t tessellation = 3, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCylinder(float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCone(float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTorus(float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTetrahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateOctahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateDodecahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateIcosahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTeapot(float size = 1, size_t tessellation = 8, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCustom(const VertexCollection& vertices, const IndexCollection& indices, _In_opt_ ID3D12Device* device = nullptr);
using VertexType = VertexPositionNormalTexture;
using VertexCollection = std::vector<VertexType>;
using IndexCollection = std::vector<uint16_t>;
static void __cdecl CreateCube(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateBox(VertexCollection& vertices, IndexCollection& indices, const XMFLOAT3& size, bool rhcoords = true, bool invertn = false);
static void __cdecl CreateSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false);
static void __cdecl CreateGeoSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 3, bool rhcoords = true);
static void __cdecl CreateCylinder(VertexCollection& vertices, IndexCollection& indices, float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateCone(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateTorus(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateTetrahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateOctahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateDodecahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateIcosahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateTeapot(VertexCollection& vertices, IndexCollection& indices, float size = 1, size_t tessellation = 8, bool rhcoords = true);
// Factory methods.
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCube(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateBox(const XMFLOAT3& size, bool rhcoords = true, bool invertn = false, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateSphere(float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateGeoSphere(float diameter = 1, size_t tessellation = 3, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCylinder(float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCone(float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTorus(float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTetrahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateOctahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateDodecahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateIcosahedron(float size = 1, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTeapot(float size = 1, size_t tessellation = 8, bool rhcoords = true, _In_opt_ ID3D12Device* device = nullptr);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCustom(const VertexCollection& vertices, const IndexCollection& indices, _In_opt_ ID3D12Device* device = nullptr);
// Load VB/IB resources for static geometry.
void __cdecl LoadStaticBuffers(
_In_ ID3D12Device* device,
ResourceUploadBatch& resourceUploadBatch);
static void __cdecl CreateCube(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateBox(VertexCollection& vertices, IndexCollection& indices, const XMFLOAT3& size, bool rhcoords = true, bool invertn = false);
static void __cdecl CreateSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false);
static void __cdecl CreateGeoSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 3, bool rhcoords = true);
static void __cdecl CreateCylinder(VertexCollection& vertices, IndexCollection& indices, float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateCone(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateTorus(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateTetrahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateOctahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateDodecahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateIcosahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateTeapot(VertexCollection& vertices, IndexCollection& indices, float size = 1, size_t tessellation = 8, bool rhcoords = true);
// Transition VB/IB resources for static geometry.
void __cdecl Transition(
_In_ ID3D12GraphicsCommandList* commandList,
D3D12_RESOURCE_STATES stateBeforeVB,
D3D12_RESOURCE_STATES stateAfterVB,
D3D12_RESOURCE_STATES stateBeforeIB,
D3D12_RESOURCE_STATES stateAfterIB);
// Load VB/IB resources for static geometry.
void __cdecl LoadStaticBuffers(
_In_ ID3D12Device* device,
ResourceUploadBatch& resourceUploadBatch);
// Draw the primitive.
void __cdecl Draw(_In_ ID3D12GraphicsCommandList* commandList) const;
// Transition VB/IB resources for static geometry.
void __cdecl Transition(
_In_ ID3D12GraphicsCommandList* commandList,
D3D12_RESOURCE_STATES stateBeforeVB,
D3D12_RESOURCE_STATES stateAfterVB,
D3D12_RESOURCE_STATES stateBeforeIB,
D3D12_RESOURCE_STATES stateAfterIB);
void __cdecl DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation = 0) const;
// Draw the primitive.
void __cdecl Draw(_In_ ID3D12GraphicsCommandList* commandList) const;
private:
GeometricPrimitive() noexcept(false);
void __cdecl DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation = 0) const;
// Private implementation.
class Impl;
private:
GeometricPrimitive() noexcept(false);
std::unique_ptr<Impl> pImpl;
};
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
}

Просмотреть файл

@ -29,155 +29,158 @@ namespace DirectX
{
class LinearAllocatorPage;
inline namespace DX12
{
// Works a little like a smart pointer. The memory will only be fenced by the GPU once the pointer
// has been invalidated or the user explicitly marks it for fencing.
class GraphicsResource
{
public:
GraphicsResource() noexcept;
GraphicsResource(
_In_ LinearAllocatorPage* page,
_In_ D3D12_GPU_VIRTUAL_ADDRESS gpuAddress,
_In_ ID3D12Resource* resource,
_In_ void* memory,
_In_ size_t offset,
_In_ size_t size) noexcept;
GraphicsResource(GraphicsResource&& other) noexcept;
GraphicsResource&& operator= (GraphicsResource&&) noexcept;
GraphicsResource(const GraphicsResource&) = delete;
GraphicsResource& operator= (const GraphicsResource&) = delete;
~GraphicsResource();
D3D12_GPU_VIRTUAL_ADDRESS GpuAddress() const noexcept { return mGpuAddress; }
ID3D12Resource* Resource() const noexcept { return mResource; }
void* Memory() const noexcept { return mMemory; }
size_t ResourceOffset() const noexcept { return mBufferOffset; }
size_t Size() const noexcept { return mSize; }
explicit operator bool() const noexcept { return mResource != nullptr; }
// Clear the pointer. Using operator -> will produce bad results.
void __cdecl Reset() noexcept;
void __cdecl Reset(GraphicsResource&&) noexcept;
private:
LinearAllocatorPage* mPage;
D3D12_GPU_VIRTUAL_ADDRESS mGpuAddress;
ID3D12Resource* mResource;
void* mMemory;
size_t mBufferOffset;
size_t mSize;
};
class SharedGraphicsResource
{
public:
SharedGraphicsResource() noexcept;
SharedGraphicsResource(SharedGraphicsResource&&) noexcept;
SharedGraphicsResource&& operator= (SharedGraphicsResource&&) noexcept;
SharedGraphicsResource(GraphicsResource&&);
SharedGraphicsResource&& operator= (GraphicsResource&&);
SharedGraphicsResource(const SharedGraphicsResource&) noexcept;
SharedGraphicsResource& operator= (const SharedGraphicsResource&) noexcept;
SharedGraphicsResource(const GraphicsResource&) = delete;
SharedGraphicsResource& operator= (const GraphicsResource&) = delete;
~SharedGraphicsResource();
D3D12_GPU_VIRTUAL_ADDRESS GpuAddress() const noexcept { return mSharedResource->GpuAddress(); }
ID3D12Resource* Resource() const noexcept { return mSharedResource->Resource(); }
void* Memory() const noexcept { return mSharedResource->Memory(); }
size_t ResourceOffset() const noexcept { return mSharedResource->ResourceOffset(); }
size_t Size() const noexcept { return mSharedResource->Size(); }
explicit operator bool() const noexcept { return mSharedResource != nullptr; }
bool operator == (const SharedGraphicsResource& other) const noexcept { return mSharedResource.get() == other.mSharedResource.get(); }
bool operator != (const SharedGraphicsResource& other) const noexcept { return mSharedResource.get() != other.mSharedResource.get(); }
// Clear the pointer. Using operator -> will produce bad results.
void __cdecl Reset() noexcept;
void __cdecl Reset(GraphicsResource&&);
void __cdecl Reset(SharedGraphicsResource&&) noexcept;
void __cdecl Reset(const SharedGraphicsResource& resource) noexcept;
private:
std::shared_ptr<GraphicsResource> mSharedResource;
};
//----------------------------------------------------------------------------------
struct GraphicsMemoryStatistics
{
size_t committedMemory; // Bytes of memory currently committed/in-flight
size_t totalMemory; // Total bytes of memory used by the allocators
size_t totalPages; // Total page count
size_t peakCommitedMemory; // Peak commited memory value since last reset
size_t peakTotalMemory; // Peak total bytes
size_t peakTotalPages; // Peak total page count
};
//----------------------------------------------------------------------------------
class GraphicsMemory
{
public:
explicit GraphicsMemory(_In_ ID3D12Device* device);
GraphicsMemory(GraphicsMemory&&) noexcept;
GraphicsMemory& operator= (GraphicsMemory&&) noexcept;
GraphicsMemory(GraphicsMemory const&) = delete;
GraphicsMemory& operator=(GraphicsMemory const&) = delete;
virtual ~GraphicsMemory();
// Make sure to keep the GraphicsResource handle alive as long as you need to access
// the memory on the CPU. For example, do not simply cache GpuAddress() and discard
// the GraphicsResource object, or your memory may be overwritten later.
GraphicsResource __cdecl Allocate(size_t size, size_t alignment = 16);
// Special overload of Allocate that aligns to D3D12 constant buffer alignment requirements
template<typename T> GraphicsResource AllocateConstant()
class GraphicsResource
{
constexpr size_t alignment = D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT;
constexpr size_t alignedSize = (sizeof(T) + alignment - 1) & ~(alignment - 1);
return Allocate(alignedSize, alignment);
}
template<typename T> GraphicsResource AllocateConstant(const T& setData)
public:
GraphicsResource() noexcept;
GraphicsResource(
_In_ LinearAllocatorPage* page,
_In_ D3D12_GPU_VIRTUAL_ADDRESS gpuAddress,
_In_ ID3D12Resource* resource,
_In_ void* memory,
_In_ size_t offset,
_In_ size_t size) noexcept;
GraphicsResource(GraphicsResource&& other) noexcept;
GraphicsResource&& operator= (GraphicsResource&&) noexcept;
GraphicsResource(const GraphicsResource&) = delete;
GraphicsResource& operator= (const GraphicsResource&) = delete;
~GraphicsResource();
D3D12_GPU_VIRTUAL_ADDRESS GpuAddress() const noexcept { return mGpuAddress; }
ID3D12Resource* Resource() const noexcept { return mResource; }
void* Memory() const noexcept { return mMemory; }
size_t ResourceOffset() const noexcept { return mBufferOffset; }
size_t Size() const noexcept { return mSize; }
explicit operator bool() const noexcept { return mResource != nullptr; }
// Clear the pointer. Using operator -> will produce bad results.
void __cdecl Reset() noexcept;
void __cdecl Reset(GraphicsResource&&) noexcept;
private:
LinearAllocatorPage* mPage;
D3D12_GPU_VIRTUAL_ADDRESS mGpuAddress;
ID3D12Resource* mResource;
void* mMemory;
size_t mBufferOffset;
size_t mSize;
};
class SharedGraphicsResource
{
GraphicsResource alloc = AllocateConstant<T>();
memcpy(alloc.Memory(), &setData, sizeof(T));
return alloc;
}
public:
SharedGraphicsResource() noexcept;
// Submits all the pending one-shot memory to the GPU.
// The memory will be recycled once the GPU is done with it.
void __cdecl Commit(_In_ ID3D12CommandQueue* commandQueue);
SharedGraphicsResource(SharedGraphicsResource&&) noexcept;
SharedGraphicsResource&& operator= (SharedGraphicsResource&&) noexcept;
// This frees up any unused memory.
// If you want to make sure all memory is reclaimed, idle the GPU before calling this.
// It is not recommended that you call this unless absolutely necessary (e.g. your
// memory budget changes at run-time, or perhaps you're changing levels in your game.)
void __cdecl GarbageCollect();
SharedGraphicsResource(GraphicsResource&&);
SharedGraphicsResource&& operator= (GraphicsResource&&);
// Memory statistics
GraphicsMemoryStatistics __cdecl GetStatistics();
void __cdecl ResetStatistics();
SharedGraphicsResource(const SharedGraphicsResource&) noexcept;
SharedGraphicsResource& operator= (const SharedGraphicsResource&) noexcept;
// Singleton
// Should only use nullptr for single GPU scenarios; mGPU requires a specific device
static GraphicsMemory& __cdecl Get(_In_opt_ ID3D12Device* device = nullptr);
SharedGraphicsResource(const GraphicsResource&) = delete;
SharedGraphicsResource& operator= (const GraphicsResource&) = delete;
private:
// Private implementation.
class Impl;
~SharedGraphicsResource();
std::unique_ptr<Impl> pImpl;
};
D3D12_GPU_VIRTUAL_ADDRESS GpuAddress() const noexcept { return mSharedResource->GpuAddress(); }
ID3D12Resource* Resource() const noexcept { return mSharedResource->Resource(); }
void* Memory() const noexcept { return mSharedResource->Memory(); }
size_t ResourceOffset() const noexcept { return mSharedResource->ResourceOffset(); }
size_t Size() const noexcept { return mSharedResource->Size(); }
explicit operator bool() const noexcept { return mSharedResource != nullptr; }
bool operator == (const SharedGraphicsResource& other) const noexcept { return mSharedResource.get() == other.mSharedResource.get(); }
bool operator != (const SharedGraphicsResource& other) const noexcept { return mSharedResource.get() != other.mSharedResource.get(); }
// Clear the pointer. Using operator -> will produce bad results.
void __cdecl Reset() noexcept;
void __cdecl Reset(GraphicsResource&&);
void __cdecl Reset(SharedGraphicsResource&&) noexcept;
void __cdecl Reset(const SharedGraphicsResource& resource) noexcept;
private:
std::shared_ptr<GraphicsResource> mSharedResource;
};
//------------------------------------------------------------------------------
struct GraphicsMemoryStatistics
{
size_t committedMemory; // Bytes of memory currently committed/in-flight
size_t totalMemory; // Total bytes of memory used by the allocators
size_t totalPages; // Total page count
size_t peakCommitedMemory; // Peak commited memory value since last reset
size_t peakTotalMemory; // Peak total bytes
size_t peakTotalPages; // Peak total page count
};
//------------------------------------------------------------------------------
class GraphicsMemory
{
public:
explicit GraphicsMemory(_In_ ID3D12Device* device);
GraphicsMemory(GraphicsMemory&&) noexcept;
GraphicsMemory& operator= (GraphicsMemory&&) noexcept;
GraphicsMemory(GraphicsMemory const&) = delete;
GraphicsMemory& operator=(GraphicsMemory const&) = delete;
virtual ~GraphicsMemory();
// Make sure to keep the GraphicsResource handle alive as long as you need to access
// the memory on the CPU. For example, do not simply cache GpuAddress() and discard
// the GraphicsResource object, or your memory may be overwritten later.
GraphicsResource __cdecl Allocate(size_t size, size_t alignment = 16);
// Special overload of Allocate that aligns to D3D12 constant buffer alignment requirements
template<typename T> GraphicsResource AllocateConstant()
{
constexpr size_t alignment = D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT;
constexpr size_t alignedSize = (sizeof(T) + alignment - 1) & ~(alignment - 1);
return Allocate(alignedSize, alignment);
}
template<typename T> GraphicsResource AllocateConstant(const T& setData)
{
GraphicsResource alloc = AllocateConstant<T>();
memcpy(alloc.Memory(), &setData, sizeof(T));
return alloc;
}
// Submits all the pending one-shot memory to the GPU.
// The memory will be recycled once the GPU is done with it.
void __cdecl Commit(_In_ ID3D12CommandQueue* commandQueue);
// This frees up any unused memory.
// If you want to make sure all memory is reclaimed, idle the GPU before calling this.
// It is not recommended that you call this unless absolutely necessary (e.g. your
// memory budget changes at run-time, or perhaps you're changing levels in your game.)
void __cdecl GarbageCollect();
// Memory statistics
GraphicsMemoryStatistics __cdecl GetStatistics();
void __cdecl ResetStatistics();
// Singleton
// Should only use nullptr for single GPU scenarios; mGPU requires a specific device
static GraphicsMemory& __cdecl Get(_In_opt_ ID3D12Device* device = nullptr);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -29,186 +29,189 @@
namespace DirectX
{
//----------------------------------------------------------------------------------
// Abstract interface representing a post-process pass
class IPostProcess
inline namespace DX12
{
public:
virtual ~IPostProcess() = default;
IPostProcess(const IPostProcess&) = delete;
IPostProcess& operator=(const IPostProcess&) = delete;
virtual void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) = 0;
protected:
IPostProcess() = default;
IPostProcess(IPostProcess&&) = default;
IPostProcess& operator=(IPostProcess&&) = default;
};
//----------------------------------------------------------------------------------
// Basic post-process
class BasicPostProcess : public IPostProcess
{
public:
enum Effect : unsigned int
//------------------------------------------------------------------------------
// Abstract interface representing a post-process pass
class IPostProcess
{
Copy,
Monochrome,
Sepia,
DownScale_2x2,
DownScale_4x4,
GaussianBlur_5x5,
BloomExtract,
BloomBlur,
Effect_Max
public:
virtual ~IPostProcess() = default;
IPostProcess(const IPostProcess&) = delete;
IPostProcess& operator=(const IPostProcess&) = delete;
virtual void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) = 0;
protected:
IPostProcess() = default;
IPostProcess(IPostProcess&&) = default;
IPostProcess& operator=(IPostProcess&&) = default;
};
BasicPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx);
BasicPostProcess(BasicPostProcess&&) noexcept;
BasicPostProcess& operator= (BasicPostProcess&&) noexcept;
BasicPostProcess(BasicPostProcess const&) = delete;
BasicPostProcess& operator= (BasicPostProcess const&) = delete;
~BasicPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) override;
// Properties
void __cdecl SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, _In_opt_ ID3D12Resource* resource);
// Sets multiplier for GaussianBlur_5x5
void __cdecl SetGaussianParameter(float multiplier);
// Sets parameters for BloomExtract
void __cdecl SetBloomExtractParameter(float threshold);
// Sets parameters for BloomBlur
void __cdecl SetBloomBlurParameters(bool horizontal, float size, float brightness);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
// Dual-texure post-process
class DualPostProcess : public IPostProcess
{
public:
enum Effect : unsigned int
//------------------------------------------------------------------------------
// Basic post-process
class BasicPostProcess : public IPostProcess
{
Merge,
BloomCombine,
Effect_Max
public:
enum Effect : unsigned int
{
Copy,
Monochrome,
Sepia,
DownScale_2x2,
DownScale_4x4,
GaussianBlur_5x5,
BloomExtract,
BloomBlur,
Effect_Max
};
BasicPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx);
BasicPostProcess(BasicPostProcess&&) noexcept;
BasicPostProcess& operator= (BasicPostProcess&&) noexcept;
BasicPostProcess(BasicPostProcess const&) = delete;
BasicPostProcess& operator= (BasicPostProcess const&) = delete;
~BasicPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) override;
// Properties
void __cdecl SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, _In_opt_ ID3D12Resource* resource);
// Sets multiplier for GaussianBlur_5x5
void __cdecl SetGaussianParameter(float multiplier);
// Sets parameters for BloomExtract
void __cdecl SetBloomExtractParameter(float threshold);
// Sets parameters for BloomBlur
void __cdecl SetBloomBlurParameters(bool horizontal, float size, float brightness);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
DualPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx);
DualPostProcess(DualPostProcess&&) noexcept;
DualPostProcess& operator= (DualPostProcess&&) noexcept;
DualPostProcess(DualPostProcess const&) = delete;
DualPostProcess& operator= (DualPostProcess const&) = delete;
~DualPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) override;
// Properties
void __cdecl SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
void __cdecl SetSourceTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
// Sets parameters for Merge
void __cdecl SetMergeParameters(float weight1, float weight2);
// Sets parameters for BloomCombine
void __cdecl SetBloomCombineParameters(float bloom, float base, float bloomSaturation, float baseSaturation);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
// Tone-map post-process
class ToneMapPostProcess : public IPostProcess
{
public:
// Tone-mapping operator
enum Operator : unsigned int
//------------------------------------------------------------------------------
// Dual-texure post-process
class DualPostProcess : public IPostProcess
{
None, // Pass-through
Saturate, // Clamp [0,1]
Reinhard, // x/(1+x)
ACESFilmic,
Operator_Max
public:
enum Effect : unsigned int
{
Merge,
BloomCombine,
Effect_Max
};
DualPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState, Effect fx);
DualPostProcess(DualPostProcess&&) noexcept;
DualPostProcess& operator= (DualPostProcess&&) noexcept;
DualPostProcess(DualPostProcess const&) = delete;
DualPostProcess& operator= (DualPostProcess const&) = delete;
~DualPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) override;
// Properties
void __cdecl SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
void __cdecl SetSourceTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
// Sets parameters for Merge
void __cdecl SetMergeParameters(float weight1, float weight2);
// Sets parameters for BloomCombine
void __cdecl SetBloomCombineParameters(float bloom, float base, float bloomSaturation, float baseSaturation);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
// Electro-Optical Transfer Function (EOTF)
enum TransferFunction : unsigned int
//------------------------------------------------------------------------------
// Tone-map post-process
class ToneMapPostProcess : public IPostProcess
{
Linear, // Pass-through
SRGB, // sRGB (Rec.709 and approximate sRGB display curve)
ST2084, // HDR10 (Rec.2020 color primaries and ST.2084 display curve)
TransferFunction_Max
public:
// Tone-mapping operator
enum Operator : unsigned int
{
None, // Pass-through
Saturate, // Clamp [0,1]
Reinhard, // x/(1+x)
ACESFilmic,
Operator_Max
};
// Electro-Optical Transfer Function (EOTF)
enum TransferFunction : unsigned int
{
Linear, // Pass-through
SRGB, // sRGB (Rec.709 and approximate sRGB display curve)
ST2084, // HDR10 (Rec.2020 color primaries and ST.2084 display curve)
TransferFunction_Max
};
// Color Rotation Transform for HDR10
enum ColorPrimaryRotation : unsigned int
{
HDTV_to_UHDTV, // Rec.709 to Rec.2020
DCI_P3_D65_to_UHDTV, // DCI-P3-D65 (a.k.a Display P3 or P3D65) to Rec.2020
HDTV_to_DCI_P3_D65, // Rec.709 to DCI-P3-D65 (a.k.a Display P3 or P3D65)
};
ToneMapPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState,
Operator op, TransferFunction func
#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX)
, bool mrt = false
#endif
);
ToneMapPostProcess(ToneMapPostProcess&&) noexcept;
ToneMapPostProcess& operator= (ToneMapPostProcess&&) noexcept;
ToneMapPostProcess(ToneMapPostProcess const&) = delete;
ToneMapPostProcess& operator= (ToneMapPostProcess const&) = delete;
~ToneMapPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) override;
// Properties
void __cdecl SetHDRSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
// Sets the Color Rotation Transform for HDR10 signal output
void __cdecl SetColorRotation(ColorPrimaryRotation value);
void __cdecl SetColorRotation(CXMMATRIX value);
// Sets exposure value for LDR tonemap operators
void __cdecl SetExposure(float exposureValue);
// Sets ST.2084 parameter for how bright white should be in nits
void __cdecl SetST2084Parameter(float paperWhiteNits);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
// Color Rotation Transform for HDR10
enum ColorPrimaryRotation : unsigned int
{
HDTV_to_UHDTV, // Rec.709 to Rec.2020
DCI_P3_D65_to_UHDTV, // DCI-P3-D65 (a.k.a Display P3 or P3D65) to Rec.2020
HDTV_to_DCI_P3_D65, // Rec.709 to DCI-P3-D65 (a.k.a Display P3 or P3D65)
};
ToneMapPostProcess(_In_ ID3D12Device* device, const RenderTargetState& rtState,
Operator op, TransferFunction func
#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX)
, bool mrt = false
#endif
);
ToneMapPostProcess(ToneMapPostProcess&&) noexcept;
ToneMapPostProcess& operator= (ToneMapPostProcess&&) noexcept;
ToneMapPostProcess(ToneMapPostProcess const&) = delete;
ToneMapPostProcess& operator= (ToneMapPostProcess const&) = delete;
~ToneMapPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D12GraphicsCommandList* commandList) override;
// Properties
void __cdecl SetHDRSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
// Sets the Color Rotation Transform for HDR10 signal output
void __cdecl SetColorRotation(ColorPrimaryRotation value);
void __cdecl SetColorRotation(CXMMATRIX value);
// Sets exposure value for LDR tonemap operators
void __cdecl SetExposure(float exposureValue);
// Sets ST.2084 parameter for how bright white should be in nits
void __cdecl SetST2084Parameter(float paperWhiteNits);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
}

Просмотреть файл

@ -29,117 +29,119 @@
namespace DirectX
{
namespace Internal
inline namespace DX12
{
// Base class, not to be used directly: clients should access this via the derived PrimitiveBatch<T>.
class PrimitiveBatchBase
namespace Private
{
protected:
PrimitiveBatchBase(_In_ ID3D12Device* device, size_t maxIndices, size_t maxVertices, size_t vertexSize);
// Base class, not to be used directly: clients should access this via the derived PrimitiveBatch<T>.
class PrimitiveBatchBase
{
protected:
PrimitiveBatchBase(_In_ ID3D12Device* device, size_t maxIndices, size_t maxVertices, size_t vertexSize);
PrimitiveBatchBase(PrimitiveBatchBase&&) noexcept;
PrimitiveBatchBase& operator= (PrimitiveBatchBase&&) noexcept;
PrimitiveBatchBase(PrimitiveBatchBase&&) noexcept;
PrimitiveBatchBase& operator= (PrimitiveBatchBase&&) noexcept;
PrimitiveBatchBase(PrimitiveBatchBase const&) = delete;
PrimitiveBatchBase& operator= (PrimitiveBatchBase const&) = delete;
PrimitiveBatchBase(PrimitiveBatchBase const&) = delete;
PrimitiveBatchBase& operator= (PrimitiveBatchBase const&) = delete;
virtual ~PrimitiveBatchBase();
virtual ~PrimitiveBatchBase();
public:
// Begin/End a batch of primitive drawing operations.
void __cdecl Begin(_In_ ID3D12GraphicsCommandList* cmdList);
void __cdecl End();
protected:
// Internal, untyped drawing method.
void __cdecl Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isIndexed, _In_opt_count_(indexCount) uint16_t const* indices, size_t indexCount, size_t vertexCount, _Outptr_ void** pMappedVertices);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
// Template makes the API typesafe, eg. PrimitiveBatch<VertexPositionColor>.
template<typename TVertex>
class PrimitiveBatch : public Private::PrimitiveBatchBase
{
static constexpr size_t DefaultBatchSize = 4096;
public:
// Begin/End a batch of primitive drawing operations.
void __cdecl Begin(_In_ ID3D12GraphicsCommandList* cmdList);
void __cdecl End();
explicit PrimitiveBatch(_In_ ID3D12Device* device,
size_t maxIndices = DefaultBatchSize * 3,
size_t maxVertices = DefaultBatchSize)
: PrimitiveBatchBase(device, maxIndices, maxVertices, sizeof(TVertex))
{
}
protected:
// Internal, untyped drawing method.
void __cdecl Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isIndexed, _In_opt_count_(indexCount) uint16_t const* indices, size_t indexCount, size_t vertexCount, _Outptr_ void** pMappedVertices);
PrimitiveBatch(PrimitiveBatch&&) = default;
PrimitiveBatch& operator= (PrimitiveBatch&&) = default;
private:
// Private implementation.
class Impl;
PrimitiveBatch(PrimitiveBatch const&) = delete;
PrimitiveBatch& operator= (PrimitiveBatch const&) = delete;
std::unique_ptr<Impl> pImpl;
// Similar to the D3D9 API DrawPrimitiveUP.
void Draw(D3D_PRIMITIVE_TOPOLOGY topology, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount)
{
void* mappedVertices;
PrimitiveBatchBase::Draw(topology, false, nullptr, 0, vertexCount, &mappedVertices);
memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex));
}
// Similar to the D3D9 API DrawIndexedPrimitiveUP.
void DrawIndexed(D3D_PRIMITIVE_TOPOLOGY topology, _In_reads_(indexCount) uint16_t const* indices, size_t indexCount, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount)
{
void* mappedVertices;
PrimitiveBatchBase::Draw(topology, true, indices, indexCount, vertexCount, &mappedVertices);
memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex));
}
void DrawLine(TVertex const& v1, TVertex const& v2)
{
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_LINELIST, false, nullptr, 0, 2, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
}
void DrawTriangle(TVertex const& v1, TVertex const& v2, TVertex const& v3)
{
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, false, nullptr, 0, 3, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
mappedVertices[2] = v3;
}
void DrawQuad(TVertex const& v1, TVertex const& v2, TVertex const& v3, TVertex const& v4)
{
static const uint16_t quadIndices[] = { 0, 1, 2, 0, 2, 3 };
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, true, quadIndices, 6, 4, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
mappedVertices[2] = v3;
mappedVertices[3] = v4;
}
};
}
// Template makes the API typesafe, eg. PrimitiveBatch<VertexPositionColor>.
template<typename TVertex>
class PrimitiveBatch : public Internal::PrimitiveBatchBase
{
static constexpr size_t DefaultBatchSize = 4096;
public:
explicit PrimitiveBatch(_In_ ID3D12Device* device,
size_t maxIndices = DefaultBatchSize * 3,
size_t maxVertices = DefaultBatchSize)
: PrimitiveBatchBase(device, maxIndices, maxVertices, sizeof(TVertex))
{
}
PrimitiveBatch(PrimitiveBatch&&) = default;
PrimitiveBatch& operator= (PrimitiveBatch&&) = default;
PrimitiveBatch(PrimitiveBatch const&) = delete;
PrimitiveBatch& operator= (PrimitiveBatch const&) = delete;
// Similar to the D3D9 API DrawPrimitiveUP.
void Draw(D3D_PRIMITIVE_TOPOLOGY topology, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount)
{
void* mappedVertices;
PrimitiveBatchBase::Draw(topology, false, nullptr, 0, vertexCount, &mappedVertices);
memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex));
}
// Similar to the D3D9 API DrawIndexedPrimitiveUP.
void DrawIndexed(D3D_PRIMITIVE_TOPOLOGY topology, _In_reads_(indexCount) uint16_t const* indices, size_t indexCount, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount)
{
void* mappedVertices;
PrimitiveBatchBase::Draw(topology, true, indices, indexCount, vertexCount, &mappedVertices);
memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex));
}
void DrawLine(TVertex const& v1, TVertex const& v2)
{
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_LINELIST, false, nullptr, 0, 2, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
}
void DrawTriangle(TVertex const& v1, TVertex const& v2, TVertex const& v3)
{
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, false, nullptr, 0, 3, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
mappedVertices[2] = v3;
}
void DrawQuad(TVertex const& v1, TVertex const& v2, TVertex const& v3, TVertex const& v4)
{
static const uint16_t quadIndices[] = { 0, 1, 2, 0, 2, 3 };
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, true, quadIndices, 6, 4, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
mappedVertices[2] = v3;
mappedVertices[3] = v4;
}
};
}

Просмотреть файл

@ -37,118 +37,121 @@ namespace DirectX
{
class ResourceUploadBatch;
enum SpriteSortMode
inline namespace DX12
{
SpriteSortMode_Deferred,
SpriteSortMode_Immediate,
SpriteSortMode_Texture,
SpriteSortMode_BackToFront,
SpriteSortMode_FrontToBack,
};
enum SpriteEffects : uint32_t
{
SpriteEffects_None = 0,
SpriteEffects_FlipHorizontally = 1,
SpriteEffects_FlipVertically = 2,
SpriteEffects_FlipBoth = SpriteEffects_FlipHorizontally | SpriteEffects_FlipVertically,
};
class SpriteBatchPipelineStateDescription
{
public:
explicit SpriteBatchPipelineStateDescription(
const RenderTargetState& renderTarget,
_In_opt_ const D3D12_BLEND_DESC* blend = nullptr,
_In_opt_ const D3D12_DEPTH_STENCIL_DESC* depthStencil = nullptr,
_In_opt_ const D3D12_RASTERIZER_DESC* rasterizer = nullptr,
_In_opt_ const D3D12_GPU_DESCRIPTOR_HANDLE* isamplerDescriptor = nullptr) noexcept
:
blendDesc(blend ? *blend : s_DefaultBlendDesc),
depthStencilDesc(depthStencil ? *depthStencil : s_DefaultDepthStencilDesc),
rasterizerDesc(rasterizer ? *rasterizer : s_DefaultRasterizerDesc),
renderTargetState(renderTarget),
samplerDescriptor{},
customRootSignature(nullptr),
customVertexShader{},
customPixelShader{}
enum SpriteSortMode
{
if (isamplerDescriptor)
this->samplerDescriptor = *isamplerDescriptor;
}
SpriteSortMode_Deferred,
SpriteSortMode_Immediate,
SpriteSortMode_Texture,
SpriteSortMode_BackToFront,
SpriteSortMode_FrontToBack,
};
D3D12_BLEND_DESC blendDesc;
D3D12_DEPTH_STENCIL_DESC depthStencilDesc;
D3D12_RASTERIZER_DESC rasterizerDesc;
RenderTargetState renderTargetState;
D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor;
ID3D12RootSignature* customRootSignature;
D3D12_SHADER_BYTECODE customVertexShader;
D3D12_SHADER_BYTECODE customPixelShader;
enum SpriteEffects : uint32_t
{
SpriteEffects_None = 0,
SpriteEffects_FlipHorizontally = 1,
SpriteEffects_FlipVertically = 2,
SpriteEffects_FlipBoth = SpriteEffects_FlipHorizontally | SpriteEffects_FlipVertically,
};
private:
static const D3D12_BLEND_DESC s_DefaultBlendDesc;
static const D3D12_RASTERIZER_DESC s_DefaultRasterizerDesc;
static const D3D12_DEPTH_STENCIL_DESC s_DefaultDepthStencilDesc;
};
class SpriteBatchPipelineStateDescription
{
public:
explicit SpriteBatchPipelineStateDescription(
const RenderTargetState& renderTarget,
_In_opt_ const D3D12_BLEND_DESC* blend = nullptr,
_In_opt_ const D3D12_DEPTH_STENCIL_DESC* depthStencil = nullptr,
_In_opt_ const D3D12_RASTERIZER_DESC* rasterizer = nullptr,
_In_opt_ const D3D12_GPU_DESCRIPTOR_HANDLE* isamplerDescriptor = nullptr) noexcept
:
blendDesc(blend ? *blend : s_DefaultBlendDesc),
depthStencilDesc(depthStencil ? *depthStencil : s_DefaultDepthStencilDesc),
rasterizerDesc(rasterizer ? *rasterizer : s_DefaultRasterizerDesc),
renderTargetState(renderTarget),
samplerDescriptor{},
customRootSignature(nullptr),
customVertexShader{},
customPixelShader{}
{
if (isamplerDescriptor)
this->samplerDescriptor = *isamplerDescriptor;
}
class SpriteBatch
{
public:
SpriteBatch(_In_ ID3D12Device* device, ResourceUploadBatch& upload,
const SpriteBatchPipelineStateDescription& psoDesc,
_In_opt_ const D3D12_VIEWPORT* viewport = nullptr);
D3D12_BLEND_DESC blendDesc;
D3D12_DEPTH_STENCIL_DESC depthStencilDesc;
D3D12_RASTERIZER_DESC rasterizerDesc;
RenderTargetState renderTargetState;
D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor;
ID3D12RootSignature* customRootSignature;
D3D12_SHADER_BYTECODE customVertexShader;
D3D12_SHADER_BYTECODE customPixelShader;
SpriteBatch(SpriteBatch&&) noexcept;
SpriteBatch& operator= (SpriteBatch&&) noexcept;
private:
static const D3D12_BLEND_DESC s_DefaultBlendDesc;
static const D3D12_RASTERIZER_DESC s_DefaultRasterizerDesc;
static const D3D12_DEPTH_STENCIL_DESC s_DefaultDepthStencilDesc;
};
SpriteBatch(SpriteBatch const&) = delete;
SpriteBatch& operator= (SpriteBatch const&) = delete;
class SpriteBatch
{
public:
SpriteBatch(_In_ ID3D12Device* device, ResourceUploadBatch& upload,
const SpriteBatchPipelineStateDescription& psoDesc,
_In_opt_ const D3D12_VIEWPORT* viewport = nullptr);
virtual ~SpriteBatch();
SpriteBatch(SpriteBatch&&) noexcept;
SpriteBatch& operator= (SpriteBatch&&) noexcept;
// Begin/End a batch of sprite drawing operations.
void XM_CALLCONV Begin(
_In_ ID3D12GraphicsCommandList* commandList,
SpriteSortMode sortMode = SpriteSortMode_Deferred,
FXMMATRIX transformMatrix = MatrixIdentity);
void XM_CALLCONV Begin(
_In_ ID3D12GraphicsCommandList* commandList,
D3D12_GPU_DESCRIPTOR_HANDLE sampler,
SpriteSortMode sortMode = SpriteSortMode_Deferred,
FXMMATRIX transformMatrix = MatrixIdentity);
void __cdecl End();
SpriteBatch(SpriteBatch const&) = delete;
SpriteBatch& operator= (SpriteBatch const&) = delete;
// Draw overloads specifying position, origin and scale as XMFLOAT2.
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, XMFLOAT2 const& position, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
virtual ~SpriteBatch();
// Draw overloads specifying position, origin and scale via the first two components of an XMVECTOR.
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, FXMVECTOR position, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
// Begin/End a batch of sprite drawing operations.
void XM_CALLCONV Begin(
_In_ ID3D12GraphicsCommandList* commandList,
SpriteSortMode sortMode = SpriteSortMode_Deferred,
FXMMATRIX transformMatrix = MatrixIdentity);
void XM_CALLCONV Begin(
_In_ ID3D12GraphicsCommandList* commandList,
D3D12_GPU_DESCRIPTOR_HANDLE sampler,
SpriteSortMode sortMode = SpriteSortMode_Deferred,
FXMMATRIX transformMatrix = MatrixIdentity);
void __cdecl End();
// Draw overloads specifying position as a RECT.
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, RECT const& destinationRectangle, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, RECT const& destinationRectangle, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
// Draw overloads specifying position, origin and scale as XMFLOAT2.
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, XMFLOAT2 const& position, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
// Rotation mode to be applied to the sprite transformation
#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
void __cdecl SetRotation(DXGI_MODE_ROTATION mode);
DXGI_MODE_ROTATION __cdecl GetRotation() const noexcept;
#endif
// Draw overloads specifying position, origin and scale via the first two components of an XMVECTOR.
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, FXMVECTOR position, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
// Set viewport for sprite transformation
void __cdecl SetViewport(const D3D12_VIEWPORT& viewPort);
// Draw overloads specifying position as a RECT.
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, RECT const& destinationRectangle, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, RECT const& destinationRectangle, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
private:
// Private implementation.
struct Impl;
// Rotation mode to be applied to the sprite transformation
#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
void __cdecl SetRotation(DXGI_MODE_ROTATION mode);
DXGI_MODE_ROTATION __cdecl GetRotation() const noexcept;
#endif
std::unique_ptr<Impl> pImpl;
// Set viewport for sprite transformation
void __cdecl SetViewport(const D3D12_VIEWPORT& viewPort);
static const XMMATRIX MatrixIdentity;
static const XMFLOAT2 Float2Zero;
};
private:
// Private implementation.
struct Impl;
std::unique_ptr<Impl> pImpl;
static const XMMATRIX MatrixIdentity;
static const XMFLOAT2 Float2Zero;
};
}
}

Просмотреть файл

@ -18,84 +18,87 @@
namespace DirectX
{
class SpriteFont
inline namespace DX12
{
public:
struct Glyph;
SpriteFont(ID3D12Device* device, ResourceUploadBatch& upload,
_In_z_ wchar_t const* fileName,
D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor,
bool forceSRGB = false);
SpriteFont(ID3D12Device* device, ResourceUploadBatch& upload,
_In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize,
D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor,
bool forceSRGB = false);
SpriteFont(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 textureSize,
_In_reads_(glyphCount) Glyph const* glyphs, size_t glyphCount, float lineSpacing);
SpriteFont(SpriteFont&&) noexcept;
SpriteFont& operator= (SpriteFont&&) noexcept;
SpriteFont(SpriteFont const&) = delete;
SpriteFont& operator= (SpriteFont const&) = delete;
virtual ~SpriteFont();
// Wide-character / UTF-16LE
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
XMVECTOR XM_CALLCONV MeasureString(_In_z_ wchar_t const* text, bool ignoreWhitespace = true) const;
RECT __cdecl MeasureDrawBounds(_In_z_ wchar_t const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const;
RECT XM_CALLCONV MeasureDrawBounds(_In_z_ wchar_t const* text, FXMVECTOR position, bool ignoreWhitespace = true) const;
// UTF-8
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
XMVECTOR XM_CALLCONV MeasureString(_In_z_ char const* text, bool ignoreWhitespace = true) const;
RECT __cdecl MeasureDrawBounds(_In_z_ char const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const;
RECT XM_CALLCONV MeasureDrawBounds(_In_z_ char const* text, FXMVECTOR position, bool ignoreWhitespace = true) const;
// Spacing properties
float __cdecl GetLineSpacing() const noexcept;
void __cdecl SetLineSpacing(float spacing);
// Font properties
wchar_t __cdecl GetDefaultCharacter() const noexcept;
void __cdecl SetDefaultCharacter(wchar_t character);
bool __cdecl ContainsCharacter(wchar_t character) const;
// Custom layout/rendering
Glyph const* __cdecl FindGlyph(wchar_t character) const;
D3D12_GPU_DESCRIPTOR_HANDLE __cdecl GetSpriteSheet() const noexcept;
XMUINT2 __cdecl GetSpriteSheetSize() const noexcept;
// Describes a single character glyph.
struct Glyph
class SpriteFont
{
uint32_t Character;
RECT Subrect;
float XOffset;
float YOffset;
float XAdvance;
public:
struct Glyph;
SpriteFont(ID3D12Device* device, ResourceUploadBatch& upload,
_In_z_ wchar_t const* fileName,
D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor,
bool forceSRGB = false);
SpriteFont(ID3D12Device* device, ResourceUploadBatch& upload,
_In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize,
D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptorDest, D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptor,
bool forceSRGB = false);
SpriteFont(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 textureSize,
_In_reads_(glyphCount) Glyph const* glyphs, size_t glyphCount, float lineSpacing);
SpriteFont(SpriteFont&&) noexcept;
SpriteFont& operator= (SpriteFont&&) noexcept;
SpriteFont(SpriteFont const&) = delete;
SpriteFont& operator= (SpriteFont const&) = delete;
virtual ~SpriteFont();
// Wide-character / UTF-16LE
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
XMVECTOR XM_CALLCONV MeasureString(_In_z_ wchar_t const* text, bool ignoreWhitespace = true) const;
RECT __cdecl MeasureDrawBounds(_In_z_ wchar_t const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const;
RECT XM_CALLCONV MeasureDrawBounds(_In_z_ wchar_t const* text, FXMVECTOR position, bool ignoreWhitespace = true) const;
// UTF-8
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
XMVECTOR XM_CALLCONV MeasureString(_In_z_ char const* text, bool ignoreWhitespace = true) const;
RECT __cdecl MeasureDrawBounds(_In_z_ char const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const;
RECT XM_CALLCONV MeasureDrawBounds(_In_z_ char const* text, FXMVECTOR position, bool ignoreWhitespace = true) const;
// Spacing properties
float __cdecl GetLineSpacing() const noexcept;
void __cdecl SetLineSpacing(float spacing);
// Font properties
wchar_t __cdecl GetDefaultCharacter() const noexcept;
void __cdecl SetDefaultCharacter(wchar_t character);
bool __cdecl ContainsCharacter(wchar_t character) const;
// Custom layout/rendering
Glyph const* __cdecl FindGlyph(wchar_t character) const;
D3D12_GPU_DESCRIPTOR_HANDLE __cdecl GetSpriteSheet() const noexcept;
XMUINT2 __cdecl GetSpriteSheetSize() const noexcept;
// Describes a single character glyph.
struct Glyph
{
uint32_t Character;
RECT Subrect;
float XOffset;
float YOffset;
float XAdvance;
};
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
static const XMFLOAT2 Float2Zero;
};
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
static const XMFLOAT2 Float2Zero;
};
}
}

Просмотреть файл

@ -25,333 +25,336 @@
namespace DirectX
{
inline namespace DX12
{
// Vertex struct holding position information.
struct VertexPosition
{
VertexPosition() = default;
VertexPosition(const VertexPosition&) = default;
VertexPosition& operator=(const VertexPosition&) = default;
VertexPosition(VertexPosition&&) = default;
VertexPosition& operator=(VertexPosition&&) = default;
VertexPosition(XMFLOAT3 const& iposition) noexcept
: position(iposition)
struct VertexPosition
{
}
VertexPosition() = default;
VertexPosition(FXMVECTOR iposition) noexcept
VertexPosition(const VertexPosition&) = default;
VertexPosition& operator=(const VertexPosition&) = default;
VertexPosition(VertexPosition&&) = default;
VertexPosition& operator=(VertexPosition&&) = default;
VertexPosition(XMFLOAT3 const& iposition) noexcept
: position(iposition)
{
}
VertexPosition(FXMVECTOR iposition) noexcept
{
XMStoreFloat3(&this->position, iposition);
}
XMFLOAT3 position;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 1;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and color information.
struct VertexPositionColor
{
XMStoreFloat3(&this->position, iposition);
}
VertexPositionColor() = default;
XMFLOAT3 position;
VertexPositionColor(const VertexPositionColor&) = default;
VertexPositionColor& operator=(const VertexPositionColor&) = default;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
VertexPositionColor(VertexPositionColor&&) = default;
VertexPositionColor& operator=(VertexPositionColor&&) = default;
private:
static constexpr unsigned int InputElementCount = 1;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
VertexPositionColor(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor) noexcept
: position(iposition),
color(icolor)
{
}
VertexPositionColor(FXMVECTOR iposition, FXMVECTOR icolor) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat4(&this->color, icolor);
}
XMFLOAT3 position;
XMFLOAT4 color;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 2;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and color information.
struct VertexPositionColor
{
VertexPositionColor() = default;
VertexPositionColor(const VertexPositionColor&) = default;
VertexPositionColor& operator=(const VertexPositionColor&) = default;
VertexPositionColor(VertexPositionColor&&) = default;
VertexPositionColor& operator=(VertexPositionColor&&) = default;
VertexPositionColor(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor) noexcept
: position(iposition),
color(icolor)
// Vertex struct holding position and texture mapping information.
struct VertexPositionTexture
{
}
VertexPositionTexture() = default;
VertexPositionColor(FXMVECTOR iposition, FXMVECTOR icolor) noexcept
VertexPositionTexture(const VertexPositionTexture&) = default;
VertexPositionTexture& operator=(const VertexPositionTexture&) = default;
VertexPositionTexture(VertexPositionTexture&&) = default;
VertexPositionTexture& operator=(VertexPositionTexture&&) = default;
VertexPositionTexture(XMFLOAT3 const& iposition, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionTexture(FXMVECTOR iposition, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT2 textureCoordinate;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 2;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and dual texture mapping information.
struct VertexPositionDualTexture
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat4(&this->color, icolor);
}
VertexPositionDualTexture() = default;
XMFLOAT3 position;
XMFLOAT4 color;
VertexPositionDualTexture(const VertexPositionDualTexture&) = default;
VertexPositionDualTexture& operator=(const VertexPositionDualTexture&) = default;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
VertexPositionDualTexture(VertexPositionDualTexture&&) = default;
VertexPositionDualTexture& operator=(VertexPositionDualTexture&&) = default;
private:
static constexpr unsigned int InputElementCount = 2;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
VertexPositionDualTexture(
XMFLOAT3 const& iposition,
XMFLOAT2 const& itextureCoordinate0,
XMFLOAT2 const& itextureCoordinate1) noexcept
: position(iposition),
textureCoordinate0(itextureCoordinate0),
textureCoordinate1(itextureCoordinate1)
{
}
VertexPositionDualTexture(
FXMVECTOR iposition,
FXMVECTOR itextureCoordinate0,
FXMVECTOR itextureCoordinate1) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat2(&this->textureCoordinate0, itextureCoordinate0);
XMStoreFloat2(&this->textureCoordinate1, itextureCoordinate1);
}
XMFLOAT3 position;
XMFLOAT2 textureCoordinate0;
XMFLOAT2 textureCoordinate1;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and texture mapping information.
struct VertexPositionTexture
{
VertexPositionTexture() = default;
VertexPositionTexture(const VertexPositionTexture&) = default;
VertexPositionTexture& operator=(const VertexPositionTexture&) = default;
VertexPositionTexture(VertexPositionTexture&&) = default;
VertexPositionTexture& operator=(VertexPositionTexture&&) = default;
VertexPositionTexture(XMFLOAT3 const& iposition, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
textureCoordinate(itextureCoordinate)
// Vertex struct holding position and normal vector.
struct VertexPositionNormal
{
}
VertexPositionNormal() = default;
VertexPositionTexture(FXMVECTOR iposition, FXMVECTOR itextureCoordinate) noexcept
VertexPositionNormal(const VertexPositionNormal&) = default;
VertexPositionNormal& operator=(const VertexPositionNormal&) = default;
VertexPositionNormal(VertexPositionNormal&&) = default;
VertexPositionNormal& operator=(VertexPositionNormal&&) = default;
VertexPositionNormal(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal) noexcept
: position(iposition),
normal(inormal)
{
}
VertexPositionNormal(FXMVECTOR iposition, FXMVECTOR inormal) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
}
XMFLOAT3 position;
XMFLOAT3 normal;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 2;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, color, and texture mapping information.
struct VertexPositionColorTexture
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
VertexPositionColorTexture() = default;
XMFLOAT3 position;
XMFLOAT2 textureCoordinate;
VertexPositionColorTexture(const VertexPositionColorTexture&) = default;
VertexPositionColorTexture& operator=(const VertexPositionColorTexture&) = default;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
VertexPositionColorTexture(VertexPositionColorTexture&&) = default;
VertexPositionColorTexture& operator=(VertexPositionColorTexture&&) = default;
private:
static constexpr unsigned int InputElementCount = 2;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
VertexPositionColorTexture(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
color(icolor),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionColorTexture(FXMVECTOR iposition, FXMVECTOR icolor, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat4(&this->color, icolor);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT4 color;
XMFLOAT2 textureCoordinate;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and dual texture mapping information.
struct VertexPositionDualTexture
{
VertexPositionDualTexture() = default;
VertexPositionDualTexture(const VertexPositionDualTexture&) = default;
VertexPositionDualTexture& operator=(const VertexPositionDualTexture&) = default;
VertexPositionDualTexture(VertexPositionDualTexture&&) = default;
VertexPositionDualTexture& operator=(VertexPositionDualTexture&&) = default;
VertexPositionDualTexture(
XMFLOAT3 const& iposition,
XMFLOAT2 const& itextureCoordinate0,
XMFLOAT2 const& itextureCoordinate1) noexcept
: position(iposition),
textureCoordinate0(itextureCoordinate0),
textureCoordinate1(itextureCoordinate1)
// Vertex struct holding position, normal vector, and color information.
struct VertexPositionNormalColor
{
}
VertexPositionNormalColor() = default;
VertexPositionDualTexture(
FXMVECTOR iposition,
FXMVECTOR itextureCoordinate0,
FXMVECTOR itextureCoordinate1) noexcept
VertexPositionNormalColor(const VertexPositionNormalColor&) = default;
VertexPositionNormalColor& operator=(const VertexPositionNormalColor&) = default;
VertexPositionNormalColor(VertexPositionNormalColor&&) = default;
VertexPositionNormalColor& operator=(VertexPositionNormalColor&&) = default;
VertexPositionNormalColor(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT4 const& icolor) noexcept
: position(iposition),
normal(inormal),
color(icolor)
{
}
VertexPositionNormalColor(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->color, icolor);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT4 color;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, normal vector, and texture mapping information.
struct VertexPositionNormalTexture
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat2(&this->textureCoordinate0, itextureCoordinate0);
XMStoreFloat2(&this->textureCoordinate1, itextureCoordinate1);
}
VertexPositionNormalTexture() = default;
XMFLOAT3 position;
XMFLOAT2 textureCoordinate0;
XMFLOAT2 textureCoordinate1;
VertexPositionNormalTexture(const VertexPositionNormalTexture&) = default;
VertexPositionNormalTexture& operator=(const VertexPositionNormalTexture&) = default;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
VertexPositionNormalTexture(VertexPositionNormalTexture&&) = default;
VertexPositionNormalTexture& operator=(VertexPositionNormalTexture&&) = default;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
VertexPositionNormalTexture(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionNormalTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT2 textureCoordinate;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and normal vector.
struct VertexPositionNormal
{
VertexPositionNormal() = default;
VertexPositionNormal(const VertexPositionNormal&) = default;
VertexPositionNormal& operator=(const VertexPositionNormal&) = default;
VertexPositionNormal(VertexPositionNormal&&) = default;
VertexPositionNormal& operator=(VertexPositionNormal&&) = default;
VertexPositionNormal(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal) noexcept
: position(iposition),
normal(inormal)
// Vertex struct holding position, normal vector, color, and texture mapping information.
struct VertexPositionNormalColorTexture
{
}
VertexPositionNormalColorTexture() = default;
VertexPositionNormal(FXMVECTOR iposition, FXMVECTOR inormal) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
}
VertexPositionNormalColorTexture(const VertexPositionNormalColorTexture&) = default;
VertexPositionNormalColorTexture& operator=(const VertexPositionNormalColorTexture&) = default;
XMFLOAT3 position;
XMFLOAT3 normal;
VertexPositionNormalColorTexture(VertexPositionNormalColorTexture&&) = default;
VertexPositionNormalColorTexture& operator=(VertexPositionNormalColorTexture&&) = default;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
VertexPositionNormalColorTexture(
XMFLOAT3 const& iposition,
XMFLOAT3 const& inormal,
XMFLOAT4 const& icolor,
XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
color(icolor),
textureCoordinate(itextureCoordinate)
{
}
private:
static constexpr unsigned int InputElementCount = 2;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
VertexPositionNormalColorTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor, CXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->color, icolor);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT4 color;
XMFLOAT2 textureCoordinate;
// Vertex struct holding position, color, and texture mapping information.
struct VertexPositionColorTexture
{
VertexPositionColorTexture() = default;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
VertexPositionColorTexture(const VertexPositionColorTexture&) = default;
VertexPositionColorTexture& operator=(const VertexPositionColorTexture&) = default;
VertexPositionColorTexture(VertexPositionColorTexture&&) = default;
VertexPositionColorTexture& operator=(VertexPositionColorTexture&&) = default;
VertexPositionColorTexture(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
color(icolor),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionColorTexture(FXMVECTOR iposition, FXMVECTOR icolor, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat4(&this->color, icolor);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT4 color;
XMFLOAT2 textureCoordinate;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, normal vector, and color information.
struct VertexPositionNormalColor
{
VertexPositionNormalColor() = default;
VertexPositionNormalColor(const VertexPositionNormalColor&) = default;
VertexPositionNormalColor& operator=(const VertexPositionNormalColor&) = default;
VertexPositionNormalColor(VertexPositionNormalColor&&) = default;
VertexPositionNormalColor& operator=(VertexPositionNormalColor&&) = default;
VertexPositionNormalColor(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT4 const& icolor) noexcept
: position(iposition),
normal(inormal),
color(icolor)
{
}
VertexPositionNormalColor(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->color, icolor);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT4 color;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, normal vector, and texture mapping information.
struct VertexPositionNormalTexture
{
VertexPositionNormalTexture() = default;
VertexPositionNormalTexture(const VertexPositionNormalTexture&) = default;
VertexPositionNormalTexture& operator=(const VertexPositionNormalTexture&) = default;
VertexPositionNormalTexture(VertexPositionNormalTexture&&) = default;
VertexPositionNormalTexture& operator=(VertexPositionNormalTexture&&) = default;
VertexPositionNormalTexture(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionNormalTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT2 textureCoordinate;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 3;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, normal vector, color, and texture mapping information.
struct VertexPositionNormalColorTexture
{
VertexPositionNormalColorTexture() = default;
VertexPositionNormalColorTexture(const VertexPositionNormalColorTexture&) = default;
VertexPositionNormalColorTexture& operator=(const VertexPositionNormalColorTexture&) = default;
VertexPositionNormalColorTexture(VertexPositionNormalColorTexture&&) = default;
VertexPositionNormalColorTexture& operator=(VertexPositionNormalColorTexture&&) = default;
VertexPositionNormalColorTexture(
XMFLOAT3 const& iposition,
XMFLOAT3 const& inormal,
XMFLOAT4 const& icolor,
XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
color(icolor),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionNormalColorTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor, CXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->color, icolor);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT4 color;
XMFLOAT2 textureCoordinate;
static const D3D12_INPUT_LAYOUT_DESC InputLayout;
private:
static constexpr unsigned int InputElementCount = 4;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
private:
static constexpr unsigned int InputElementCount = 4;
static const D3D12_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
}
}

Просмотреть файл

@ -39,18 +39,21 @@
namespace DirectX
{
enum WIC_LOADER_FLAGS : uint32_t
inline namespace DX12
{
WIC_LOADER_DEFAULT = 0,
WIC_LOADER_FORCE_SRGB = 0x1,
WIC_LOADER_IGNORE_SRGB = 0x2,
WIC_LOADER_SRGB_DEFAULT = 0x4,
WIC_LOADER_MIP_AUTOGEN = 0x8,
WIC_LOADER_MIP_RESERVE = 0x10,
WIC_LOADER_FIT_POW2 = 0x20,
WIC_LOADER_MAKE_SQUARE = 0x40,
WIC_LOADER_FORCE_RGBA32 = 0x80,
};
enum WIC_LOADER_FLAGS : uint32_t
{
WIC_LOADER_DEFAULT = 0,
WIC_LOADER_FORCE_SRGB = 0x1,
WIC_LOADER_IGNORE_SRGB = 0x2,
WIC_LOADER_SRGB_DEFAULT = 0x4,
WIC_LOADER_MIP_AUTOGEN = 0x8,
WIC_LOADER_MIP_RESERVE = 0x10,
WIC_LOADER_FIT_POW2 = 0x20,
WIC_LOADER_MAKE_SQUARE = 0x40,
WIC_LOADER_FORCE_RGBA32 = 0x80,
};
}
class ResourceUploadBatch;
@ -137,7 +140,10 @@ namespace DirectX
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#endif
DEFINE_ENUM_FLAG_OPERATORS(WIC_LOADER_FLAGS);
inline namespace DX12
{
DEFINE_ENUM_FLAG_OPERATORS(WIC_LOADER_FLAGS);
}
#ifdef __clang__
#pragma clang diagnostic pop

Просмотреть файл

@ -6,11 +6,11 @@ http://go.microsoft.com/fwlink/?LinkID=615561
Copyright (c) Microsoft Corporation.
**June 9, 2022**
**October 17, 2022**
This package contains the "DirectX Tool Kit", a collection of helper classes for writing Direct3D 12 C++ code for Universal Windows Platform (UWP) apps for Windows 11 / Windows 10, game titles for Xbox Series X\|S / Xbox One, and Win32 desktop applications for Windows 11 / Windows 10.
This code is designed to build with Visual Studio 2019 (16.9 or later), Visual Studio 2022, or clang for Windows v11 or later. Use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later is required.
This code is designed to build with Visual Studio 2019 (16.11), Visual Studio 2022, or clang for Windows v11 or later. Use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later is required.
These components are designed to work without requiring any content from the legacy DirectX SDK. For details, see [Where is the DirectX SDK?](https://aka.ms/dxsdk).
@ -80,6 +80,8 @@ For the latest version of DirectXTK12, bug reports, etc. please visit the projec
## Release Notes
* As of the September 2022 release, the library makes use of C++11 inline namespaces for differing types that have the same names in the DirectX 11 and DirectX 12 version of the *DirectX Tool Kit*. This provides a link-unique name such as ``DirectX::DX12::SpriteBatch`` that will appear in linker output messages. In most use cases, however, there is no need to add explicit ``DX12`` namespace resolution in client code.
* As of the March 2022 release, legacy Xbox One XDK support requires the XDK April 2018 release or later. Upgrading to the Microsoft GDKX is strongly recommended.
* In the June 2021 release or later, the VS 2019 projects of this library build the HLSL shaders with Shader Model 6 via DXC. Since the NuGet still builds using VS 2017, the build-in shaders in that version are currently Shader Model 5.1. See [this wiki page](https://github.com/microsoft/DirectXTK12/wiki/Shader-Model-6) for more information. The Microsoft GDK projects always use Shader Model 6.
@ -116,7 +118,7 @@ This project may contain trademarks or logos for projects, products, or services
## Credits
The _DirectX Tool Kit for DirectX 11_ is the work of Shawn Hargreaves and Chuck Walbourn, with contributions from Aaron Rodriguez Hernandez, and Dani Roman.
The _DirectX Tool Kit for DirectX 11_ is the work of Shawn Hargreaves and Chuck Walbourn, with contributions from Aaron Rodriguez Hernandez and Dani Roman.
The _DirectX Tool Kit for DirectX 12_ is the work of Pete Lewis, Justin Saunders, and Chuck Walbourn based heavily on the DirectX Tool Kit for DirectX 11.

Просмотреть файл

@ -572,7 +572,12 @@ void BasicPostProcess::SetSourceTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescripto
if (resource)
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto desc = resource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& desc = *resource->GetDesc(&tmpDesc);
#endif
pImpl->texWidth = static_cast<unsigned>(desc.Width);
pImpl->texHeight = desc.Height;
}

Просмотреть файл

@ -239,6 +239,10 @@ namespace
{
format = MakeSRGB(format);
}
else if (loadFlags & DDS_LOADER_IGNORE_SRGB)
{
format = MakeLinear(format);
}
D3D12_RESOURCE_DESC desc = {};
desc.Width = static_cast<UINT>(width);
@ -871,7 +875,14 @@ HRESULT DirectX::CreateDDSTextureFromMemoryEx(
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
// If it's missing mips, let's generate them
if ((loadFlags & DDS_LOADER_MIP_AUTOGEN) && subresources.size() != (*texture)->GetDesc().MipLevels)
#if defined(_MSC_VER) || !defined(_WIN32)
const size_t mipLevels = (*texture)->GetDesc().MipLevels;
#else
D3D12_RESOURCE_DESC tmpDesc;
const size_t mipLevels = (*texture)->GetDesc(&tmpDesc)->MipLevels;
#endif
if ((loadFlags & DDS_LOADER_MIP_AUTOGEN) && subresources.size() != mipLevels)
{
resourceUpload.GenerateMips(*texture);
}
@ -986,7 +997,14 @@ HRESULT DirectX::CreateDDSTextureFromFileEx(
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
// If it's missing mips, let's generate them
if ((loadFlags & DDS_LOADER_MIP_AUTOGEN) && subresources.size() != (*texture)->GetDesc().MipLevels)
#if defined(_MSC_VER) || !defined(_WIN32)
const size_t mipLevels = (*texture)->GetDesc().MipLevels;
#else
D3D12_RESOURCE_DESC tmpDesc;
const size_t mipLevels = (*texture)->GetDesc(&tmpDesc)->MipLevels;
#endif
if ((loadFlags & DDS_LOADER_MIP_AUTOGEN) && subresources.size() != mipLevels)
{
resourceUpload.GenerateMips(*texture);
}

Просмотреть файл

@ -37,9 +37,15 @@ DescriptorHeap::DescriptorHeap(
ID3D12DescriptorHeap* pExistingHeap) noexcept
: m_pHeap(pExistingHeap)
{
#if defined(_MSC_VER) || !defined(_WIN32)
m_hCPU = pExistingHeap->GetCPUDescriptorHandleForHeapStart();
m_hGPU = pExistingHeap->GetGPUDescriptorHandleForHeapStart();
m_desc = pExistingHeap->GetDesc();
#else
std::ignore = pExistingHeap->GetCPUDescriptorHandleForHeapStart(&m_hCPU);
std::ignore = pExistingHeap->GetGPUDescriptorHandleForHeapStart(&m_hGPU);
std::ignore = pExistingHeap->GetDesc(&m_desc);
#endif
ComPtr<ID3D12Device> device;
pExistingHeap->GetDevice(IID_GRAPHICS_PPV_ARGS(device.GetAddressOf()));
@ -168,11 +174,19 @@ void DescriptorHeap::Create(
SetDebugObjectName(m_pHeap.Get(), L"DescriptorHeap");
#if defined(_MSC_VER) || !defined(_WIN32)
m_hCPU = m_pHeap->GetCPUDescriptorHandleForHeapStart();
if (pDesc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)
{
m_hGPU = m_pHeap->GetGPUDescriptorHandleForHeapStart();
}
#else
std::ignore = m_pHeap->GetCPUDescriptorHandleForHeapStart(&m_hCPU);
if (pDesc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)
{
std::ignore = m_pHeap->GetGPUDescriptorHandleForHeapStart(&m_hGPU);
}
#endif
}
}

Просмотреть файл

@ -21,7 +21,12 @@ void DirectX::CreateShaderResourceView(
D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptor,
bool isCubeMap)
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto desc = tex->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& desc = *tex->GetDesc(&tmpDesc);
#endif
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = desc.Format;

Просмотреть файл

@ -28,13 +28,16 @@
namespace DirectX
{
// Internal effect flags
namespace EffectFlags
inline namespace DX12
{
constexpr int PerPixelLightingBit = 0x04;
}
// Internal effect flags
namespace EffectFlags
{
constexpr int PerPixelLightingBit = 0x04;
}
static_assert(((EffectFlags::PerPixelLighting)& EffectFlags::PerPixelLightingBit) != 0, "PerPixelLighting enum flags mismatch");
static_assert(((EffectFlags::PerPixelLighting)& EffectFlags::PerPixelLightingBit) != 0, "PerPixelLighting enum flags mismatch");
}
// Bitfield tracks which derived parameter values need to be recomputed.
namespace EffectDirtyFlags

Просмотреть файл

@ -497,11 +497,20 @@ EffectFactory::EffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_
throw std::invalid_argument("Descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead.");
}
if (textureDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
#if defined(_MSC_VER) || !defined(_WIN32)
const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc().Type;
const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc().Type;
#else
D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2;
const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc(&tmpDesc1)->Type;
const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc(&tmpDesc2)->Type;
#endif
if (textureHeapType != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
{
throw std::invalid_argument("EffectFactory::CreateEffect requires a CBV_SRV_UAV descriptor heap for textureDescriptors.");
}
if (samplerDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)
if (samplerHeapType != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)
{
throw std::invalid_argument("EffectFactory::CreateEffect requires a SAMPLER descriptor heap for samplerDescriptors.");
}

Просмотреть файл

@ -91,7 +91,13 @@ void EffectPipelineStateDescription::CreatePipelineState(
const D3D12_SHADER_BYTECODE& pixelShader,
_Outptr_ ID3D12PipelineState** pPipelineState) const
{
#if defined(_MSC_VER) || !defined(_WIN32)
auto psoDesc = GetDesc();
#else
D3D12_GRAPHICS_PIPELINE_STATE_DESC tmpPSODesc;
auto& psoDesc = *GetDesc(&tmpPSODesc);
#endif
psoDesc.pRootSignature = rootSignature;
psoDesc.VS = vertexShader;
psoDesc.PS = pixelShader;

Просмотреть файл

@ -1683,11 +1683,7 @@ GamePad& GamePad::Get()
// ButtonStateTracker
//======================================================================================
#define UPDATE_BUTTON_STATE(field) field = static_cast<ButtonState>( ( !!state.buttons.field ) | ( ( !!state.buttons.field ^ !!lastState.buttons.field ) << 1 ) );
#ifdef __clang__
#pragma clang diagnostic ignored "-Wextra-semi-stmt"
#endif
#define UPDATE_BUTTON_STATE(field) field = static_cast<ButtonState>( ( !!state.buttons.field ) | ( ( !!state.buttons.field ^ !!lastState.buttons.field ) << 1 ) )
void GamePad::ButtonStateTracker::Update(const GamePad::State& state) noexcept
{

Просмотреть файл

@ -221,6 +221,37 @@ namespace DirectX
}
}
//--------------------------------------------------------------------------------------
inline DXGI_FORMAT MakeLinear(_In_ DXGI_FORMAT format) noexcept
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case DXGI_FORMAT_BC1_UNORM_SRGB:
return DXGI_FORMAT_BC1_UNORM;
case DXGI_FORMAT_BC2_UNORM_SRGB:
return DXGI_FORMAT_BC2_UNORM;
case DXGI_FORMAT_BC3_UNORM_SRGB:
return DXGI_FORMAT_BC3_UNORM;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
return DXGI_FORMAT_B8G8R8X8_UNORM;
case DXGI_FORMAT_BC7_UNORM_SRGB:
return DXGI_FORMAT_BC7_UNORM;
default:
return format;
}
}
//--------------------------------------------------------------------------------------
inline bool IsCompressed(_In_ DXGI_FORMAT fmt) noexcept
{

Просмотреть файл

@ -1193,8 +1193,8 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam)
if (!pImpl)
return;
HANDLE events[3] = { pImpl->mScrollWheelValue.get(), pImpl->mAbsoluteMode.get(), pImpl->mRelativeMode.get() };
switch (WaitForMultipleObjectsEx(static_cast<DWORD>(std::size(events)), events, FALSE, 0, FALSE))
// First handle any pending scroll wheel reset event.
switch (WaitForSingleObjectEx(pImpl->mScrollWheelValue.get(), 0, FALSE))
{
default:
case WAIT_TIMEOUT:
@ -1202,10 +1202,22 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam)
case WAIT_OBJECT_0:
pImpl->mState.scrollWheelValue = 0;
ResetEvent(events[0]);
ResetEvent(pImpl->mScrollWheelValue.get());
break;
case (WAIT_OBJECT_0 + 1):
case WAIT_FAILED:
throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx");
}
// Next handle mode change events.
HANDLE events[2] = { pImpl->mAbsoluteMode.get(), pImpl->mRelativeMode.get() };
switch (WaitForMultipleObjectsEx(static_cast<DWORD>(std::size(events)), events, FALSE, 0, FALSE))
{
default:
case WAIT_TIMEOUT:
break;
case WAIT_OBJECT_0:
{
pImpl->mMode = MODE_ABSOLUTE;
ClipCursor(nullptr);
@ -1226,7 +1238,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam)
}
break;
case (WAIT_OBJECT_0 + 2):
case (WAIT_OBJECT_0 + 1):
{
ResetEvent(pImpl->mRelativeRead.get());
@ -1484,11 +1496,7 @@ Mouse& Mouse::Get()
// ButtonStateTracker
//======================================================================================
#define UPDATE_BUTTON_STATE(field) field = static_cast<ButtonState>( ( !!state.field ) | ( ( !!state.field ^ !!lastState.field ) << 1 ) );
#ifdef __clang__
#pragma clang diagnostic ignored "-Wextra-semi-stmt"
#endif
#define UPDATE_BUTTON_STATE(field) field = static_cast<ButtonState>( ( !!state.field ) | ( ( !!state.field ^ !!lastState.field ) << 1 ) )
void Mouse::ButtonStateTracker::Update(const Mouse::State& state) noexcept
{

Просмотреть файл

@ -257,11 +257,20 @@ PBREffectFactory::PBREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors
throw std::invalid_argument("Descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead.");
}
if (textureDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
#if defined(_MSC_VER) || !defined(_WIN32)
const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc().Type;
const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc().Type;
#else
D3D12_DESCRIPTOR_HEAP_DESC tmpDesc1, tmpDesc2;
const D3D12_DESCRIPTOR_HEAP_TYPE textureHeapType = textureDescriptors->GetDesc(&tmpDesc1)->Type;
const D3D12_DESCRIPTOR_HEAP_TYPE samplerHeapType = samplerDescriptors->GetDesc(&tmpDesc2)->Type;
#endif
if (textureHeapType != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
{
throw std::invalid_argument("PBREffectFactory::CreateEffect requires a CBV_SRV_UAV descriptor heap for textureDescriptors.");
}
if (samplerDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)
if (samplerHeapType != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)
{
throw std::invalid_argument("PBREffectFactory::CreateEffect requires a SAMPLER descriptor heap for samplerDescriptors.");
}

Просмотреть файл

@ -14,7 +14,7 @@
#include "GraphicsMemory.h"
using namespace DirectX;
using namespace DirectX::Internal;
using namespace DirectX::DX12::Private;
using Microsoft::WRL::ComPtr;

Просмотреть файл

@ -418,7 +418,12 @@ public:
throw std::runtime_error("GenerateMips cannot operate on a copy queue");
}
#if defined(_MSC_VER) || !defined(_WIN32)
const auto desc = resource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& desc = *resource->GetDesc(&tmpDesc);
#endif
if (desc.MipLevels == 1)
{
@ -626,7 +631,12 @@ private:
void GenerateMips_UnorderedAccessPath(
_In_ ID3D12Resource* resource)
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto desc = resource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& desc = *resource->GetDesc(&tmpDesc);
#endif
assert(!FormatIsBGR(desc.Format) && !FormatIsSRGB(desc.Format));
const CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
@ -683,7 +693,12 @@ private:
auto const descriptorSize = static_cast<int>(mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV));
// Create the top-level SRV
#if defined(_MSC_VER) || !defined(_WIN32)
CD3DX12_CPU_DESCRIPTOR_HANDLE handleIt(descriptorHeap->GetCPUDescriptorHandleForHeapStart());
#else
CD3DX12_CPU_DESCRIPTOR_HANDLE handleIt;
std::ignore = descriptorHeap->GetCPUDescriptorHandleForHeapStart(&handleIt);
#endif
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
@ -734,12 +749,17 @@ private:
mList->SetComputeRootSignature(mGenMipsResources->rootSignature.Get());
mList->SetPipelineState(pso.Get());
mList->SetDescriptorHeaps(1, descriptorHeap.GetAddressOf());
mList->SetComputeRootDescriptorTable(GenerateMipsResources::SourceTexture, descriptorHeap->GetGPUDescriptorHandleForHeapStart());
#if defined(_MSC_VER) || !defined(_WIN32)
D3D12_GPU_DESCRIPTOR_HANDLE handle(descriptorHeap->GetGPUDescriptorHandleForHeapStart());
#else
D3D12_GPU_DESCRIPTOR_HANDLE handle;
std::ignore = descriptorHeap->GetGPUDescriptorHandleForHeapStart(&handle);
#endif
mList->SetComputeRootDescriptorTable(GenerateMipsResources::SourceTexture, handle);
// Get the descriptor handle -- uavH will increment over each loop
CD3DX12_GPU_DESCRIPTOR_HANDLE uavH(
descriptorHeap->GetGPUDescriptorHandleForHeapStart(),
descriptorSize); // offset by 1 descriptor
CD3DX12_GPU_DESCRIPTOR_HANDLE uavH(handle, descriptorSize); // offset by 1 descriptor
// Process each mip
auto mipWidth = static_cast<uint32_t>(desc.Width);
@ -823,7 +843,12 @@ private:
void GenerateMips_TexturePath(
_In_ ID3D12Resource* resource)
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto resourceDesc = resource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& resourceDesc = *resource->GetDesc(&tmpDesc);
#endif
assert(!FormatIsBGR(resourceDesc.Format) || FormatIsSRGB(resourceDesc.Format));
auto copyDesc = resourceDesc;
@ -888,7 +913,12 @@ private:
void GenerateMips_TexturePathBGR(
_In_ ID3D12Resource* resource)
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto resourceDesc = resource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& resourceDesc = *resource->GetDesc(&tmpDesc);
#endif
assert(FormatIsBGR(resourceDesc.Format));
// Create a resource with the same description with RGB and with UAV flags
@ -900,7 +930,12 @@ private:
#endif
D3D12_HEAP_DESC heapDesc = {};
#if defined(_MSC_VER) || !defined(_WIN32)
auto const allocInfo = mDevice->GetResourceAllocationInfo(0, 1, &copyDesc);
#else
D3D12_RESOURCE_ALLOCATION_INFO allocInfo;
std::ignore = mDevice->GetResourceAllocationInfo(&allocInfo, 0, 1, &copyDesc);
#endif
heapDesc.SizeInBytes = allocInfo.SizeInBytes;
heapDesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
heapDesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;

Просмотреть файл

@ -234,7 +234,12 @@ HRESULT DirectX::SaveDDSTextureToFile(
pCommandQ->GetDevice(IID_GRAPHICS_PPV_ARGS(device.GetAddressOf()));
// Get the size of the image
#if defined(_MSC_VER) || !defined(_WIN32)
const auto desc = pSource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& desc = *pSource->GetDesc(&tmpDesc);
#endif
if (desc.Width > UINT32_MAX)
return E_INVALIDARG;
@ -430,9 +435,12 @@ HRESULT DirectX::SaveDDSTextureToFile(
//--------------------------------------------------------------------------------------
namespace DirectX
{
namespace Internal
inline namespace DX12
{
extern IWICImagingFactory2* GetWIC() noexcept;
namespace Internal
{
extern IWICImagingFactory2* GetWIC() noexcept;
}
}
}
@ -448,7 +456,7 @@ HRESULT DirectX::SaveWICTextureToFile(
std::function<void(IPropertyBag2*)> setCustomProps,
bool forceSRGB)
{
using namespace DirectX::Internal;
using namespace DirectX::DX12::Internal;
if (!fileName)
return E_INVALIDARG;
@ -457,7 +465,12 @@ HRESULT DirectX::SaveWICTextureToFile(
pCommandQ->GetDevice(IID_GRAPHICS_PPV_ARGS(device.GetAddressOf()));
// Get the size of the image
#if defined(_MSC_VER) || !defined(_WIN32)
const auto desc = pSource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& desc = *pSource->GetDesc(&tmpDesc);
#endif
if (desc.Width > UINT32_MAX)
return E_INVALIDARG;

Просмотреть файл

@ -46,6 +46,7 @@ if not exist %XBOXDXC% goto needgxdk
goto continue
:continuedxil
if defined DirectXShaderCompiler goto dxcviaenv
set PCDXC="%WindowsSdkVerBinPath%x86\dxc.exe"
if exist %PCDXC% goto continue
set PCDXC="%WindowsSdkBinPath%%WindowsSDKVersion%\x86\dxc.exe"
@ -54,6 +55,11 @@ if exist %PCDXC% goto continue
set PCDXC=dxc.exe
goto continue
:dxcviaenv
set PCDXC="%DirectXShaderCompiler%"
if exist %PCDXC% goto continue
goto needdxil
:continuepc
set PCOPTS=
@ -284,56 +290,56 @@ endlocal
exit /b 0
:CompileShader
set fxc=%PCFXC% %1.fx %FXCOPTS% /T%2_5_1 %PCOPTS% /E%3 "/Fh%CompileShadersOutput%\%1_%3.inc" "/Fd%CompileShadersOutput%\%1_%3.pdb" /Vn%1_%3
set fxc=%PCFXC% "%1.fx" %FXCOPTS% /T%2_5_1 %PCOPTS% /E%3 "/Fh%CompileShadersOutput%\%1_%3.inc" "/Fd%CompileShadersOutput%\%1_%3.pdb" /Vn%1_%3
echo.
echo %fxc%
%fxc% || set error=1
exit /b
:CompileComputeShader
set fxc=%PCFXC% %1.hlsl %FXCOPTS% /Tcs_5_1 %PCOPTS% /E%2 "/Fh%CompileShadersOutput%\%1_%2.inc" "/Fd%CompileShadersOutput%\%1_%2.pdb" /Vn%1_%2
set fxc=%PCFXC% "%1.hlsl" %FXCOPTS% /Tcs_5_1 %PCOPTS% /E%2 "/Fh%CompileShadersOutput%\%1_%2.inc" "/Fd%CompileShadersOutput%\%1_%2.pdb" /Vn%1_%2
echo.
echo %fxc%
%fxc% || set error=1
exit /b
:CompileShaderdxil
set dxc=%PCDXC% %1.fx %FXCOPTS% /T%2_6_0 /E%3 "/Fh%CompileShadersOutput%\%1_%3.inc" "/Fd%CompileShadersOutput%\%1_%3.pdb" /Vn%1_%3
set dxc=%PCDXC% "%1.fx" %FXCOPTS% /T%2_6_0 /E%3 "/Fh%CompileShadersOutput%\%1_%3.inc" "/Fd%CompileShadersOutput%\%1_%3.pdb" /Vn%1_%3
echo.
echo %dxc%
%dxc% || set error=1
exit /b
:CompileComputeShaderdxil
set dxc=%PCDXC% %1.hlsl %FXCOPTS% /Tcs_6_0 /E%2 "/Fh%CompileShadersOutput%\%1_%2.inc" "/Fd%CompileShadersOutput%\%1_%2.pdb" /Vn%1_%2
set dxc=%PCDXC% "%1.hlsl" %FXCOPTS% /Tcs_6_0 /E%2 "/Fh%CompileShadersOutput%\%1_%2.inc" "/Fd%CompileShadersOutput%\%1_%2.pdb" /Vn%1_%2
echo.
echo %dxc%
%dxc% || set error=1
exit /b
:CompileShaderxbox
set fxc=%XBOXFXC% %1.fx %FXCOPTS% /T%2_5_1 %XBOXOPTS% /E%3 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%3.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%3.pdb" /Vn%1_%3
set fxc=%XBOXFXC% "%1.fx" %FXCOPTS% /T%2_5_1 %XBOXOPTS% /E%3 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%3.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%3.pdb" /Vn%1_%3
echo.
echo %fxc%
%fxc% || set error=1
exit /b
:CompileComputeShaderxbox
set fxc==%XBOXFXC% %1.hlsl %FXCOPTS% /Tcs_5_1 %XBOXOPTS% /E%2 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%2.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%2.pdb" /Vn%1_%2
set fxc==%XBOXFXC% "%1.hlsl" %FXCOPTS% /Tcs_5_1 %XBOXOPTS% /E%2 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%2.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%2.pdb" /Vn%1_%2
echo.
echo %fxc%
%fxc% || set error=1
exit /b
:CompileShadergxdk
set dxc=%XBOXDXC% %1.fx %FXCOPTS% /T%2_6_0 /E%3 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%3.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%3.pdb" /Vn%1_%3
set dxc=%XBOXDXC% "%1.fx" %FXCOPTS% /T%2_6_0 /E%3 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%3.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%3.pdb" /Vn%1_%3
echo.
echo %dxc%
%dxc% || set error=1
exit /b
:CompileComputeShadergxdk
set dxc=%XBOXDXC% %1.hlsl %FXCOPTS% /Tcs_6_0 /E%2 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%2.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%2.pdb" /Vn%1_%2
set dxc=%XBOXDXC% "%1.hlsl" %FXCOPTS% /Tcs_6_0 /E%2 "/Fh%CompileShadersOutput%\%XBOXPREFIX%%1_%2.inc" "/Fd%CompileShadersOutput%\%XBOXPREFIX%%1_%2.pdb" /Vn%1_%2
echo.
echo %dxc%
%dxc% || set error=1
@ -342,9 +348,13 @@ exit /b
:needxdk
echo ERROR: CompileShaders xbox requires the Microsoft Xbox One XDK
echo (try re-running from the XDK Command Prompt)
exit /b
exit /b 1
:needgxdk
echo ERROR: CompileShaders gxdk requires the Microsoft Gaming SDK
echo (try re-running from the Gaming GXDK Command Prompt)
exit /b
echo (try re-running from the Microsoft GDKX Gaming Command Prompt)
exit /b 1
:needdxil
echo ERROR: CompileShaders dxil requires DXC.EXE
exit /b 1

Просмотреть файл

@ -154,14 +154,17 @@ namespace
//--------------------------------------------------------------------------------------
namespace DirectX
{
namespace Internal
inline namespace DX12
{
IWICImagingFactory2* GetWIC() noexcept;
// Also used by ScreenGrab
namespace Internal
{
IWICImagingFactory2* GetWIC() noexcept;
// Also used by ScreenGrab
}
}
}
IWICImagingFactory2* DirectX::Internal::GetWIC() noexcept
IWICImagingFactory2* DirectX::DX12::Internal::GetWIC() noexcept
{
static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT;
@ -178,7 +181,7 @@ IWICImagingFactory2* DirectX::Internal::GetWIC() noexcept
return factory;
}
using namespace Internal;
using namespace DirectX::DX12::Internal;
namespace
{

Просмотреть файл

@ -76,7 +76,12 @@ struct CD3DX12_VIEWPORT : public D3D12_VIEWPORT
FLOAT minDepth = D3D12_MIN_DEPTH,
FLOAT maxDepth = D3D12_MAX_DEPTH ) noexcept
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pResource->GetDesc(&tmpDesc);
#endif
const UINT64 SubresourceWidth = Desc.Width >> mipSlice;
const UINT64 SubresourceHeight = Desc.Height >> mipSlice;
switch (Desc.Dimension)
@ -2040,7 +2045,12 @@ inline UINT64 GetRequiredIntermediateSize(
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources) noexcept
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
UINT64 RequiredSize = 0;
ID3D12Device* pDevice = nullptr;
@ -2066,8 +2076,14 @@ inline UINT64 UpdateSubresources(
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) noexcept
{
// Minor validation
#if defined(_MSC_VER) || !defined(_WIN32)
const auto IntermediateDesc = pIntermediate->GetDesc();
const auto DestinationDesc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc1, tmpDesc2;
const auto& IntermediateDesc = *pIntermediate->GetDesc(&tmpDesc1);
const auto& DestinationDesc = *pDestinationResource->GetDesc(&tmpDesc2);
#endif
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > SIZE_T(-1) ||
@ -2125,8 +2141,14 @@ inline UINT64 UpdateSubresources(
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_INFO* pSrcData) noexcept
{
// Minor validation
#if defined(_MSC_VER) || !defined(_WIN32)
const auto IntermediateDesc = pIntermediate->GetDesc();
const auto DestinationDesc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc1, tmpDesc2;
const auto& IntermediateDesc = *pIntermediate->GetDesc(&tmpDesc1);
const auto& DestinationDesc = *pDestinationResource->GetDesc(&tmpDesc2);
#endif
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > SIZE_T(-1) ||
@ -2194,7 +2216,12 @@ inline UINT64 UpdateSubresources(
auto pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
auto pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
@ -2232,7 +2259,12 @@ inline UINT64 UpdateSubresources(
auto pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
auto pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
@ -2260,7 +2292,12 @@ inline UINT64 UpdateSubresources(
UINT NumRows[MaxSubresources];
UINT64 RowSizesInBytes[MaxSubresources];
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize);
@ -2287,7 +2324,12 @@ inline UINT64 UpdateSubresources(
UINT NumRows[MaxSubresources];
UINT64 RowSizesInBytes[MaxSubresources];
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize);
@ -4071,20 +4113,20 @@ public:
D3D12_BARRIER_SUBRESOURCE_RANGE{ Subresource, 0, 0, 0, 0, 0 }
{}
CD3DX12_BARRIER_SUBRESOURCE_RANGE(
UINT FirstMipLevel,
UINT NumMips,
UINT FirstArraySlice,
UINT NumArraySlices,
UINT FirstPlane = 0,
UINT NumPlanes = 1) noexcept :
UINT firstMipLevel,
UINT numMips,
UINT firstArraySlice,
UINT numArraySlices,
UINT firstPlane = 0,
UINT numPlanes = 1) noexcept :
D3D12_BARRIER_SUBRESOURCE_RANGE
{
FirstMipLevel,
NumMips,
FirstArraySlice,
NumArraySlices,
FirstPlane,
NumPlanes
firstMipLevel,
numMips,
firstArraySlice,
numArraySlices,
firstPlane,
numPlanes
}
{}
};

Просмотреть файл

@ -10,7 +10,7 @@
#pragma once
// Off by default warnings
#pragma warning(disable : 4619 4061 4265 4355 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4987 5026 5027 5031 5032 5039 5045 5219 5246 26812)
#pragma warning(disable : 4619 4061 4265 4355 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4987 5026 5027 5031 5032 5039 5045 5219 5246 5264 26812)
// C4619 #pragma warning: there is no warning number 'X'
// C4061 enumerator 'X' in switch of enum 'X' is not explicitly handled by a case label
// C4265 class has virtual functions, but destructor is not virtual
@ -35,6 +35,7 @@
// C5045 Spectre mitigation warning
// C5219 implicit conversion from 'int' to 'float', possible loss of data
// C5246 the initialization of a subobject should be wrapped in braces
// C5264 'const' variable is not used
// 26812: The enum type 'x' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
// XBox One XDK related Off by default warnings
@ -234,6 +235,12 @@
#include <wincodec.h>
#if defined(NTDDI_WIN10_FE) || defined(__MINGW32__)
#include <ocidl.h>
#else
#include <OCIdl.h>
#endif
#ifndef __MINGW32__
// DirectX Tool Kit for Audio is in all versions of DirectXTK12
#include <mmreg.h>

Просмотреть файл

@ -60,7 +60,6 @@ namespace DirectX
public:
HDRColorA() = default;
HDRColorA(float _r, float _g, float _b, float _a) noexcept : r(_r), g(_g), b(_b), a(_a) {}
HDRColorA(const HDRColorA& c) noexcept : r(c.r), g(c.g), b(c.b), a(c.a) {}
// binary operators
HDRColorA operator + (const HDRColorA& c) const noexcept

Просмотреть файл

@ -452,7 +452,6 @@ namespace
public:
INTColor() = default;
INTColor(int nr, int ng, int nb) noexcept : r(nr), g(ng), b(nb), pad(0) {}
INTColor(const INTColor& c) noexcept : r(c.r), g(c.g), b(c.b), pad(0) {}
INTColor& operator += (_In_ const INTColor& c) noexcept
{
@ -751,9 +750,12 @@ namespace
float RoughMSE(_Inout_ EncodeParams* pEP) const noexcept;
private:
static const ModeDescriptor ms_aDesc[][82];
static const ModeInfo ms_aInfo[];
static const int ms_aModeToInfo[];
static constexpr uint8_t c_NumModes = 14;
static constexpr uint8_t c_NumModeInfo = 32;
static const ModeDescriptor ms_aDesc[c_NumModes][82];
static const ModeInfo ms_aInfo[c_NumModes];
static const int ms_aModeToInfo[c_NumModeInfo];
};
// BC67 compression (16b bits per texel)
@ -856,12 +858,14 @@ namespace
static float RoughMSE(_Inout_ EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode) noexcept;
private:
static const ModeInfo ms_aInfo[];
static constexpr uint8_t c_NumModes = 8;
static const ModeInfo ms_aInfo[c_NumModes];
};
}
// BC6H Compression
const D3DX_BC6H::ModeDescriptor D3DX_BC6H::ms_aDesc[14][82] =
const D3DX_BC6H::ModeDescriptor D3DX_BC6H::ms_aDesc[D3DX_BC6H::c_NumModes][82] =
{
{ // Mode 1 (0x00) - 10 5 5 5
{ M, 0}, { M, 1}, {GY, 4}, {BY, 4}, {BZ, 4}, {RW, 0}, {RW, 1}, {RW, 2}, {RW, 3}, {RW, 4},
@ -1033,7 +1037,7 @@ const D3DX_BC6H::ModeDescriptor D3DX_BC6H::ms_aDesc[14][82] =
};
// Mode, Partitions, Transformed, IndexPrec, RGBAPrec
const D3DX_BC6H::ModeInfo D3DX_BC6H::ms_aInfo[] =
const D3DX_BC6H::ModeInfo D3DX_BC6H::ms_aInfo[D3DX_BC6H::c_NumModes] =
{
{0x00, 1, true, 3, { { LDRColorA(10,10,10,0), LDRColorA(5, 5, 5,0) }, { LDRColorA(5,5,5,0), LDRColorA(5,5,5,0) } } }, // Mode 1
{0x01, 1, true, 3, { { LDRColorA(7, 7, 7,0), LDRColorA(6, 6, 6,0) }, { LDRColorA(6,6,6,0), LDRColorA(6,6,6,0) } } }, // Mode 2
@ -1051,7 +1055,7 @@ const D3DX_BC6H::ModeInfo D3DX_BC6H::ms_aInfo[] =
{0x0f, 0, true, 4, { { LDRColorA(16,16,16,0), LDRColorA(4, 4, 4,0) }, { LDRColorA(0,0,0,0), LDRColorA(0,0,0,0) } } }, // Mode 14
};
const int D3DX_BC6H::ms_aModeToInfo[] =
const int D3DX_BC6H::ms_aModeToInfo[D3DX_BC6H::c_NumModeInfo] =
{
0, // Mode 1 - 0x00
1, // Mode 2 - 0x01
@ -1088,7 +1092,7 @@ const int D3DX_BC6H::ms_aModeToInfo[] =
};
// BC7 compression: uPartitions, uPartitionBits, uPBits, uRotationBits, uIndexModeBits, uIndexPrec, uIndexPrec2, RGBAPrec, RGBAPrecWithP
const D3DX_BC7::ModeInfo D3DX_BC7::ms_aInfo[] =
const D3DX_BC7::ModeInfo D3DX_BC7::ms_aInfo[D3DX_BC7::c_NumModes] =
{
{2, 4, 6, 0, 0, 3, 0, LDRColorA(4,4,4,0), LDRColorA(5,5,5,0)},
// Mode 0: Color only, 3 Subsets, RGBP 4441 (unique P-bit), 3-bit indecies, 16 partitions
@ -1655,17 +1659,14 @@ void D3DX_BC6H::Decode(bool bSigned, HDRColorA* pOut) const noexcept
uMode = static_cast<uint8_t>((unsigned(GetBits(uStartBit, 3)) << 2) | uMode);
}
assert(uMode < 32);
_Analysis_assume_(uMode < 32);
assert(uMode < c_NumModeInfo);
_Analysis_assume_(uMode < c_NumModeInfo);
if (ms_aModeToInfo[uMode] >= 0)
{
assert(static_cast<unsigned int>(ms_aModeToInfo[uMode]) < std::size(ms_aInfo));
_Analysis_assume_(ms_aModeToInfo[uMode] < std::size(ms_aInfo));
assert(static_cast<unsigned int>(ms_aModeToInfo[uMode]) < c_NumModes);
_Analysis_assume_(ms_aModeToInfo[uMode] < c_NumModes);
const ModeDescriptor* desc = ms_aDesc[ms_aModeToInfo[uMode]];
assert(static_cast<unsigned int>(ms_aModeToInfo[uMode]) < std::size(ms_aDesc));
_Analysis_assume_(ms_aModeToInfo[uMode] < std::size(ms_aDesc));
const ModeInfo& info = ms_aInfo[ms_aModeToInfo[uMode]];
INTEndPntPair aEndPts[BC6H_MAX_REGIONS] = {};
@ -1811,7 +1812,7 @@ void D3DX_BC6H::Encode(bool bSigned, const HDRColorA* const pIn) noexcept
EncodeParams EP(pIn, bSigned);
for (EP.uMode = 0; EP.uMode < std::size(ms_aInfo) && EP.fBestErr > 0; ++EP.uMode)
for (EP.uMode = 0; EP.uMode < c_NumModes && EP.fBestErr > 0; ++EP.uMode)
{
const uint8_t uShapes = ms_aInfo[EP.uMode].uPartitions ? 32u : 1u;
// Number of rough cases to look at. reasonable values of this are 1, uShapes/4, and uShapes
@ -1936,6 +1937,9 @@ _Use_decl_annotations_
bool D3DX_BC6H::EndPointsFit(const EncodeParams* pEP, const INTEndPntPair aEndPts[]) noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const bool bTransformed = ms_aInfo[pEP->uMode].bTransformed;
const bool bIsSigned = pEP->bSigned;
const LDRColorA& Prec0 = ms_aInfo[pEP->uMode].RGBAPrec[0][0];
@ -1978,6 +1982,9 @@ _Use_decl_annotations_
void D3DX_BC6H::GeneratePaletteQuantized(const EncodeParams* pEP, const INTEndPntPair& endPts, INTColor aPalette[]) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const size_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
const size_t uNumIndices = size_t(1) << uIndexPrec;
assert(uNumIndices > 0);
@ -2029,6 +2036,8 @@ _Use_decl_annotations_
float D3DX_BC6H::MapColorsQuantized(const EncodeParams* pEP, const INTColor aColors[], size_t np, const INTEndPntPair &endPts) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
auto const uNumIndices = static_cast<const uint8_t>(1u << uIndexPrec);
@ -2065,6 +2074,9 @@ float D3DX_BC6H::PerturbOne(const EncodeParams* pEP, const INTColor aColors[], s
const INTEndPntPair& oldEndPts, INTEndPntPair& newEndPts, float fOldErr, int do_b) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
uint8_t uPrec;
switch (ch)
{
@ -2178,6 +2190,9 @@ _Use_decl_annotations_
void D3DX_BC6H::OptimizeEndPoints(const EncodeParams* pEP, const float aOrgErr[], const INTEndPntPair aOrgEndPts[], INTEndPntPair aOptEndPts[]) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
assert(uPartitions < BC6H_MAX_REGIONS);
_Analysis_assume_(uPartitions < BC6H_MAX_REGIONS);
@ -2205,6 +2220,9 @@ _Use_decl_annotations_
void D3DX_BC6H::SwapIndices(const EncodeParams* pEP, INTEndPntPair aEndPts[], size_t aIndices[]) noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const size_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
const size_t uNumIndices = size_t(1) << ms_aInfo[pEP->uMode].uIndexPrec;
const size_t uHighIndexBit = uNumIndices >> 1;
@ -2234,6 +2252,9 @@ _Use_decl_annotations_
void D3DX_BC6H::AssignIndices(const EncodeParams* pEP, const INTEndPntPair aEndPts[], size_t aIndices[], float aTotErr[]) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
auto const uNumIndices = static_cast<const uint8_t>(1u << ms_aInfo[pEP->uMode].uIndexPrec);
@ -2276,6 +2297,9 @@ _Use_decl_annotations_
void D3DX_BC6H::QuantizeEndPts(const EncodeParams* pEP, INTEndPntPair* aQntEndPts) const noexcept
{
assert(pEP && aQntEndPts);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const INTEndPntPair* aUnqEndPts = pEP->aUnqEndPts[pEP->uShape];
const LDRColorA& Prec = ms_aInfo[pEP->uMode].RGBAPrec[0][0];
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
@ -2298,6 +2322,9 @@ _Use_decl_annotations_
void D3DX_BC6H::EmitBlock(const EncodeParams* pEP, const INTEndPntPair aEndPts[], const size_t aIndices[]) noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uRealMode = ms_aInfo[pEP->uMode].uMode;
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
@ -2342,6 +2369,9 @@ _Use_decl_annotations_
void D3DX_BC6H::Refine(EncodeParams* pEP) noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
assert(uPartitions < BC6H_MAX_REGIONS);
_Analysis_assume_(uPartitions < BC6H_MAX_REGIONS);
@ -2394,6 +2424,9 @@ void D3DX_BC6H::GeneratePaletteUnquantized(const EncodeParams* pEP, size_t uRegi
assert(pEP);
assert(uRegion < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES);
_Analysis_assume_(uRegion < BC6H_MAX_REGIONS && pEP->uShape < BC6H_MAX_SHAPES);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const INTEndPntPair& endPts = pEP->aUnqEndPts[pEP->uShape][uRegion];
const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
auto const uNumIndices = static_cast<const uint8_t>(1u << uIndexPrec);
@ -2428,6 +2461,9 @@ _Use_decl_annotations_
float D3DX_BC6H::MapColors(const EncodeParams* pEP, size_t uRegion, size_t np, const size_t* auIndex) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uIndexPrec = ms_aInfo[pEP->uMode].uIndexPrec;
auto const uNumIndices = static_cast<const uint8_t>(1u << uIndexPrec);
INTColor aPalette[BC6H_MAX_INDICES];
@ -2455,6 +2491,8 @@ float D3DX_BC6H::RoughMSE(EncodeParams* pEP) const noexcept
assert(pEP);
assert(pEP->uShape < BC6H_MAX_SHAPES);
_Analysis_assume_(pEP->uShape < BC6H_MAX_SHAPES);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
INTEndPntPair* aEndPts = pEP->aUnqEndPts[pEP->uShape];
@ -2838,6 +2876,9 @@ _Use_decl_annotations_
void D3DX_BC7::GeneratePaletteQuantized(const EncodeParams* pEP, size_t uIndexMode, const LDREndPntPair& endPts, LDRColorA aPalette[]) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const size_t uIndexPrec = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec2 : ms_aInfo[pEP->uMode].uIndexPrec;
const size_t uIndexPrec2 = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec : ms_aInfo[pEP->uMode].uIndexPrec2;
const size_t uNumIndices = size_t(1) << uIndexPrec;
@ -2868,6 +2909,9 @@ float D3DX_BC7::PerturbOne(const EncodeParams* pEP, const LDRColorA aColors[], s
const LDREndPntPair &oldEndPts, LDREndPntPair &newEndPts, float fOldErr, uint8_t do_b) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const int prec = ms_aInfo[pEP->uMode].RGBAPrecWithP[ch];
LDREndPntPair tmp_endPts = newEndPts = oldEndPts;
float fMinErr = fOldErr;
@ -2910,6 +2954,9 @@ void D3DX_BC7::Exhaustive(const EncodeParams* pEP, const LDRColorA aColors[], si
float& fOrgErr, LDREndPntPair& optEndPt) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uPrec = ms_aInfo[pEP->uMode].RGBAPrecWithP[ch];
LDREndPntPair tmpEndPt;
if (fOrgErr == 0)
@ -2981,6 +3028,8 @@ void D3DX_BC7::OptimizeOne(const EncodeParams* pEP, const LDRColorA aColors[], s
float fOrgErr, const LDREndPntPair& org, LDREndPntPair& opt) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
float fOptErr = fOrgErr;
opt = org;
@ -3047,6 +3096,9 @@ void D3DX_BC7::OptimizeEndPoints(const EncodeParams* pEP, size_t uShape, size_t
const LDREndPntPair aOrgEndPts[], LDREndPntPair aOptEndPts[]) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
assert(uPartitions < BC7_MAX_REGIONS && uShape < BC7_MAX_SHAPES);
_Analysis_assume_(uPartitions < BC7_MAX_REGIONS && uShape < BC7_MAX_SHAPES);
@ -3072,6 +3124,8 @@ void D3DX_BC7::AssignIndices(const EncodeParams* pEP, size_t uShape, size_t uInd
assert(pEP);
assert(uShape < BC7_MAX_SHAPES);
_Analysis_assume_(uShape < BC7_MAX_SHAPES);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
assert(uPartitions < BC7_MAX_REGIONS);
@ -3149,6 +3203,9 @@ _Use_decl_annotations_
void D3DX_BC7::EmitBlock(const EncodeParams* pEP, size_t uShape, size_t uRotation, size_t uIndexMode, const LDREndPntPair aEndPts[], const size_t aIndex[], const size_t aIndex2[]) noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
assert(uPartitions < BC7_MAX_REGIONS);
_Analysis_assume_(uPartitions < BC7_MAX_REGIONS);
@ -3236,6 +3293,9 @@ _Use_decl_annotations_
void D3DX_BC7::FixEndpointPBits(const EncodeParams* pEP, const LDREndPntPair *pOrigEndpoints, LDREndPntPair *pFixedEndpoints) noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const size_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
assert(uPartitions < BC7_MAX_REGIONS);
_Analysis_assume_(uPartitions < BC7_MAX_REGIONS);
@ -3323,6 +3383,8 @@ float D3DX_BC7::Refine(const EncodeParams* pEP, size_t uShape, size_t uRotation,
assert(pEP);
assert(uShape < BC7_MAX_SHAPES);
_Analysis_assume_(uShape < BC7_MAX_SHAPES);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const size_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;
assert(uPartitions < BC7_MAX_REGIONS);
@ -3379,6 +3441,9 @@ _Use_decl_annotations_
float D3DX_BC7::MapColors(const EncodeParams* pEP, const LDRColorA aColors[], size_t np, size_t uIndexMode, const LDREndPntPair& endPts, float fMinErr) const noexcept
{
assert(pEP);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
const uint8_t uIndexPrec = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec2 : ms_aInfo[pEP->uMode].uIndexPrec;
const uint8_t uIndexPrec2 = uIndexMode ? ms_aInfo[pEP->uMode].uIndexPrec : ms_aInfo[pEP->uMode].uIndexPrec2;
LDRColorA aPalette[BC7_MAX_INDICES];
@ -3404,6 +3469,9 @@ float D3DX_BC7::RoughMSE(EncodeParams* pEP, size_t uShape, size_t uIndexMode) no
assert(pEP);
assert(uShape < BC7_MAX_SHAPES);
_Analysis_assume_(uShape < BC7_MAX_SHAPES);
assert(pEP->uMode < c_NumModes);
_Analysis_assume_(pEP->uMode < c_NumModes);
LDREndPntPair* aEndPts = pEP->aEndPts[uShape];
const uint8_t uPartitions = ms_aInfo[pEP->uMode].uPartitions;

Просмотреть файл

@ -124,6 +124,7 @@ namespace DirectX
size_t __cdecl ComputeScanlines(_In_ DXGI_FORMAT fmt, _In_ size_t height) noexcept;
DXGI_FORMAT __cdecl MakeSRGB(_In_ DXGI_FORMAT fmt) noexcept;
DXGI_FORMAT __cdecl MakeLinear(_In_ DXGI_FORMAT fmt) noexcept;
DXGI_FORMAT __cdecl MakeTypeless(_In_ DXGI_FORMAT fmt) noexcept;
DXGI_FORMAT __cdecl MakeTypelessUNORM(_In_ DXGI_FORMAT fmt) noexcept;
DXGI_FORMAT __cdecl MakeTypelessFLOAT(_In_ DXGI_FORMAT fmt) noexcept;
@ -856,6 +857,15 @@ namespace DirectX
_Out_ size_t& required) noexcept;
//---------------------------------------------------------------------------------
// Direct3D interop
enum CREATETEX_FLAGS : uint32_t
{
CREATETEX_DEFAULT = 0,
CREATETEX_FORCE_SRGB = 0x1,
CREATETEX_IGNORE_SRGB = 0x2,
};
// Direct3D 11 functions
#if defined(__d3d11_h__) || defined(__d3d11_x_h__)
bool __cdecl IsSupportedTexture(_In_ ID3D11Device* pDevice, _In_ const TexMetadata& metadata) noexcept;
@ -870,18 +880,17 @@ namespace DirectX
HRESULT __cdecl CreateTextureEx(
_In_ ID3D11Device* pDevice, _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
_In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ bool forceSRGB,
_In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ CREATETEX_FLAGS flags,
_Outptr_ ID3D11Resource** ppResource) noexcept;
HRESULT __cdecl CreateShaderResourceViewEx(
_In_ ID3D11Device* pDevice, _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
_In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ bool forceSRGB,
_In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ CREATETEX_FLAGS flags,
_Outptr_ ID3D11ShaderResourceView** ppSRV) noexcept;
HRESULT __cdecl CaptureTexture(_In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _Out_ ScratchImage& result) noexcept;
#endif
//---------------------------------------------------------------------------------
// Direct3D 12 functions
#if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
bool __cdecl IsSupportedTexture(_In_ ID3D12Device* pDevice, _In_ const TexMetadata& metadata) noexcept;
@ -892,7 +901,7 @@ namespace DirectX
HRESULT __cdecl CreateTextureEx(
_In_ ID3D12Device* pDevice, _In_ const TexMetadata& metadata,
_In_ D3D12_RESOURCE_FLAGS resFlags, _In_ bool forceSRGB,
_In_ D3D12_RESOURCE_FLAGS resFlags, _In_ CREATETEX_FLAGS flags,
_Outptr_ ID3D12Resource** ppResource) noexcept;
HRESULT __cdecl PrepareUpload(

Просмотреть файл

@ -24,6 +24,7 @@ DEFINE_ENUM_FLAG_OPERATORS(TEX_PMALPHA_FLAGS);
DEFINE_ENUM_FLAG_OPERATORS(TEX_COMPRESS_FLAGS);
DEFINE_ENUM_FLAG_OPERATORS(CNMAP_FLAGS);
DEFINE_ENUM_FLAG_OPERATORS(CMSE_FLAGS);
DEFINE_ENUM_FLAG_OPERATORS(CREATETEX_FLAGS);
// WIC_FILTER modes match TEX_FILTER modes
constexpr WIC_FLAGS operator|(WIC_FLAGS a, TEX_FILTER_FLAGS b) { return static_cast<WIC_FLAGS>(static_cast<unsigned long>(a) | static_cast<unsigned long>(b & TEX_FILTER_MODE_MASK)); }

Просмотреть файл

@ -12,7 +12,7 @@
#pragma once
// Off by default warnings
#pragma warning(disable : 4619 4616 4061 4265 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4987 5026 5027 5031 5032 5039 5045 5219 5246 26812)
#pragma warning(disable : 4619 4616 4061 4265 4365 4571 4623 4625 4626 4628 4668 4710 4711 4746 4774 4820 4987 5026 5027 5031 5032 5039 5045 5219 5246 5264 26812)
// C4619/4616 #pragma warning warnings
// C4061 enumerator 'X' in switch of enum 'X' is not explicitly handled by a case label
// C4265 class has virtual functions, but destructor is not virtual
@ -36,6 +36,7 @@
// C5045 Spectre mitigation warning
// C5219 implicit conversion from 'int' to 'float', possible loss of data
// C5246 the initialization of a subobject should be wrapped in braces
// C5264 'const' variable is not used
// 26812: The enum type 'x' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
// Windows 8.1 SDK related Off by default warnings
@ -153,9 +154,9 @@
#include "DirectXTex.h"
#ifdef _WIN32
#include <malloc.h>
#ifdef _WIN32
#if defined(NTDDI_WIN10_FE) || defined(__MINGW32__)
#include <ole2.h>
#else

Просмотреть файл

@ -1183,6 +1183,41 @@ DXGI_FORMAT DirectX::MakeSRGB(DXGI_FORMAT fmt) noexcept
}
//-------------------------------------------------------------------------------------
// Converts to an non-SRGB equivalent type
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
DXGI_FORMAT DirectX::MakeLinear(DXGI_FORMAT fmt) noexcept
{
switch (fmt)
{
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case DXGI_FORMAT_BC1_UNORM_SRGB:
return DXGI_FORMAT_BC1_UNORM;
case DXGI_FORMAT_BC2_UNORM_SRGB:
return DXGI_FORMAT_BC2_UNORM;
case DXGI_FORMAT_BC3_UNORM_SRGB:
return DXGI_FORMAT_BC3_UNORM;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
return DXGI_FORMAT_B8G8R8X8_UNORM;
case DXGI_FORMAT_BC7_UNORM_SRGB:
return DXGI_FORMAT_BC7_UNORM;
default:
return fmt;
}
}
//-------------------------------------------------------------------------------------
// Converts to a format to an equivalent TYPELESS format if available
//-------------------------------------------------------------------------------------

Просмотреть файл

@ -169,6 +169,7 @@
<OpenMPSupport>true</OpenMPSupport>
<AdditionalOptions>/Zc:twoPhase- /Zc:__cplusplus /ZH:SHA_256 %(AdditionalOptions)</AdditionalOptions>
<ExternalWarningLevel>Level4</ExternalWarningLevel>
<GuardEHContMetadata>true</GuardEHContMetadata>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
@ -196,6 +197,7 @@
<OpenMPSupport>true</OpenMPSupport>
<AdditionalOptions>/Zc:twoPhase- /Zc:__cplusplus /ZH:SHA_256 %(AdditionalOptions)</AdditionalOptions>
<ExternalWarningLevel>Level4</ExternalWarningLevel>
<GuardEHContMetadata>true</GuardEHContMetadata>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>

Просмотреть файл

@ -6,11 +6,11 @@ http://go.microsoft.com/fwlink/?LinkId=248926
Copyright (c) Microsoft Corporation.
**May 9, 2022**
**October 17, 2022**
This package contains DirectXTex, a shared source library for reading and writing ``.DDS`` files, and performing various texture content processing operations including resizing, format conversion, mip-map generation, block compression for Direct3D runtime texture resources, and height-map to normal-map conversion. This library makes use of the Windows Image Component (WIC) APIs. It also includes ``.TGA`` and ``.HDR`` readers and writers since these image file formats are commonly used for texture content processing pipelines, but are not currently supported by a built-in WIC codec.
This code is designed to build with Visual Studio 2019 (16.9 or later), Visual Studio 2022, or clang for Windows v11 or later. Use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later is required.
This code is designed to build with Visual Studio 2019 (16.11), Visual Studio 2022, or clang for Windows v11 or later. Use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later is required.
These components are designed to work without requiring any content from the legacy DirectX SDK. For details, see [Where is the DirectX SDK?](https://aka.ms/dxsdk).
@ -71,6 +71,8 @@ For the latest version of DirectXTex, bug reports, etc. please visit the project
## Release Notes
* Starting with the July 2022 release, the ``bool forceSRGB`` parameter for the CreateTextureEx and CreateShaderResourceViewEx functions is now a ``CREATETEX_FLAGS`` typed enum bitmask flag parameter. This may have a *breaking change* impact to client code. Replace ``true`` with ``CREATETEX_FORCE_SRGB`` and ``false`` with ``CREATETEX_DEFAULT``.
* Starting with the June 2020 release, this library makes use of typed enum bitmask flags per the recommendation of the _C++ Standard_ section *17.5.2.1.3 Bitmask types*. This is consistent with Direct3D 12's use of the ``DEFINE_ENUM_FLAG_OPERATORS`` macro. This may have *breaking change* impacts to client code:
* You cannot pass the ``0`` literal as your flags value. Instead you must make use of the appropriate default enum value: ``CP_FLAGS_NONE``, ``DDS_FLAGS_NONE``, ``WIC_FLAGS_NONE``, ``TEX_FR_ROTATE0``, ``TEX_FILTER_DEFAULT``, ``TEX_FILTER_DEFAULT``, ``TEX_FILTER_DEFAULT``, ``CNMAP_DEFAULT``, or ``CNMAP_DEFAULT``.

Просмотреть файл

@ -44,7 +44,7 @@ endlocal
exit /b 0
:CompileShader
set fxc=%PCFXC% %1.hlsl %FXCOPTS% /Tcs_4_0 /E%2 "/Fh%CompileShadersOutput%\%1_%2.inc" "/Fd%CompileShadersOutput%\%1_%2.pdb" /Vn%1_%2
set fxc=%PCFXC% "%1.hlsl" %FXCOPTS% /Tcs_4_0 /E%2 "/Fh%CompileShadersOutput%\%1_%2.inc" "/Fd%CompileShadersOutput%\%1_%2.pdb" /Vn%1_%2
echo.
echo %fxc%
%fxc% || set error=1

Просмотреть файл

@ -76,7 +76,12 @@ struct CD3DX12_VIEWPORT : public D3D12_VIEWPORT
FLOAT minDepth = D3D12_MIN_DEPTH,
FLOAT maxDepth = D3D12_MAX_DEPTH ) noexcept
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pResource->GetDesc(&tmpDesc);
#endif
const UINT64 SubresourceWidth = Desc.Width >> mipSlice;
const UINT64 SubresourceHeight = Desc.Height >> mipSlice;
switch (Desc.Dimension)
@ -2040,7 +2045,12 @@ inline UINT64 GetRequiredIntermediateSize(
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources) noexcept
{
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
UINT64 RequiredSize = 0;
ID3D12Device* pDevice = nullptr;
@ -2066,8 +2076,14 @@ inline UINT64 UpdateSubresources(
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) noexcept
{
// Minor validation
#if defined(_MSC_VER) || !defined(_WIN32)
const auto IntermediateDesc = pIntermediate->GetDesc();
const auto DestinationDesc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc1, tmpDesc2;
const auto& IntermediateDesc = *pIntermediate->GetDesc(&tmpDesc1);
const auto& DestinationDesc = *pDestinationResource->GetDesc(&tmpDesc2);
#endif
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > SIZE_T(-1) ||
@ -2125,8 +2141,14 @@ inline UINT64 UpdateSubresources(
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_INFO* pSrcData) noexcept
{
// Minor validation
#if defined(_MSC_VER) || !defined(_WIN32)
const auto IntermediateDesc = pIntermediate->GetDesc();
const auto DestinationDesc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc1, tmpDesc2;
const auto& IntermediateDesc = *pIntermediate->GetDesc(&tmpDesc1);
const auto& DestinationDesc = *pDestinationResource->GetDesc(&tmpDesc2);
#endif
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > SIZE_T(-1) ||
@ -2194,7 +2216,12 @@ inline UINT64 UpdateSubresources(
auto pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
auto pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
@ -2232,7 +2259,12 @@ inline UINT64 UpdateSubresources(
auto pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
auto pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
@ -2260,7 +2292,12 @@ inline UINT64 UpdateSubresources(
UINT NumRows[MaxSubresources];
UINT64 RowSizesInBytes[MaxSubresources];
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize);
@ -2287,7 +2324,12 @@ inline UINT64 UpdateSubresources(
UINT NumRows[MaxSubresources];
UINT64 RowSizesInBytes[MaxSubresources];
#if defined(_MSC_VER) || !defined(_WIN32)
const auto Desc = pDestinationResource->GetDesc();
#else
D3D12_RESOURCE_DESC tmpDesc;
const auto& Desc = *pDestinationResource->GetDesc(&tmpDesc);
#endif
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize);
@ -4071,20 +4113,20 @@ public:
D3D12_BARRIER_SUBRESOURCE_RANGE{ Subresource, 0, 0, 0, 0, 0 }
{}
CD3DX12_BARRIER_SUBRESOURCE_RANGE(
UINT FirstMipLevel,
UINT NumMips,
UINT FirstArraySlice,
UINT NumArraySlices,
UINT FirstPlane = 0,
UINT NumPlanes = 1) noexcept :
UINT firstMipLevel,
UINT numMips,
UINT firstArraySlice,
UINT numArraySlices,
UINT firstPlane = 0,
UINT numPlanes = 1) noexcept :
D3D12_BARRIER_SUBRESOURCE_RANGE
{
FirstMipLevel,
NumMips,
FirstArraySlice,
NumArraySlices,
FirstPlane,
NumPlanes
firstMipLevel,
numMips,
firstArraySlice,
numArraySlices,
firstPlane,
numPlanes
}
{}
};

Просмотреть файл

@ -16,6 +16,7 @@
#include <XGame.h>
#include <XGameRuntimeFeature.h>
#include <XGameUI.h>
#include <XNetworking.h>
#include <XSystem.h>
#ifdef __clang__
@ -41,9 +42,7 @@ namespace
_Use_decl_annotations_
LiveResources::LiveResources(XTaskQueueHandle queue, bool autoManageUser, bool isGuestUserAllowed) noexcept(false):
#ifdef _GAMING_XBOX
m_networkConnectivityChangedHandle{},
#endif
m_networkConnectivityChangedToken{},
m_isNetworkAvailable(false),
m_autoManageUser(autoManageUser),
m_isGuestUserAllowed(isGuestUserAllowed),
@ -74,59 +73,57 @@ LiveResources::LiveResources(XTaskQueueHandle queue, bool autoManageUser, bool i
char scidBuffer[64] = {};
sprintf_s(scidBuffer, "00000000-0000-0000-0000-0000%08x", m_titleId);
XblInitArgs xblInit = { m_asyncQueue, scidBuffer };
hr = XblInitialize(&xblInit);
DX::ThrowIfFailed(hr);
m_scid = scidBuffer;
#ifdef _GAMING_XBOX
if (XGameRuntimeIsFeatureAvailable(XGameRuntimeFeature::XNetworking))
{
// Listen for network connectivity changes
NotifyNetworkConnectivityHintChange(
[](void* context, NL_NETWORK_CONNECTIVITY_HINT connectivityHint)
{
auto liveResources = static_cast<LiveResources*>(context);
liveResources->m_isNetworkAvailable =
connectivityHint.ConnectivityLevel != NL_NETWORK_CONNECTIVITY_LEVEL_HINT::NetworkConnectivityLevelHintUnknown;
}, // Callback function
this, // Context object
true, // Notify immediately with the current status
&m_networkConnectivityChangedHandle // Notification handle
);
}
else
#endif
{
// Assume network stack is ready on desktop
m_isNetworkAvailable = true;
}
// Listen for network connectivity changes
hr = XNetworkingRegisterConnectivityHintChanged(
m_asyncQueue,
this,
[](void* context, const XNetworkingConnectivityHint* connectivityHint)
{
auto liveResources = static_cast<LiveResources*>(context);
liveResources->m_isNetworkAvailable =
connectivityHint->connectivityLevel != XNetworkingConnectivityLevelHint::Unknown;
},
&m_networkConnectivityChangedToken);
DX::ThrowIfFailed(hr);
XNetworkingConnectivityHint hint{};
XNetworkingGetConnectivityHint(&hint);
m_isNetworkAvailable = hint.connectivityLevel != XNetworkingConnectivityLevelHint::Unknown;
}
LiveResources::~LiveResources()
{
#ifdef _GAMING_XBOX
if (m_networkConnectivityChangedHandle)
if (m_xboxLiveContext)
{
CancelMibChangeNotify2(m_networkConnectivityChangedHandle);
XblContextCloseHandle(m_xboxLiveContext);
}
if (m_xboxLiveUser)
{
XUserCloseHandle(m_xboxLiveUser);
}
#endif
if (m_asyncQueue)
{
XTaskQueueCloseHandle(m_asyncQueue);
m_asyncQueue = nullptr;
}
XUserUnregisterForChangeEvent(m_userChangedEventToken, false);
XNetworkingUnregisterConnectivityHintChanged(m_networkConnectivityChangedToken, false);
auto async = new XAsyncBlock{};
XblCleanupAsync(async);
XTaskQueueCloseHandle(m_asyncQueue);
}
void LiveResources::Initialize()
{
XUserRegisterForChangeEvent(m_asyncQueue, this, [](void *context, const XUserLocalId userLocalId, XUserChangeEvent event)
XUserRegisterForChangeEvent(m_asyncQueue, this, [](void *context, const XUserLocalId userLocalId, XUserChangeEvent event)
{
auto pThis = reinterpret_cast<LiveResources*>(context);
auto pThis = static_cast<LiveResources*>(context);
switch (event)
{
@ -281,7 +278,7 @@ void LiveResources::SignInSilently()
pThis->HandleError(result);
}
}
delete async;
};

Просмотреть файл

@ -74,9 +74,7 @@ namespace ATG
void HandleError(HRESULT error);
void InitializeXboxServices();
#ifdef _GAMING_XBOX
HANDLE m_networkConnectivityChangedHandle;
#endif
XTaskQueueRegistrationToken m_networkConnectivityChangedToken;
bool m_isNetworkAvailable;
bool m_autoManageUser;

144
README.md
Просмотреть файл

@ -4,14 +4,14 @@ This repo contains game development samples written by the Microsoft Xbox Advanc
* [Kits](/Kits) contains support code used by the samples
* [Media](/Media) contains media files used by the samples
* [Samples](#Samples-by-category) contains samples
* [Audio](#Audio)
* [IntroGraphics](#Intro-Graphics)
* [Graphics](#Graphics)
* [Live](#Live)
* [System](#System)
* [Tools](#Tools)
* [xCloud](#xCloud)
* [Samples](../../../wiki/SampleList) contains samples
* [Audio](../../../wiki/SampleList#Audio)
* [IntroGraphics](../../../wiki/SampleList#Intro-Graphics)
* [Graphics](../../../wiki/SampleList#Graphics)
* [Live](../../../wiki/SampleList#Live)
* [System](../../../wiki/SampleList#System)
* [Tools](../../../wiki/SampleList#Tools)
* [xCloud](../../../wiki/SampleList#xCloud)
# Requirements
@ -36,130 +36,6 @@ This project may contain trademarks or logos for projects, products, or services
For more ATG samples, see [DirectML Samples](https://github.com/microsoft/DirectML), [PlayFab-Samples](https://github.com/PlayFab/PlayFab-Samples), [Xbox-ATG-Samples](https://github.com/microsoft/Xbox-ATG-Samples), and [Xbox-LIVE-Samples](https://github.com/microsoft/xbox-live-samples).
## Samples by category
## Samples list by category
### Audio
| Path| Xbox| PC| Tool|
|----------------------------------------| ------| ------| ------|
| AdvancedSpatialSounds| [Xbox](Samples/Audio/AdvancedSpatialSounds)| | |
| InGameChat| [Xbox](Samples/Audio/InGameChat)| [PC](Samples/Audio/InGameChat)| |
| SimplePlay3DSound| [Xbox](Samples/Audio/SimplePlay3DSound)| | |
| SimplePlaySound| [Xbox](Samples/Audio/SimplePlaySound)| | |
| SimplePlaySoundStream| [Xbox](Samples/Audio/SimplePlaySoundStream)| | |
| SimpleSpatialPlaySound| [Xbox](Samples/Audio/SimpleSpatialPlaySound)| | |
| SimpleWASAPICapture| [Xbox](Samples/Audio/SimpleWASAPICapture)| | |
| SimpleWASAPIPlaySound| [Xbox](Samples/Audio/SimpleWASAPIPlaySound)| | |
### Graphics
| Path| Xbox| PC| Tool|
|----------------------------------------| ------| ------| ------|
| AdvancedESRAM| [Xbox](Samples/Graphics/AdvancedESRAM)| | |
| Antialiasing| [Xbox](Samples/Graphics/Antialiasing)| | |
| ComputeParticles| [Xbox](Samples/Graphics/ComputeParticles)| | |
| DeferredParticles| [Xbox](Samples/Graphics/DeferredParticles)| | |
| DXRTriangle| [Xbox](Samples/Graphics/DXRTriangle)| [PC](Samples/Graphics/DXRTriangle)| |
| DynamicLOD| [Xbox](Samples/Graphics/DynamicLOD)| [PC](Samples/Graphics/DynamicLOD)| |
| ExecuteIndirect| [Xbox](Samples/Graphics/ExecuteIndirect)| | |
| FastBlockCompress| [Xbox](Samples/Graphics/FastBlockCompress)| | |
| GeometricExpansion| [Xbox](Samples/Graphics/GeometricExpansion)| [PC](Samples/Graphics/GeometricExpansion)| |
| HDR10| [Xbox](Samples/Graphics/HDR10)| | |
| HistogramCS| [Xbox](Samples/Graphics/HistogramCS)| | |
| HlslCompile| [Xbox](Samples/Graphics/HlslCompile)| | [Tool](Samples/Graphics/HlslCompile)|
| MeshletCull| [Xbox](Samples/Graphics/MeshletCull)| [PC](Samples/Graphics/MeshletCull)| |
| MeshletInstancing| [Xbox](Samples/Graphics/MeshletInstancing)| [PC](Samples/Graphics/MeshletInstancing)| |
| PointSprites| [Xbox](Samples/Graphics/PointSprites)| | |
| SimpleHDR| [Xbox](Samples/Graphics/SimpleHDR)| | |
| SimplePBR| [Xbox](Samples/Graphics/SimplePBR)| [PC](Samples/Graphics/SimplePBR)| |
| SimpleMeshlet| [Xbox](Samples/Graphics/SimpleMeshlet)| [PC](Samples/Graphics/SimpleMeshlet)| |
| SmokeSimulation| [Xbox](Samples/Graphics/SmokeSimulation)| | |
| VisibilityBuffer|[Xbox](Samples/Graphics/VisibilityBuffer/VisibilityBuffer)|[PC](Samples/Graphics/VisibilityBuffer/VisibilityBuffer)| |
### IntroGraphics
| Path| Xbox| PC| Tool|
|----------------------------------------| ------| ------| ------|
| SimpleBezier| [Xbox](Samples/IntroGraphics/SimpleBezier)| | |
| SimpleCompute| [Xbox](Samples/IntroGraphics/SimpleCompute)| | |
| SimpleDeviceAndSwapChain| [Xbox](Samples/IntroGraphics/SimpleDeviceAndSwapChain)| | |
| SimpleDynamicResources| [Xbox](Samples/IntroGraphics/SimpleDynamicResources)| [PC](Samples/IntroGraphics/SimpleDynamicResources)| |
| SimpleInstancing| [Xbox](Samples/IntroGraphics/SimpleInstancing)| | |
| SimpleLighting| [Xbox](Samples/IntroGraphics/SimpleLighting)| | |
| SimpleMeshShader| [Xbox](Samples/IntroGraphics/SimpleMeshShader)| [PC](Samples/IntroGraphics/SimpleMeshShader)| |
| SimpleMSAA| [Xbox](Samples/IntroGraphics/SimpleMSAA)| | |
| SimpleSamplerFeedback| [Xbox](Samples/IntroGraphics/SimpleSamplerFeedback)| | |
| SimpleTexture| [Xbox](Samples/IntroGraphics/SimpleTexture)| | |
| SimpleTriangle| [Xbox](Samples/IntroGraphics/SimpleTriangle)| [PC](Samples/IntroGraphics/SimpleTriangleDesktop)| |
### Live
| Path| Xbox| PC| Tool|
|----------------------------------------| ------| ------| ------|
| Achievements| [Xbox](Samples/Live/Achievements)| [PC](Samples/Live/Achievements)| |
| DownloadableContent| [Xbox](Samples/Live/DownloadableContent)| [PC](Samples/Live/DownloadableContent)| |
| Fundamentals| | [PC](Samples/Live/Fundamentals_Desktop)| |
| InGameStore| [Xbox](Samples/Live/InGameStore)| [PC](Samples/Live/InGameStore)| |
| LeaderboardsEventManaged| [Xbox](Samples/Live/LeaderboardsEventManaged)| [PC](Samples/Live/LeaderboardsEventManaged)| |
| LeaderboardsTitleManaged| [Xbox](Samples/Live/LeaderboardsTitleManaged)| [PC](Samples/Live/LeaderboardsTitleManaged_Desktop)| |
| mDNS| [Xbox](Samples/Live/mDNS)| [PC](Samples/Live/mDNS_Desktop)| |
| MicrosoftStoreServicesClient| [Xbox](Samples/Live/MicrosoftStoreServicesClient)| [PC](Samples/Live/MicrosoftStoreServicesClient)| |
| SimpleCrossGenMPSD| [Xbox](Samples/Live/SimpleCrossGenMPSD)| [PC](Samples/Live/SimpleCrossGenMPSD)| |
| SimpleHttp| [Xbox](Samples/Live/SimpleHttp)| [PC](Samples/Live/SimpleHttp)| |
| SimpleWebSockets| [Xbox](Samples/Live/SimpleWebSockets)| [PC](Samples/Live/SimpleWebSockets)| |
| SocialManager| [Xbox](Samples/Live/SocialManager)| [PC](Samples/Live/SocialManager)| |
| TitleStorage| [Xbox](Samples/Live/TitleStorage)| | |
### System
| Path| Xbox| PC| Tool|
|----------------------------------------| ------| ------| ------|
| AdvancedExceptionHandling| [Xbox](Samples/System/AdvancedExceptionHandling)| [PC](Samples/System/AdvancedExceptionHandling)| |
| OutOfProcDumpTool| [Xbox](Samples/System/AdvancedExceptionHandling)| | |
| AsynchronousProgramming| [Xbox](Samples/System/AsynchronousProgramming)| [PC](Samples/System/AsynchronousProgramming)| |
| Collision| [Xbox](Samples/System/Collision)| [PC](Samples/System/Collision)| |
| CustomEventProvider| [Xbox](Samples/System/CustomEventProvider)| | |
| DataBreakPoints| [Xbox](Samples/System/DataBreakPoints)| [PC](Samples/System/DataBreakPoints)| |
| FrontPanelDemo| [Xbox](Samples/System/FrontPanelDemo)| | |
| FrontPanelDolphin| [Xbox](Samples/System/FrontPanelDolphin)| | |
| FrontPanelGame| [Xbox](Samples/System/FrontPanelGame)| | |
| FrontPanelLogo| [Xbox](Samples/System/FrontPanelLogo)| | |
| FrontPanelText| [Xbox](Samples/System/FrontPanelText)| | |
| GameInputInterfacing| [Xbox](Samples/System/GameInputInterfacing)| | |
| GameInputSequential| [Xbox](Samples/System/GameInputSequential)| | |
| Gamepad| [Xbox](Samples/System/Gamepad)| [PC](Samples/System/Gamepad | |
| GamepadVibration| [Xbox](Samples/System/GamepadVibration)| [PC](Samples/System/GamepadVibration)| |
| GameSave| [Xbox](Samples/System/GameSave)| [PC](Samples/System/GameSave_Desktop)| |
| IntelligentDelivery| [Xbox](Samples/System/IntelligentDelivery)| [PC](Samples/System/IntelligentDelivery)| |
| LocalStorage| [Xbox](Samples/System/LocalStorage)| [PC](Samples/System/LocalStorage)| |
| MouseInput| [Xbox](Samples/System/MouseInput)| | |
| NLSAndLocalization| [Xbox](Samples/System/NLSAndLocalization)| [PC](Samples/System/NLSAndLocalization)| |
| SimpleDirectStorage| [Xbox](Samples/System/SimpleDirectStorage)| | |
| SimpleDirectStorageCombo| [Xbox](Samples/System/SimpleDirectStorageCombo)| [PC](Samples/System/SimpleDirectStorageCombo)| |
| SimpleExceptionHandling| [Xbox](Samples/System/SimpleExceptionHandling)| [PC](Samples/System/SimpleExceptionHandling)| |
| SimpleFFBWheel| [Xbox](Samples/System/SimpleFFBWheel)| | |
| SimpleFrontPanel| [Xbox](Samples/System/SimpleFrontPanel)| | |
| SimplePLM| [Xbox](Samples/System/SimplePLM)| | |
| SimpleUserModel| [Xbox](Samples/System/SimpleUserModel)| | |
| SystemInfo| [Xbox](Samples/System/SystemInfo)| [PC](Samples/System/SystemInfo)| |
| UserManagement| [Xbox](Samples/System/UserManagement)| | |
### Tools
| Path| Xbox| PC| Tool|
|----------------------------------------| ------| ------| ------|
| BWOIExample| [Xbox](Samples/Tools/BWOIExample)| [PC](Samples/Tools/BWOIExample)| |
| CacheTestCombo| [Xbox](Samples/Tools/CacheTestCombo)| [PC](Samples/Tools/CacheTestCombo)| |
| DumpTool| [Xbox](Samples/Tools/DumpTool)| | |
| ConverterApp| | | [Tool](Samples/Tools/MeshletConverter)|
| Runtime| | | [Tool](Samples/Tools/MeshletConverter)|
| OSPrimitiveTestCombo| [Xbox](Samples/Tools/OSPrimitiveTestCombo)| [PC](Samples/Tools/OSPrimitiveTestCombo)| |
| xbgamepad| | | [Tool](Samples/Tools/xbgamepad)|
| xtexconv| | | [Tool](Samples/Tools/xtexconv)|
### xCloud
| Path| Xbox| PC| Tool|
|----------------------------------------| ------| ------| ------|
| SimpleCloudAwareSample| [Xbox](Samples/xCloud/SimpleCloudAwareSample)| | |
[Samples List Wiki](../../../wiki/SampleList)

Просмотреть файл

@ -508,7 +508,7 @@
</ClCompile>
</ItemGroup>
<ItemGroup>
<MGCCompile Include="MicrosoftGame.Config" />
<MGCCompile Include="MicrosoftGameConfig.mgc" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Kits\DirectXTK12\DirectXTK12_GDK_2019.vcxproj">

Просмотреть файл

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Common">
@ -118,7 +118,7 @@
</ClCompile>
</ItemGroup>
<ItemGroup>
<MGCCompile Include="MicrosoftGame.Config" />
<MGCCompile Include="MicrosoftGameConfig.mgc" />
</ItemGroup>
<ItemGroup>
<CopyFileToFolders Include="Assets\Logo.png">

Просмотреть файл

@ -384,7 +384,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
}
else
{
SetWindowLongPtr(hWnd, GWL_STYLE, 0);
SetWindowLongPtr(hWnd, GWL_STYLE, WS_POPUP);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);

Просмотреть файл

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Game configVersion="0">
<Game configVersion="1">
<!-- Version "1" is supported by March 2022 GDK or later -->
<Identity Name="41336MicrosoftATG.InGameChat" Version="1.1.0.0" Publisher="CN=A4954634-DF4B-47C7-AB70-D3215D246AF1" />
@ -10,6 +10,7 @@
</ExecutableList>
<TitleId>6B2BEA70</TitleId>
<MSAAppId>000000004C26F118</MSAAppId>
<ShellVisuals DefaultDisplayName="InGameChat"
PublisherDisplayName="Xbox Advanced Technology Group"

Двоичные данные
Samples/Audio/InGameChat/ReadMe.docx

Двоичный файл не отображается.

Просмотреть файл

@ -42,8 +42,8 @@
#include <grdk.h>
#if _GRDK_VER < 0x4A610D2B /* GXDK Edition 200600 */
#error This sample requires the June 2020 GDK or later
#if _GRDK_VER < 0x55F00C58 /* GDK Edition 220300 */
#error This sample requires the March 2022 GDK or later
#endif
#ifdef _GAMING_XBOX_SCARLETT

Просмотреть файл

@ -8,7 +8,7 @@
#include "pch.h"
#include "AdvancedESRAM.h"
extern void ExitSample();
extern void ExitSample() noexcept;
using namespace DirectX;
using namespace ATG;
@ -107,36 +107,37 @@ namespace
const std::vector<uint16_t> s_triIndex = { 0, 1, 2 };
// Sample Constants
const DXGI_FORMAT c_colorFormat = DXGI_FORMAT_R11G11B10_FLOAT;
const DXGI_FORMAT c_depthFormat = DXGI_FORMAT_D32_FLOAT;
constexpr DXGI_FORMAT c_colorFormat = DXGI_FORMAT_R11G11B10_FLOAT;
constexpr DXGI_FORMAT c_depthFormat = DXGI_FORMAT_D32_FLOAT;
const float c_defaultPhi = XM_2PI / 6.0f;
const float c_defaultRadius = 3.3f;
constexpr float c_defaultPhi = XM_2PI / 6.0f;
constexpr float c_defaultRadius = 3.3f;
//-----------------------------------
// Helper Functions
template <typename T>
void IncrMod(T& value, T mod) {
void IncrMod(T& value, T mod) noexcept
{
T res = (value + 1) % mod;
value = res < 0 ? mod - 1 : res;
}
template <typename T>
void DecrMod(T& value, T mod) {
void DecrMod(T& value, T mod) noexcept
{
int res = int(value) - 1;
value = res < 0 ? mod - 1 : res;
}
void Saturate(float& value) { value = std::max(0.0f, std::min(1.0f, value)); }
void Saturate(float& value) noexcept { value = std::max(0.0f, std::min(1.0f, value)); }
}
#pragma endregion
#pragma region Construction
Sample::Sample()
: m_deviceResources(new DX::DeviceResources(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN))
, m_displayWidth(0)
Sample::Sample() noexcept(false)
: m_displayWidth(0)
, m_displayHeight(0)
, m_frame(0)
, m_theta(0.0f)
@ -148,7 +149,9 @@ Sample::Sample()
, m_updateStats(true)
, m_visData{}
{
std::fill_n(m_esramRatios, _countof(m_esramRatios), 1.0f);
m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN);
std::fill_n(m_esramRatios, std::size(m_esramRatios), 1.0f);
}
Sample::~Sample()
@ -188,6 +191,8 @@ void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %llu", m_frame);
m_deviceResources->WaitForOrigin();
m_timer.Tick([&]()
{
Update(m_timer);
@ -196,10 +201,11 @@ void Sample::Tick()
Render();
PIXEndEvent();
++m_frame;
m_frame++;
}
void Sample::Update(const DX::StepTimer& timer)
// Updates the world.
void Sample::Update(DX::StepTimer const& timer)
{
using ButtonState = DirectX::GamePad::ButtonStateTracker::ButtonState;
@ -326,6 +332,7 @@ void Sample::Update(const DX::StepTimer& timer)
#pragma region Frame Render
// Draws the scene.
void Sample::Render()
{
// Don't try to render anything before the first Update.
@ -360,14 +367,14 @@ void Sample::Render()
// Set descriptor heaps
ID3D12DescriptorHeap* heaps[] = { m_srvPile->Heap(), m_commonStates->Heap() };
commandList->SetDescriptorHeaps(UINT(_countof(heaps)), heaps);
commandList->SetDescriptorHeaps(static_cast<UINT>(std::size(heaps)), heaps);
{
ScopedPixEvent Clear(commandList, PIX_COLOR_DEFAULT, L"Clear");
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
auto const viewport = m_deviceResources->GetScreenViewport();
auto const scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
@ -412,10 +419,11 @@ void Sample::Render()
TransientResource outlineTex[2];
D3D12_GPU_DESCRIPTOR_HANDLE srvHandles[2];
for (uint32_t i = 0; i < _countof(outlineTex); ++i)
for (size_t i = 0; i < std::size(outlineTex); ++i)
{
outlineTex[i] = AcquireTransientTexture(commandList, m_outlineDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, SceneTexture(ST_Outline0 + i));
srvHandles[i] = m_srvPile->WriteDescriptors(m_deviceResources->GetD3DDevice(), SRV_Outline0 + i, &outlineTex[i].SRV, 1);
srvHandles[i] = m_srvPile->WriteDescriptors(m_deviceResources->GetD3DDevice(),
static_cast<uint32_t>(SRV_Outline0 + i), &outlineTex[i].SRV, 1);
handles[ST_Outline0 + i] = outlineTex[i].handle;
}
@ -454,7 +462,7 @@ void Sample::Render()
obj.model->DrawOpaque(commandList, obj.effects.begin());
// Release the outline textures' memory pages back to the allocator.
for (uint32_t i = 0; i < _countof(outlineTex); ++i)
for (size_t i = 0; i < std::size(outlineTex); ++i)
{
m_allocator->Release(commandList, outlineTex[i], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
}
@ -476,10 +484,11 @@ void Sample::Render()
TransientResource bloomTex[2];
D3D12_GPU_DESCRIPTOR_HANDLE srvHandles[2];
for (uint32_t i = 0; i < _countof(bloomTex); ++i)
for (size_t i = 0; i < std::size(bloomTex); ++i)
{
bloomTex[i] = AcquireTransientTexture(commandList, m_bloomDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, SceneTexture(ST_Bloom0 + i));
srvHandles[i] = m_srvPile->WriteDescriptors(m_deviceResources->GetD3DDevice(), SRV_Bloom0 + i, &bloomTex[i].SRV, 1);
srvHandles[i] = m_srvPile->WriteDescriptors(m_deviceResources->GetD3DDevice(),
static_cast<uint32_t>(SRV_Bloom0 + i), &bloomTex[i].SRV, 1);
handles[ST_Bloom0 + i] = bloomTex[i].handle;
}
@ -540,7 +549,7 @@ void Sample::Render()
commandList->CopyResource(colorTex.resource, bloomTex[1].resource);
// We're finished with the bloom textures - release their memory pages back to the allocator.
for (uint32_t i = 0; i < _countof(bloomTex); ++i)
for (size_t i = 0; i < std::size(bloomTex); ++i)
{
m_allocator->Release(commandList, bloomTex[i], D3D12_RESOURCE_STATE_GENERIC_READ);
}
@ -613,7 +622,7 @@ void Sample::DrawHUD(ID3D12GraphicsCommandList* commandList)
{
m_hudBatch->Begin(commandList);
auto safe = SimpleMath::Viewport::ComputeTitleSafeArea(m_displayWidth, m_displayHeight);
auto const safe = SimpleMath::Viewport::ComputeTitleSafeArea(m_displayWidth, m_displayHeight);
wchar_t textBuffer[128] = {};
XMFLOAT2 textPos = XMFLOAT2(float(safe.left), float(safe.top));
@ -748,13 +757,11 @@ void Sample::CreateDeviceDependentResources()
// Create heap
m_srvPile = std::make_unique<DescriptorPile>(device,
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
128,
DescriptorHeapIndex::SRV_Count);
// Load models from disk.
m_models.resize(_countof(s_modelPaths));
m_models.resize(std::size(s_modelPaths));
for (size_t i = 0; i < m_models.size(); ++i)
{
m_models[i] = Model::CreateFromSDKMESH(device, s_modelPaths[i]);
@ -782,8 +789,8 @@ void Sample::CreateDeviceDependentResources()
}
// HUD
auto backBufferRts = RenderTargetState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
auto spritePSD = SpriteBatchPipelineStateDescription(backBufferRts, &CommonStates::AlphaBlend);
const RenderTargetState backBufferRts(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
const SpriteBatchPipelineStateDescription spritePSD(backBufferRts, &CommonStates::AlphaBlend);
m_hudBatch = std::make_unique<SpriteBatch>(device, resourceUpload, spritePSD);
auto finished = resourceUpload.End(m_deviceResources->GetCommandQueue());
@ -795,8 +802,8 @@ void Sample::CreateDeviceDependentResources()
auto effectFactory = EffectFactory(m_srvPile->Heap(), m_commonStates->Heap());
auto objectRTState = RenderTargetState(c_colorFormat, c_depthFormat);
auto objectPSD = EffectPipelineStateDescription(
const RenderTargetState objectRTState(c_colorFormat, c_depthFormat);
const EffectPipelineStateDescription objectPSD(
nullptr,
CommonStates::Opaque,
CommonStates::DepthDefault,
@ -804,7 +811,7 @@ void Sample::CreateDeviceDependentResources()
objectRTState,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
m_scene.resize(_countof(s_sceneDefinition));
m_scene.resize(std::size(s_sceneDefinition));
for (size_t i = 0; i < m_scene.size(); i++)
{
size_t index = s_sceneDefinition[i].modelIndex;
@ -825,8 +832,8 @@ void Sample::CreateDeviceDependentResources()
});
}
auto outlineRtState = RenderTargetState(c_colorFormat, DXGI_FORMAT_UNKNOWN);
auto outlinePSD = EffectPipelineStateDescription(
const RenderTargetState outlineRtState(c_colorFormat, DXGI_FORMAT_UNKNOWN);
const EffectPipelineStateDescription outlinePSD(
&VertexPositionNormalTexture::InputLayout,
CommonStates::Opaque,
CommonStates::DepthNone,
@ -842,11 +849,11 @@ void Sample::CreateDeviceDependentResources()
m_fullScreenTri = GeometricPrimitive::CreateCustom(s_triVertex, s_triIndex);
auto postRtState = RenderTargetState(c_colorFormat, DXGI_FORMAT_UNKNOWN);
const RenderTargetState postRtState(c_colorFormat, DXGI_FORMAT_UNKNOWN);
m_blurEffect = std::make_unique<BasicPostProcess>(device, postRtState, BasicPostProcess::GaussianBlur_5x5);
m_blurEffect->SetGaussianParameter(12.0f);
auto combinePSD = EffectPipelineStateDescription(
const EffectPipelineStateDescription combinePSD(
&VertexPositionNormalTexture::InputLayout,
CommonStates::NonPremultiplied,
CommonStates::DepthNone,
@ -859,7 +866,7 @@ void Sample::CreateDeviceDependentResources()
m_alphaCompositeEffect->SetDiffuseColor(XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f));
m_alphaCompositeEffect->SetAlpha(0.6f);
auto backBufferRtState = RenderTargetState(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN);
const RenderTargetState backBufferRtState(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN);
m_bloomExtractEffect = std::make_unique<BasicPostProcess>(device, postRtState, BasicPostProcess::BloomExtract);
m_bloomExtractEffect->SetBloomExtractParameter(0.9f);
@ -988,7 +995,7 @@ void Sample::UpdateVisualizerRanges(const ResourceHandle(&resources)[ST_Count])
// Calculate ESRAM page ranges for each texture
std::vector<Range> ranges;
for (size_t i = 0; i < _countof(resources); ++i)
for (size_t i = 0; i < std::size(resources); ++i)
{
#ifdef _GAMING_XBOX_XBOXONE
m_allocator->GetEsramRanges(resources[i], ranges);

Просмотреть файл

@ -46,25 +46,33 @@ enum SceneTexture : uint32_t
class Sample
{
public:
Sample();
Sample() noexcept(false);
~Sample();
Sample(Sample&&) = default;
Sample& operator= (Sample&&) = default;
Sample(Sample const&) = delete;
Sample& operator= (Sample const&) = delete;
// Initialization and management
void Initialize(HWND window);
void Uninitialize();
// Basic Sample loop
// Basic render loop
void Tick();
// Messages
void OnSuspending();
void OnResuming();
void OnConstrained() {}
void OnUnConstrained() {}
// Properties
bool RequestHDRMode() const { return m_deviceResources ? (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_EnableHDR) != 0 : false; }
bool RequestHDRMode() const noexcept { return m_deviceResources ? (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_EnableHDR) != 0 : false; }
private:
void Update(const DX::StepTimer& timer);
void Update(DX::StepTimer const& timer);
void Render();
void DrawHUD(ID3D12GraphicsCommandList* commandList);

Просмотреть файл

@ -31,14 +31,13 @@ DeviceResources::DeviceResources(
m_rtvDescriptorSize(0),
m_screenViewport{},
m_scissorRect{},
m_backBufferFormat((flags & c_EnableHDR) ? DXGI_FORMAT_R10G10B10A2_UNORM : backBufferFormat),
m_backBufferFormat(backBufferFormat),
m_depthBufferFormat(depthBufferFormat),
m_backBufferCount(backBufferCount),
m_window(nullptr),
m_d3dFeatureLevel(D3D_FEATURE_LEVEL_12_0),
m_outputSize{0, 0, 1920, 1080},
m_options(flags),
m_gameDVRFormat((flags & c_EnableHDR) ? backBufferFormat : DXGI_FORMAT_UNKNOWN)
m_options(flags)
{
if (backBufferCount < 2 || backBufferCount > MAX_BACK_BUFFER_COUNT)
{
@ -55,12 +54,16 @@ DeviceResources::~DeviceResources()
// Ensure we present a blank screen before cleaning up resources.
if (m_commandQueue)
{
(void)m_commandQueue->PresentX(0, nullptr, nullptr);
std::ignore = m_commandQueue->PresentX(0, nullptr, nullptr);
}
}
// Configures the Direct3D device, and stores handles to it and the device context.
#ifdef _GAMING_XBOX_SCARLETT
void DeviceResources::CreateDeviceResources(D3D12XBOX_CREATE_DEVICE_FLAGS createDeviceFlags)
#else
void DeviceResources::CreateDeviceResources()
#endif
{
// Create the DX12 API device object.
D3D12XBOX_CREATE_DEVICE_PARAMETERS params = {};
@ -77,6 +80,17 @@ void DeviceResources::CreateDeviceResources()
params.GraphicsCommandQueueRingSizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.GraphicsScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.ComputeScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
#ifdef _GAMING_XBOX_SCARLETT
params.CreateDeviceFlags = createDeviceFlags;
#if (_GXDK_VER >= 0x585D070E /* GXDK Edition 221000 */)
if (m_options & c_AmplificationShaders)
{
params.AmplificationShaderIndirectArgsBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.AmplificationShaderPayloadBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
}
#endif
#endif
HRESULT hr = D3D12XboxCreateDevice(
nullptr,
@ -107,7 +121,7 @@ void DeviceResources::CreateDeviceResources()
// Create descriptor heaps for render target views and depth stencil views.
D3D12_DESCRIPTOR_HEAP_DESC rtvDescriptorHeapDesc = {};
rtvDescriptorHeapDesc.NumDescriptors = (m_options & c_EnableHDR) ? (m_backBufferCount * 2) : m_backBufferCount;
rtvDescriptorHeapDesc.NumDescriptors = m_backBufferCount;
rtvDescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
ThrowIfFailed(m_d3dDevice->CreateDescriptorHeap(&rtvDescriptorHeapDesc, IID_GRAPHICS_PPV_ARGS(m_rtvDescriptorHeap.ReleaseAndGetAddressOf())));
@ -152,31 +166,46 @@ void DeviceResources::CreateDeviceResources()
m_fenceEvent.Attach(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
if (!m_fenceEvent.IsValid())
{
throw std::exception("CreateEvent");
throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEventEx");
}
if (m_options & c_Enable4K_UHD)
if (m_options & (c_Enable4K_UHD | c_EnableQHD))
{
switch (XSystemGetDeviceType())
{
case XSystemDeviceType::XboxOne:
case XSystemDeviceType::XboxOneS:
case XSystemDeviceType::XboxScarlettLockhart /* Xbox Series S */:
m_options &= ~c_Enable4K_UHD;
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 1080p (1920 x 1080)\n");
#endif
m_options &= ~(c_Enable4K_UHD | c_EnableQHD);
break;
case XSystemDeviceType::XboxScarlettLockhart /* Xbox Series S */:
m_options &= ~c_Enable4K_UHD;
if (m_options & c_EnableQHD)
{
m_outputSize = { 0, 0, 2560, 1440 };
}
break;
case XSystemDeviceType::XboxScarlettAnaconda /* Xbox Series X */:
case XSystemDeviceType::XboxOneXDevkit:
case XSystemDeviceType::XboxScarlettDevkit:
default:
m_outputSize = { 0, 0, 3840, 2160 };
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 4k (3840 x 2160)\n");
#endif
m_outputSize = (m_options & c_Enable4K_UHD) ? RECT{ 0, 0, 3840, 2160 } : RECT{ 0, 0, 2560, 1440 };
break;
}
}
#ifdef _DEBUG
const char* info = nullptr;
switch (m_outputSize.bottom)
{
case 2160: info = "INFO: Swapchain using 4k (3840 x 2160)\n"; break;
case 1440: info = "INFO: Swapchain using 1440p (2560 x 1440)\n"; break;
default: info = "INFO: Swapchain using 1080p (1920 x 1080)\n"; break;
}
OutputDebugStringA(info);
#endif
RegisterFrameEvents();
}
@ -185,7 +214,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
{
if (!m_window)
{
throw std::exception("Call SetWindow with a valid window handle");
throw std::logic_error("Call SetWindow with a valid Win32 window handle");
}
// Wait until all previous GPU work is complete.
@ -198,7 +227,6 @@ void DeviceResources::CreateWindowSizeDependentResources()
for (UINT n = 0; n < m_backBufferCount; n++)
{
m_renderTargets[n].Reset();
m_renderTargetsGameDVR[n].Reset();
m_fenceValues[n] = m_fenceValues[m_backBufferIndex];
}
@ -208,7 +236,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
// Obtain the back buffers for this window which will be the final render targets
// and create render target views for each of them.
CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC swapChainBufferDesc = CD3DX12_RESOURCE_DESC::Tex2D(
m_backBufferFormat,
@ -219,6 +247,13 @@ void DeviceResources::CreateWindowSizeDependentResources()
);
swapChainBufferDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
#ifdef _GAMING_XBOX_XBOXONE
if (m_options & c_EnableHDR)
{
swapChainBufferDesc.Flags |= D3D12XBOX_RESOURCE_FLAG_ALLOW_AUTOMATIC_GAMEDVR_TONE_MAP;
}
#endif
D3D12_CLEAR_VALUE swapChainOptimizedClearValue = {};
swapChainOptimizedClearValue.Format = m_backBufferFormat;
@ -240,41 +275,12 @@ void DeviceResources::CreateWindowSizeDependentResources()
rtvDesc.Format = m_backBufferFormat;
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
const CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(n), m_rtvDescriptorSize);
m_d3dDevice->CreateRenderTargetView(m_renderTargets[n].Get(), &rtvDesc, rtvDescriptor);
}
if (m_options & c_EnableHDR)
{
swapChainBufferDesc.Format = swapChainOptimizedClearValue.Format = m_gameDVRFormat;
for (UINT n = 0; n < m_backBufferCount; n++)
{
ThrowIfFailed(m_d3dDevice->CreateCommittedResource(
&swapChainHeapProperties,
D3D12_HEAP_FLAG_ALLOW_DISPLAY,
&swapChainBufferDesc,
D3D12_RESOURCE_STATE_PRESENT,
&swapChainOptimizedClearValue,
IID_GRAPHICS_PPV_ARGS(m_renderTargetsGameDVR[n].GetAddressOf())));
wchar_t name[25] = {};
swprintf_s(name, L"GameDVR Render target %u", n);
m_renderTargetsGameDVR[n]->SetName(name);
D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
rtvDesc.Format = m_gameDVRFormat;
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptorGameDVR(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(m_backBufferCount + n), m_rtvDescriptorSize);
m_d3dDevice->CreateRenderTargetView(m_renderTargetsGameDVR[n].Get(), &rtvDesc, rtvDescriptorGameDVR);
}
}
// Reset the index to the current back buffer.
m_backBufferIndex = 0;
@ -282,7 +288,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
{
// Allocate a 2-D surface as the depth/stencil buffer and create a depth/stencil view
// on this surface.
CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC depthStencilDesc = CD3DX12_RESOURCE_DESC::Tex2D(
m_depthBufferFormat,
@ -295,7 +301,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = m_depthBufferFormat;
depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
depthOptimizedClearValue.DepthStencil.Depth = (m_options & c_ReverseDepth) ? 0.0f : 1.0f;
depthOptimizedClearValue.DepthStencil.Stencil = 0;
ThrowIfFailed(m_d3dDevice->CreateCommittedResource(
@ -331,10 +337,6 @@ void DeviceResources::CreateWindowSizeDependentResources()
// Prepare the command list and render target for rendering.
void DeviceResources::Prepare(D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState)
{
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, nullptr, D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE, &m_framePipelineToken));
// Reset command list and allocator.
ThrowIfFailed(m_commandAllocators[m_backBufferIndex]->Reset());
ThrowIfFailed(m_commandList->Reset(m_commandAllocators[m_backBufferIndex].Get(), nullptr));
@ -342,23 +344,10 @@ void DeviceResources::Prepare(D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_
if (beforeState != afterState)
{
// Transition the render target into the correct state to allow for drawing into it.
if (m_options & c_EnableHDR)
{
D3D12_RESOURCE_BARRIER barriers[2] =
{
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState),
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargetsGameDVR[m_backBufferIndex].Get(),
beforeState, afterState),
};
m_commandList->ResourceBarrier(_countof(barriers), barriers);
}
else
{
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState);
m_commandList->ResourceBarrier(1, &barrier);
}
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState);
m_commandList->ResourceBarrier(1, &barrier);
}
}
@ -368,20 +357,10 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState, _In_opt_ const
if (beforeState != D3D12_RESOURCE_STATE_PRESENT)
{
// Transition the render target to the state that allows it to be presented to the display.
if (m_options & c_EnableHDR)
{
D3D12_RESOURCE_BARRIER barriers[2] =
{
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT),
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargetsGameDVR[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT),
};
m_commandList->ResourceBarrier(_countof(barriers), barriers);
}
else
{
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &barrier);
}
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &barrier);
}
// Send the command list off to the GPU for processing.
@ -389,32 +368,24 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState, _In_opt_ const
m_commandQueue->ExecuteCommandLists(1, CommandListCast(m_commandList.GetAddressOf()));
// Present the backbuffer using the PresentX API.
D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParameters[2] = {};
planeParameters[0].Token = planeParameters[1].Token = m_framePipelineToken;
planeParameters[0].ResourceCount = planeParameters[1].ResourceCount = 1;
planeParameters[0].ppResources = m_renderTargets[m_backBufferIndex].GetAddressOf();
D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParameters = {};
planeParameters.Token = m_framePipelineToken;
planeParameters.ResourceCount = 1;
planeParameters.ppResources = m_renderTargets[m_backBufferIndex].GetAddressOf();
if (m_options & c_EnableHDR)
{
planeParameters[0].pSrcViewRects = planeParameters[1].pSrcViewRects = &m_outputSize;
planeParameters[0].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
planeParameters[1].ppResources = m_renderTargetsGameDVR[m_backBufferIndex].GetAddressOf();
planeParameters[1].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
ThrowIfFailed(
m_commandQueue->PresentX(2, planeParameters, params)
);
}
else
{
ThrowIfFailed(
m_commandQueue->PresentX(1, planeParameters, params)
);
planeParameters.ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
}
// Xbox One apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
ThrowIfFailed(
m_commandQueue->PresentX(1, &planeParameters, params)
);
MoveToNextFrame();
// Xbox apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
// Update the back buffer index.
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
}
// Handle GPU suspend/resume
@ -436,13 +407,13 @@ void DeviceResources::WaitForGpu() noexcept
if (m_commandQueue && m_fence && m_fenceEvent.IsValid())
{
// Schedule a Signal command in the GPU queue.
UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
const UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
if (SUCCEEDED(m_commandQueue->Signal(m_fence.Get(), fenceValue)))
{
// Wait until the Signal has been processed.
if (SUCCEEDED(m_fence->SetEventOnCompletion(fenceValue, m_fenceEvent.Get())))
{
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
std::ignore = WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
// Increment the fence value for the current frame.
m_fenceValues[m_backBufferIndex]++;
@ -451,25 +422,17 @@ void DeviceResources::WaitForGpu() noexcept
}
}
// Prepare to render the next frame.
void DeviceResources::MoveToNextFrame()
// For PresentX rendering, we should wait for the origin event just before processing input.
void DeviceResources::WaitForOrigin()
{
// Schedule a Signal command in the queue.
const UINT64 currentFenceValue = m_fenceValues[m_backBufferIndex];
ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), currentFenceValue));
// Update the back buffer index.
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
// If the next frame is not ready to be rendered yet, wait until it is ready.
if (m_fence->GetCompletedValue() < m_fenceValues[m_backBufferIndex])
{
ThrowIfFailed(m_fence->SetEventOnCompletion(m_fenceValues[m_backBufferIndex], m_fenceEvent.Get()));
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
}
// Set the fence value for the next frame.
m_fenceValues[m_backBufferIndex] = currentFenceValue + 1;
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(
D3D12XBOX_FRAME_EVENT_ORIGIN,
INFINITE,
nullptr,
D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE,
&m_framePipelineToken));
}
// Set frame interval and register for frame events

Просмотреть файл

@ -10,8 +10,11 @@ namespace DX
class DeviceResources
{
public:
static constexpr unsigned int c_Enable4K_UHD = 0x1;
static constexpr unsigned int c_EnableHDR = 0x2;
static constexpr unsigned int c_Enable4K_UHD = 0x1;
static constexpr unsigned int c_EnableQHD = 0x2;
static constexpr unsigned int c_EnableHDR = 0x4;
static constexpr unsigned int c_ReverseDepth = 0x8;
static constexpr unsigned int c_AmplificationShaders = 0x10;
DeviceResources(DXGI_FORMAT backBufferFormat = DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D32_FLOAT,
@ -25,7 +28,11 @@ namespace DX
DeviceResources(DeviceResources const&) = delete;
DeviceResources& operator= (DeviceResources const&) = delete;
#ifdef _GAMING_XBOX_SCARLETT
void CreateDeviceResources(D3D12XBOX_CREATE_DEVICE_FLAGS createDeviceFlags = D3D12XBOX_CREATE_DEVICE_FLAG_NONE);
#else
void CreateDeviceResources();
#endif
void CreateWindowSizeDependentResources();
void SetWindow(HWND window) noexcept { m_window = window; }
void Prepare(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_PRESENT,
@ -35,6 +42,7 @@ namespace DX
void Suspend();
void Resume();
void WaitForGpu() noexcept;
void WaitForOrigin();
// Device Accessors.
RECT GetOutputSize() const noexcept { return m_outputSize; }
@ -67,19 +75,7 @@ namespace DX
return CD3DX12_CPU_DESCRIPTOR_HANDLE(m_dsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
}
// Direct3D HDR Game DVR support for Xbox One.
ID3D12Resource* GetGameDVRRenderTarget() const noexcept { return m_renderTargetsGameDVR[m_backBufferIndex].Get(); }
DXGI_FORMAT GetGameDVRFormat() const noexcept { return m_gameDVRFormat; }
CD3DX12_CPU_DESCRIPTOR_HANDLE GetGameDVRRenderTargetView() const noexcept
{
return CD3DX12_CPU_DESCRIPTOR_HANDLE(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(m_backBufferCount + m_backBufferIndex), m_rtvDescriptorSize);
}
private:
void MoveToNextFrame();
void RegisterFrameEvents();
static constexpr size_t MAX_BACK_BUFFER_COUNT = 3;
@ -87,8 +83,13 @@ namespace DX
UINT m_backBufferIndex;
// Direct3D objects.
Microsoft::WRL::ComPtr<ID3D12Device> m_d3dDevice;
#ifdef _GAMING_XBOX_SCARLETT
Microsoft::WRL::ComPtr<ID3D12Device8> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList5> m_commandList;
#else
Microsoft::WRL::ComPtr<ID3D12Device2> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> m_commandList;
#endif
Microsoft::WRL::ComPtr<ID3D12CommandQueue> m_commandQueue;
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> m_commandAllocators[MAX_BACK_BUFFER_COUNT];
@ -121,9 +122,5 @@ namespace DX
// DeviceResources options (see flags above)
unsigned int m_options;
// Direct3D HDR Game DVR support for Xbox One.
Microsoft::WRL::ComPtr<ID3D12Resource> m_renderTargetsGameDVR[MAX_BACK_BUFFER_COUNT];
DXGI_FORMAT m_gameDVRFormat;
};
}

Просмотреть файл

@ -1,7 +1,7 @@
//--------------------------------------------------------------------------------------
// Main.cpp
//
// Entry point for Microsoft GDK with Xbox extensions.
// Entry point for Microsoft GDK with Xbox extensions
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
@ -18,16 +18,25 @@
using namespace DirectX;
#ifdef __clang__
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wswitch-enum"
#endif
#pragma warning(disable : 4061)
namespace
{
std::unique_ptr<Sample> g_sample;
HANDLE g_plmSuspendComplete = nullptr;
HANDLE g_plmSignalResume = nullptr;
};
}
bool g_HDRMode = false;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void SetDisplayMode() noexcept;
void ExitSample() noexcept;
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
@ -58,6 +67,8 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
// Register class and create window
PAPPSTATE_REGISTRATION hPLM = {};
PAPPCONSTRAIN_REGISTRATION hPLM2 = {};
{
// Register class
WNDCLASSEXA wcex = {};
@ -66,7 +77,7 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = u8"PointSpritesWindowClass";
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
if (!RegisterClassExA(&wcex))
return 1;
@ -79,17 +90,7 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
ShowWindow(hwnd, nCmdShow);
if (g_sample->RequestHDRMode())
{
// Request HDR mode.
auto result = XDisplayTryEnableHdrMode(XDisplayHdrModePreference::PreferHdr, nullptr);
g_HDRMode = (result == XDisplayHdrModeResult::Enabled);
#ifdef _DEBUG
OutputDebugStringA((g_HDRMode) ? "INFO: Display in HDR Mode\n" : "INFO: Display in SDR Mode\n");
#endif
}
SetDisplayMode();
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_sample.get()));
@ -116,7 +117,7 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
PostMessage(reinterpret_cast<HWND>(context), WM_USER, 0, 0);
// To defer suspend, you must wait to exit this callback
(void)WaitForSingleObject(g_plmSuspendComplete, INFINITE);
std::ignore = WaitForSingleObject(g_plmSuspendComplete, INFINITE);
}
else
{
@ -124,6 +125,13 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
}
}, hwnd, &hPLM))
return 1;
if (RegisterAppConstrainedChangeNotification([](BOOLEAN constrained, PVOID context)
{
// To ensure we use the main UI thread to process the notification, we self-post a message
SendMessage(reinterpret_cast<HWND>(context), WM_USER + 1, (constrained) ? 1u : 0u, 0);
}, hwnd, &hPLM2))
return 1;
}
// Main message loop
@ -144,13 +152,14 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
g_sample.reset();
UnregisterAppStateChangeNotification(hPLM);
UnregisterAppConstrainedChangeNotification(hPLM2);
CloseHandle(g_plmSuspendComplete);
CloseHandle(g_plmSignalResume);
XGameRuntimeUninitialize();
return (int)msg.wParam;
return static_cast<int>(msg.wParam);
}
// Windows procedure
@ -168,18 +177,52 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
// Complete deferral
SetEvent(g_plmSuspendComplete);
(void)WaitForSingleObject(g_plmSignalResume, INFINITE);
std::ignore = WaitForSingleObject(g_plmSignalResume, INFINITE);
SetDisplayMode();
sample->OnResuming();
}
break;
case WM_USER + 1:
if (sample)
{
if (wParam)
{
sample->OnConstrained();
}
else
{
SetDisplayMode();
sample->OnUnConstrained();
}
}
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// HDR helper
void SetDisplayMode() noexcept
{
if (g_sample && g_sample->RequestHDRMode())
{
// Request HDR mode.
auto result = XDisplayTryEnableHdrMode(XDisplayHdrModePreference::PreferHdr, nullptr);
g_HDRMode = (result == XDisplayHdrModeResult::Enabled);
#ifdef _DEBUG
OutputDebugStringA((g_HDRMode) ? "INFO: Display in HDR Mode\n" : "INFO: Display in SDR Mode\n");
#endif
}
}
// Exit helper
void ExitSample()
void ExitSample() noexcept
{
PostQuitMessage(0);
}

Двоичные данные
Samples/Graphics/AdvancedESRAM/ReadMe.docx

Двоичный файл не отображается.

Просмотреть файл

@ -111,7 +111,7 @@ namespace DX
timeDelta *= TicksPerSecond;
timeDelta /= static_cast<uint64_t>(m_qpcFrequency.QuadPart);
uint32_t lastFrameCount = m_frameCount;
const uint32_t lastFrameCount = m_frameCount;
if (m_isFixedTimeStep)
{

Просмотреть файл

@ -37,8 +37,8 @@
#include <gxdk.h>
#if _GXDK_VER < 0x4A610D2B /* GXDK Edition 200600 */
#error This sample requires the June 2020 GDK or later
#if _GXDK_VER < 0x55F007B0 /* GDK Edition 211000 */
#error This sample requires the October 2021 GDK or later
#endif
#ifdef _GAMING_XBOX_SCARLETT
@ -59,25 +59,30 @@
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <exception>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <vector>
#include <string>
#include <system_error>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <assert.h>
#include <stdio.h>
#include <pix3.h>
#include <XGame.h>
#include <XSystem.h>
#include <XTaskQueue.h>
#include "ATGColors.h"
#include "CommonStates.h"
#include "ControllerFont.h"
#include "DescriptorHeap.h"
#include "DirectXHelpers.h"
#include "Effects.h"
@ -85,9 +90,7 @@
#include "GeometricPrimitive.h"
#include "GraphicsMemory.h"
#include "Model.h"
#include "PerformanceTimersXbox.h"
#include "PostProcess.h"
#include "ReadData.h"
#include "RenderTargetState.h"
#include "ResourceUploadBatch.h"
#include "SimpleMath.h"
@ -95,6 +98,11 @@
#include "SpriteFont.h"
#include "VertexTypes.h"
#include "ATGColors.h"
#include "ControllerFont.h"
#include "PerformanceTimersXbox.h"
#include "ReadData.h"
#include "SharedDefinitions.h"
namespace DX
@ -103,7 +111,7 @@ namespace DX
class com_exception : public std::exception
{
public:
com_exception(HRESULT hr) : result(hr) {}
com_exception(HRESULT hr) noexcept : result(hr) {}
const char* what() const override
{
@ -121,6 +129,12 @@ namespace DX
{
if (FAILED(hr))
{
#ifdef _DEBUG
char str[64] = {};
sprintf_s(str, "**ERROR** Fatal Error with HRESULT of %08X\n", static_cast<unsigned int>(hr));
OutputDebugStringA(str);
__debugbreak();
#endif
throw com_exception(hr);
}
}

Просмотреть файл

@ -137,6 +137,8 @@ void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %I64u", m_frame);
m_deviceResources->WaitForOrigin();
m_timer.Tick([&]()
{
Update(m_timer);
@ -226,8 +228,8 @@ void Sample::Update(DX::StepTimer const&)
}
// Limit to avoid looking directly up or down
const float limit = XM_PI / 2.0f - 0.01f;
m_pitch = std::max(-limit, std::min(+limit, m_pitch));
constexpr float c_limit = XM_PI / 2.0f - 0.01f;
m_pitch = std::max(-c_limit, std::min(+c_limit, m_pitch));
if (m_yaw > XM_PI)
{
@ -386,7 +388,7 @@ void Sample::Render()
{
case AntialiasMethods::SMAA2X:
{
auto size = m_deviceResources->GetOutputSize();
auto const size = m_deviceResources->GetOutputSize();
SMAAConstantBuffer cb = { { 1.f, 1.f, 1.f, 0.f }, 1.f / float(size.right), 1.f / float(size.bottom) };
auto cbHandle = m_graphicsMemory->AllocateConstant(cb);
RenderSMAA(commandList, Descriptors::SceneTex, Descriptors::DepthTex, 1.f, cbHandle.GpuAddress());
@ -406,7 +408,7 @@ void Sample::Render()
commandList->ResourceBarrier(1, &barrier);
}
auto size = m_deviceResources->GetOutputSize();
auto const size = m_deviceResources->GetOutputSize();
SMAAConstantBuffer cb = { { 0.f, 0.f, 0.f, 0.f }, 1.f / float(size.right), 1.f / float(size.bottom) };
auto cbHandle = m_graphicsMemory->AllocateConstant(cb);
RenderSMAA(commandList, Descriptors::SceneTex, m_hardwareAA ? Descriptors::DepthTex : Descriptors::DepthStencilSRV, 1.f, cbHandle.GpuAddress());
@ -425,13 +427,13 @@ void Sample::Render()
{
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Render FXAA");
auto rtvDescriptor = m_renderDescriptors->GetCpuHandle(RTDescriptors::FinalRTV);
auto const rtvDescriptor = m_renderDescriptors->GetCpuHandle(RTDescriptors::FinalRTV);
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, nullptr);
m_scene->TransitionTo(commandList, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
m_final->BeginScene(commandList);
auto size = m_deviceResources->GetOutputSize();
auto const size = m_deviceResources->GetOutputSize();
FXAAConstantBuffer cb = { 1.f / float(size.right), 1.f / float(size.bottom) };
auto cbHandle = m_graphicsMemory->AllocateConstant(cb);
@ -451,7 +453,7 @@ void Sample::Render()
}
// Render final scene
auto rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto const rtvDescriptor = m_deviceResources->GetRenderTargetView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, nullptr);
@ -517,10 +519,10 @@ void Sample::RenderZoom(ID3D12GraphicsCommandList* commandList)
m_fullScreenQuad->Draw(commandList, m_zoomPSO.Get(), m_resourceDescriptors->GetGpuHandle(Descriptors::FinalTex));
auto vp = m_deviceResources->GetScreenViewport();
auto const vp = m_deviceResources->GetScreenViewport();
commandList->RSSetViewports(1, &vp);
auto scissors = m_deviceResources->GetScissorRect();
auto const scissors = m_deviceResources->GetScissorRect();
commandList->RSSetScissorRects(1, &scissors);
m_lineEFfect->Apply(commandList);
@ -554,8 +556,8 @@ void Sample::RenderUI(ID3D12GraphicsCommandList* commandList)
};
commandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
auto size = m_deviceResources->GetOutputSize();
auto safe = SimpleMath::Viewport::ComputeTitleSafeArea(UINT(size.right), UINT(size.bottom));
auto const size = m_deviceResources->GetOutputSize();
auto const safe = SimpleMath::Viewport::ComputeTitleSafeArea(UINT(size.right), UINT(size.bottom));
m_batch->Begin(commandList);
@ -683,7 +685,7 @@ void Sample::RenderSMAA(ID3D12GraphicsCommandList* commandList, size_t renderTar
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, nullptr);
float factor[4] = { blendFactor, blendFactor, blendFactor, blendFactor };
const float factor[4] = { blendFactor, blendFactor, blendFactor, blendFactor };
commandList->OMSetBlendFactor(factor);
m_fullScreenQuad->Draw(commandList, m_neighborBlendPSO.Get(), colorHandle,
@ -730,8 +732,8 @@ void Sample::Clear()
commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
auto const viewport = m_deviceResources->GetScreenViewport();
auto const scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
@ -789,7 +791,7 @@ void Sample::CreateDeviceDependentResources()
m_model->LoadStaticBuffers(device, upload);
RenderTargetState rtStateUI(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
const RenderTargetState rtStateUI(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
{
SpriteBatchPipelineStateDescription pd(rtStateUI, &CommonStates::AlphaBlend);
@ -1111,7 +1113,7 @@ void Sample::CreateWindowSizeDependentResources()
{
m_batch->SetViewport(m_deviceResources->GetScreenViewport());
auto size = m_deviceResources->GetOutputSize();
auto const size = m_deviceResources->GetOutputSize();
auto device = m_deviceResources->GetD3DDevice();
ResourceUploadBatch resourceUpload(device);

Просмотреть файл

@ -37,6 +37,11 @@ public:
// Messages
void OnSuspending();
void OnResuming();
void OnConstrained() {}
void OnUnConstrained() {}
// Properties
bool RequestHDRMode() const noexcept { return m_deviceResources ? (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_EnableHDR) != 0 : false; }
private:

Просмотреть файл

@ -33,7 +33,7 @@ namespace
default: return fmt;
}
}
};
}
// Constructor for DeviceResources.
DeviceResources::DeviceResources(
@ -70,12 +70,16 @@ DeviceResources::~DeviceResources()
// Ensure we present a blank screen before cleaning up resources.
if (m_commandQueue)
{
(void)m_commandQueue->PresentX(0, nullptr, nullptr);
std::ignore = m_commandQueue->PresentX(0, nullptr, nullptr);
}
}
// Configures the Direct3D device, and stores handles to it and the device context.
#ifdef _GAMING_XBOX_SCARLETT
void DeviceResources::CreateDeviceResources(D3D12XBOX_CREATE_DEVICE_FLAGS createDeviceFlags)
#else
void DeviceResources::CreateDeviceResources()
#endif
{
// Create the DX12 API device object.
D3D12XBOX_CREATE_DEVICE_PARAMETERS params = {};
@ -92,6 +96,17 @@ void DeviceResources::CreateDeviceResources()
params.GraphicsCommandQueueRingSizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.GraphicsScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.ComputeScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
#ifdef _GAMING_XBOX_SCARLETT
params.CreateDeviceFlags = createDeviceFlags;
#if (_GXDK_VER >= 0x585D070E /* GXDK Edition 221000 */)
if (m_options & c_AmplificationShaders)
{
params.AmplificationShaderIndirectArgsBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.AmplificationShaderPayloadBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
}
#endif
#endif
HRESULT hr = D3D12XboxCreateDevice(
nullptr,
@ -167,31 +182,46 @@ void DeviceResources::CreateDeviceResources()
m_fenceEvent.Attach(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
if (!m_fenceEvent.IsValid())
{
throw std::exception("CreateEvent");
throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEventEx");
}
if (m_options & c_Enable4K_UHD)
if (m_options & (c_Enable4K_UHD | c_EnableQHD))
{
switch (XSystemGetDeviceType())
{
case XSystemDeviceType::XboxOne:
case XSystemDeviceType::XboxOneS:
case XSystemDeviceType::XboxScarlettLockhart /* Xbox Series S */:
m_options &= ~c_Enable4K_UHD;
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 1080p (1920 x 1080)\n");
#endif
m_options &= ~(c_Enable4K_UHD | c_EnableQHD);
break;
case XSystemDeviceType::XboxScarlettLockhart /* Xbox Series S */:
m_options &= ~c_Enable4K_UHD;
if (m_options & c_EnableQHD)
{
m_outputSize = { 0, 0, 2560, 1440 };
}
break;
case XSystemDeviceType::XboxScarlettAnaconda /* Xbox Series X */:
case XSystemDeviceType::XboxOneXDevkit:
case XSystemDeviceType::XboxScarlettDevkit:
default:
m_outputSize = { 0, 0, 3840, 2160 };
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 4k (3840 x 2160)\n");
#endif
m_outputSize = (m_options & c_Enable4K_UHD) ? RECT{ 0, 0, 3840, 2160 } : RECT{ 0, 0, 2560, 1440 };
break;
}
}
#ifdef _DEBUG
const char* info = nullptr;
switch (m_outputSize.bottom)
{
case 2160: info = "INFO: Swapchain using 4k (3840 x 2160)\n"; break;
case 1440: info = "INFO: Swapchain using 1440p (2560 x 1440)\n"; break;
default: info = "INFO: Swapchain using 1080p (1920 x 1080)\n"; break;
}
OutputDebugStringA(info);
#endif
RegisterFrameEvents();
}
@ -200,7 +230,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
{
if (!m_window)
{
throw std::exception("Call SetWindow with a valid window handle");
throw std::logic_error("Call SetWindow with a valid Win32 window handle");
}
// Wait until all previous GPU work is complete.
@ -222,7 +252,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
// Obtain the back buffers for this window which will be the final render targets
// and create render target views for each of them.
CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC swapChainBufferDesc = CD3DX12_RESOURCE_DESC::Tex2D(
m_backBufferFormat,
@ -233,6 +263,13 @@ void DeviceResources::CreateWindowSizeDependentResources()
);
swapChainBufferDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
#ifdef _GAMING_XBOX_XBOXONE
if (m_options & c_EnableHDR)
{
swapChainBufferDesc.Flags |= D3D12XBOX_RESOURCE_FLAG_ALLOW_AUTOMATIC_GAMEDVR_TONE_MAP;
}
#endif
D3D12_CLEAR_VALUE swapChainOptimizedClearValue = {};
swapChainOptimizedClearValue.Format = m_backBufferFormat;
@ -254,7 +291,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
rtvDesc.Format = m_backBufferFormat;
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
const CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(n), m_rtvDescriptorSize);
m_d3dDevice->CreateRenderTargetView(m_renderTargets[n].Get(), &rtvDesc, rtvDescriptor);
@ -267,7 +304,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
{
// Allocate a 2-D surface as the depth/stencil buffer and create a depth/stencil view
// on this surface.
CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC depthStencilDesc = CD3DX12_RESOURCE_DESC::Tex2D(
MakeDepthTypeless(m_depthBufferFormat),
@ -280,7 +317,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = m_depthBufferFormat;
depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
depthOptimizedClearValue.DepthStencil.Depth = (m_options & c_ReverseDepth) ? 0.0f : 1.0f;
depthOptimizedClearValue.DepthStencil.Stencil = 0;
ThrowIfFailed(m_d3dDevice->CreateCommittedResource(
@ -316,29 +353,29 @@ void DeviceResources::CreateWindowSizeDependentResources()
// Prepare the command list and render target for rendering.
void DeviceResources::Prepare(D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState)
{
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, nullptr, D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE, &m_framePipelineToken));
// Reset command list and allocator.
ThrowIfFailed(m_commandAllocators[m_backBufferIndex]->Reset());
ThrowIfFailed(m_commandList->Reset(m_commandAllocators[m_backBufferIndex].Get(), nullptr));
if (beforeState != afterState)
{
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(),
// Transition the render target into the correct state to allow for drawing into it.
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState);
m_commandList->ResourceBarrier(1, &barrier);
}
}
// Present the contents of the swap chain to the screen.
void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState)
void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState, _In_opt_ const D3D12XBOX_PRESENT_PARAMETERS* params)
{
if (beforeState != D3D12_RESOURCE_STATE_PRESENT)
{
// Transition the render target to the state that allows it to be presented to the display.
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT);
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &barrier);
}
@ -347,18 +384,24 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState)
m_commandQueue->ExecuteCommandLists(1, CommandListCast(m_commandList.GetAddressOf()));
// Present the backbuffer using the PresentX API.
D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParameters[2] = {};
planeParameters[0].Token = planeParameters[1].Token = m_framePipelineToken;
planeParameters[0].ResourceCount = planeParameters[1].ResourceCount = 1;
planeParameters[0].ppResources = m_renderTargets[m_backBufferIndex].GetAddressOf();
D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParameters = {};
planeParameters.Token = m_framePipelineToken;
planeParameters.ResourceCount = 1;
planeParameters.ppResources = m_renderTargets[m_backBufferIndex].GetAddressOf();
if (m_options & c_EnableHDR)
{
planeParameters.ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
}
ThrowIfFailed(
m_commandQueue->PresentX(1, planeParameters, nullptr)
m_commandQueue->PresentX(1, &planeParameters, params)
);
// Xbox One apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
// Xbox apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
MoveToNextFrame();
// Update the back buffer index.
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
}
// Handle GPU suspend/resume
@ -380,13 +423,13 @@ void DeviceResources::WaitForGpu() noexcept
if (m_commandQueue && m_fence && m_fenceEvent.IsValid())
{
// Schedule a Signal command in the GPU queue.
UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
const UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
if (SUCCEEDED(m_commandQueue->Signal(m_fence.Get(), fenceValue)))
{
// Wait until the Signal has been processed.
if (SUCCEEDED(m_fence->SetEventOnCompletion(fenceValue, m_fenceEvent.Get())))
{
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
std::ignore = WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
// Increment the fence value for the current frame.
m_fenceValues[m_backBufferIndex]++;
@ -395,25 +438,17 @@ void DeviceResources::WaitForGpu() noexcept
}
}
// Prepare to render the next frame.
void DeviceResources::MoveToNextFrame()
// For PresentX rendering, we should wait for the origin event just before processing input.
void DeviceResources::WaitForOrigin()
{
// Schedule a Signal command in the queue.
const UINT64 currentFenceValue = m_fenceValues[m_backBufferIndex];
ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), currentFenceValue));
// Update the back buffer index.
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
// If the next frame is not ready to be rendered yet, wait until it is ready.
if (m_fence->GetCompletedValue() < m_fenceValues[m_backBufferIndex])
{
ThrowIfFailed(m_fence->SetEventOnCompletion(m_fenceValues[m_backBufferIndex], m_fenceEvent.Get()));
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
}
// Set the fence value for the next frame.
m_fenceValues[m_backBufferIndex] = currentFenceValue + 1;
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(
D3D12XBOX_FRAME_EVENT_ORIGIN,
INFINITE,
nullptr,
D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE,
&m_framePipelineToken));
}
// Set frame interval and register for frame events

Просмотреть файл

@ -1,6 +1,8 @@
//
// DeviceResources.h - A wrapper for the Direct3D 12.X device and swapchain
//
// Modified to use a typeless format for depth
//
#pragma once
@ -10,7 +12,11 @@ namespace DX
class DeviceResources
{
public:
static constexpr unsigned int c_Enable4K_UHD = 0x1;
static constexpr unsigned int c_Enable4K_UHD = 0x1;
static constexpr unsigned int c_EnableQHD = 0x2;
static constexpr unsigned int c_EnableHDR = 0x4;
static constexpr unsigned int c_ReverseDepth = 0x8;
static constexpr unsigned int c_AmplificationShaders = 0x10;
DeviceResources(DXGI_FORMAT backBufferFormat = DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D32_FLOAT,
@ -24,15 +30,21 @@ namespace DX
DeviceResources(DeviceResources const&) = delete;
DeviceResources& operator= (DeviceResources const&) = delete;
#ifdef _GAMING_XBOX_SCARLETT
void CreateDeviceResources(D3D12XBOX_CREATE_DEVICE_FLAGS createDeviceFlags = D3D12XBOX_CREATE_DEVICE_FLAG_NONE);
#else
void CreateDeviceResources();
#endif
void CreateWindowSizeDependentResources();
void SetWindow(HWND window) noexcept { m_window = window; }
void Prepare(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_PRESENT,
D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET);
void Present(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET);
void Present(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET,
_In_opt_ const D3D12XBOX_PRESENT_PARAMETERS* params = nullptr);
void Suspend();
void Resume();
void WaitForGpu() noexcept;
void WaitForOrigin();
// Device Accessors.
RECT GetOutputSize() const noexcept { return m_outputSize; }
@ -66,7 +78,6 @@ namespace DX
}
private:
void MoveToNextFrame();
void RegisterFrameEvents();
static constexpr size_t MAX_BACK_BUFFER_COUNT = 3;

Просмотреть файл

@ -18,16 +18,25 @@
using namespace DirectX;
#ifdef __clang__
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wswitch-enum"
#endif
#pragma warning(disable : 4061)
namespace
{
std::unique_ptr<Sample> g_sample;
HANDLE g_plmSuspendComplete = nullptr;
HANDLE g_plmSignalResume = nullptr;
};
}
bool g_HDRMode = false;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void SetDisplayMode() noexcept;
void ExitSample() noexcept;
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
@ -58,6 +67,8 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
// Register class and create window
PAPPSTATE_REGISTRATION hPLM = {};
PAPPCONSTRAIN_REGISTRATION hPLM2 = {};
{
// Register class
WNDCLASSEXA wcex = {};
@ -79,6 +90,8 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
ShowWindow(hwnd, nCmdShow);
SetDisplayMode();
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_sample.get()));
// Sample Usage Telemetry
@ -104,7 +117,7 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
PostMessage(reinterpret_cast<HWND>(context), WM_USER, 0, 0);
// To defer suspend, you must wait to exit this callback
(void)WaitForSingleObject(g_plmSuspendComplete, INFINITE);
std::ignore = WaitForSingleObject(g_plmSuspendComplete, INFINITE);
}
else
{
@ -112,6 +125,13 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
}
}, hwnd, &hPLM))
return 1;
if (RegisterAppConstrainedChangeNotification([](BOOLEAN constrained, PVOID context)
{
// To ensure we use the main UI thread to process the notification, we self-post a message
SendMessage(reinterpret_cast<HWND>(context), WM_USER + 1, (constrained) ? 1u : 0u, 0);
}, hwnd, &hPLM2))
return 1;
}
// Main message loop
@ -132,7 +152,8 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
g_sample.reset();
UnregisterAppStateChangeNotification(hPLM);
UnregisterAppConstrainedChangeNotification(hPLM2);
CloseHandle(g_plmSuspendComplete);
CloseHandle(g_plmSignalResume);
@ -156,16 +177,50 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
// Complete deferral
SetEvent(g_plmSuspendComplete);
(void)WaitForSingleObject(g_plmSignalResume, INFINITE);
std::ignore = WaitForSingleObject(g_plmSignalResume, INFINITE);
SetDisplayMode();
sample->OnResuming();
}
break;
case WM_USER + 1:
if (sample)
{
if (wParam)
{
sample->OnConstrained();
}
else
{
SetDisplayMode();
sample->OnUnConstrained();
}
}
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// HDR helper
void SetDisplayMode() noexcept
{
if (g_sample && g_sample->RequestHDRMode())
{
// Request HDR mode.
auto result = XDisplayTryEnableHdrMode(XDisplayHdrModePreference::PreferHdr, nullptr);
g_HDRMode = (result == XDisplayHdrModeResult::Enabled);
#ifdef _DEBUG
OutputDebugStringA((g_HDRMode) ? "INFO: Display in HDR Mode\n" : "INFO: Display in SDR Mode\n");
#endif
}
}
// Exit helper
void ExitSample() noexcept
{

Двоичные данные
Samples/Graphics/Antialiasing/Readme.docx

Двоичный файл не отображается.

Просмотреть файл

@ -111,7 +111,7 @@ namespace DX
timeDelta *= TicksPerSecond;
timeDelta /= static_cast<uint64_t>(m_qpcFrequency.QuadPart);
uint32_t lastFrameCount = m_frameCount;
const uint32_t lastFrameCount = m_frameCount;
if (m_isFixedTimeStep)
{

Просмотреть файл

@ -37,8 +37,8 @@
#include <gxdk.h>
#if _GXDK_VER < 0x4A610D2B /* GXDK Edition 200600 */
#error This sample requires the June 2020 GDK or later
#if _GXDK_VER < 0x55F007B0 /* GDK Edition 211000 */
#error This sample requires the October 2021 GDK or later
#endif
#ifdef _GAMING_XBOX_SCARLETT
@ -56,15 +56,23 @@
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <exception>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <string>
#include <system_error>
#include <tuple>
#include <assert.h>
#include <stdio.h>
#include <pix3.h>
#include <XGame.h>
#include <XSystem.h>

Просмотреть файл

@ -10,7 +10,7 @@
#include "ATGColors.h"
extern void ExitSample();
extern void ExitSample() noexcept;
using namespace DirectX;
using namespace DirectX::SimpleMath;
@ -63,7 +63,7 @@ void Sample::Initialize(HWND window)
m_deviceResources->SetWindow(window);
m_deviceResources->CreateDeviceResources();
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
@ -76,6 +76,8 @@ void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %llu", m_frame);
m_deviceResources->WaitForOrigin();
m_timer.Tick([&]()
{
Update(m_timer);
@ -250,16 +252,16 @@ void Sample::Clear()
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto dsvDescriptor = m_deviceResources->GetDepthStencilView();
auto const rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto const dsvDescriptor = m_deviceResources->GetDepthStencilView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, &dsvDescriptor);
commandList->ClearRenderTargetView(rtvDescriptor, ATG::Colors::Background, 0, nullptr);
commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
auto const viewport = m_deviceResources->GetScreenViewport();
auto const scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
@ -292,8 +294,6 @@ void Sample::CreateDeviceDependentResources()
m_commonStates = std::make_unique<DirectX::CommonStates>(device);
m_srvPile = std::make_unique<DescriptorPile>(device,
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
128,
SRV_Count);
@ -329,8 +329,8 @@ void Sample::CreateDeviceDependentResources()
m_particles.GenerateGeometry(*m_models[0]);
// HUD
auto backBufferRts = RenderTargetState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
auto spritePSD = SpriteBatchPipelineStateDescription(backBufferRts, &CommonStates::AlphaBlend);
const RenderTargetState backBufferRts(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
const SpriteBatchPipelineStateDescription spritePSD(backBufferRts, &CommonStates::AlphaBlend);
m_hudBatch = std::make_unique<SpriteBatch>(device, resourceUpload, spritePSD);
auto finished = resourceUpload.End(m_deviceResources->GetCommandQueue());
@ -339,7 +339,7 @@ void Sample::CreateDeviceDependentResources()
// Instantiate objects from basic scene definition.
auto effectFactory = EffectFactory(m_srvPile->Heap(), m_commonStates->Heap());
auto objectRTState = RenderTargetState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
const RenderTargetState objectRTState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
auto objectPSD = EffectPipelineStateDescription(
nullptr,
CommonStates::Opaque,

Просмотреть файл

@ -21,6 +21,12 @@ public:
Sample() noexcept(false);
~Sample();
Sample(Sample&&) = default;
Sample& operator= (Sample&&) = default;
Sample(Sample const&) = delete;
Sample& operator= (Sample const&) = delete;
// Initialization and management
void Initialize(HWND window);
@ -30,9 +36,11 @@ public:
// Messages
void OnSuspending();
void OnResuming();
void OnConstrained() {}
void OnUnConstrained() {}
// Properties
bool RequestHDRMode() const { return m_deviceResources ? (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_EnableHDR) != 0 : false; }
bool RequestHDRMode() const noexcept { return m_deviceResources ? (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_EnableHDR) != 0 : false; }
private:
void Update(DX::StepTimer const& timer);

Просмотреть файл

@ -31,14 +31,13 @@ DeviceResources::DeviceResources(
m_rtvDescriptorSize(0),
m_screenViewport{},
m_scissorRect{},
m_backBufferFormat((flags & c_EnableHDR) ? DXGI_FORMAT_R10G10B10A2_UNORM : backBufferFormat),
m_backBufferFormat(backBufferFormat),
m_depthBufferFormat(depthBufferFormat),
m_backBufferCount(backBufferCount),
m_window(nullptr),
m_d3dFeatureLevel(D3D_FEATURE_LEVEL_12_0),
m_outputSize{0, 0, 1920, 1080},
m_options(flags),
m_gameDVRFormat((flags & c_EnableHDR) ? backBufferFormat : DXGI_FORMAT_UNKNOWN)
m_options(flags)
{
if (backBufferCount < 2 || backBufferCount > MAX_BACK_BUFFER_COUNT)
{
@ -55,12 +54,16 @@ DeviceResources::~DeviceResources()
// Ensure we present a blank screen before cleaning up resources.
if (m_commandQueue)
{
(void)m_commandQueue->PresentX(0, nullptr, nullptr);
std::ignore = m_commandQueue->PresentX(0, nullptr, nullptr);
}
}
// Configures the Direct3D device, and stores handles to it and the device context.
#ifdef _GAMING_XBOX_SCARLETT
void DeviceResources::CreateDeviceResources(D3D12XBOX_CREATE_DEVICE_FLAGS createDeviceFlags)
#else
void DeviceResources::CreateDeviceResources()
#endif
{
// Create the DX12 API device object.
D3D12XBOX_CREATE_DEVICE_PARAMETERS params = {};
@ -77,6 +80,17 @@ void DeviceResources::CreateDeviceResources()
params.GraphicsCommandQueueRingSizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.GraphicsScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.ComputeScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
#ifdef _GAMING_XBOX_SCARLETT
params.CreateDeviceFlags = createDeviceFlags;
#if (_GXDK_VER >= 0x585D070E /* GXDK Edition 221000 */)
if (m_options & c_AmplificationShaders)
{
params.AmplificationShaderIndirectArgsBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.AmplificationShaderPayloadBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
}
#endif
#endif
HRESULT hr = D3D12XboxCreateDevice(
nullptr,
@ -107,7 +121,7 @@ void DeviceResources::CreateDeviceResources()
// Create descriptor heaps for render target views and depth stencil views.
D3D12_DESCRIPTOR_HEAP_DESC rtvDescriptorHeapDesc = {};
rtvDescriptorHeapDesc.NumDescriptors = (m_options & c_EnableHDR) ? (m_backBufferCount * 2) : m_backBufferCount;
rtvDescriptorHeapDesc.NumDescriptors = m_backBufferCount;
rtvDescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
ThrowIfFailed(m_d3dDevice->CreateDescriptorHeap(&rtvDescriptorHeapDesc, IID_GRAPHICS_PPV_ARGS(m_rtvDescriptorHeap.ReleaseAndGetAddressOf())));
@ -152,31 +166,46 @@ void DeviceResources::CreateDeviceResources()
m_fenceEvent.Attach(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
if (!m_fenceEvent.IsValid())
{
throw std::exception("CreateEvent");
throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEventEx");
}
if (m_options & c_Enable4K_UHD)
if (m_options & (c_Enable4K_UHD | c_EnableQHD))
{
switch (XSystemGetDeviceType())
{
case XSystemDeviceType::XboxOne:
case XSystemDeviceType::XboxOneS:
case XSystemDeviceType::XboxScarlettLockhart /* Xbox Series S */:
m_options &= ~c_Enable4K_UHD;
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 1080p (1920 x 1080)\n");
#endif
m_options &= ~(c_Enable4K_UHD | c_EnableQHD);
break;
case XSystemDeviceType::XboxScarlettLockhart /* Xbox Series S */:
m_options &= ~c_Enable4K_UHD;
if (m_options & c_EnableQHD)
{
m_outputSize = { 0, 0, 2560, 1440 };
}
break;
case XSystemDeviceType::XboxScarlettAnaconda /* Xbox Series X */:
case XSystemDeviceType::XboxOneXDevkit:
case XSystemDeviceType::XboxScarlettDevkit:
default:
m_outputSize = { 0, 0, 3840, 2160 };
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 4k (3840 x 2160)\n");
#endif
m_outputSize = (m_options & c_Enable4K_UHD) ? RECT{ 0, 0, 3840, 2160 } : RECT{ 0, 0, 2560, 1440 };
break;
}
}
#ifdef _DEBUG
const char* info = nullptr;
switch (m_outputSize.bottom)
{
case 2160: info = "INFO: Swapchain using 4k (3840 x 2160)\n"; break;
case 1440: info = "INFO: Swapchain using 1440p (2560 x 1440)\n"; break;
default: info = "INFO: Swapchain using 1080p (1920 x 1080)\n"; break;
}
OutputDebugStringA(info);
#endif
RegisterFrameEvents();
}
@ -185,7 +214,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
{
if (!m_window)
{
throw std::exception("Call SetWindow with a valid window handle");
throw std::logic_error("Call SetWindow with a valid Win32 window handle");
}
// Wait until all previous GPU work is complete.
@ -198,7 +227,6 @@ void DeviceResources::CreateWindowSizeDependentResources()
for (UINT n = 0; n < m_backBufferCount; n++)
{
m_renderTargets[n].Reset();
m_renderTargetsGameDVR[n].Reset();
m_fenceValues[n] = m_fenceValues[m_backBufferIndex];
}
@ -208,7 +236,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
// Obtain the back buffers for this window which will be the final render targets
// and create render target views for each of them.
CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC swapChainBufferDesc = CD3DX12_RESOURCE_DESC::Tex2D(
m_backBufferFormat,
@ -219,6 +247,13 @@ void DeviceResources::CreateWindowSizeDependentResources()
);
swapChainBufferDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
#ifdef _GAMING_XBOX_XBOXONE
if (m_options & c_EnableHDR)
{
swapChainBufferDesc.Flags |= D3D12XBOX_RESOURCE_FLAG_ALLOW_AUTOMATIC_GAMEDVR_TONE_MAP;
}
#endif
D3D12_CLEAR_VALUE swapChainOptimizedClearValue = {};
swapChainOptimizedClearValue.Format = m_backBufferFormat;
@ -240,41 +275,12 @@ void DeviceResources::CreateWindowSizeDependentResources()
rtvDesc.Format = m_backBufferFormat;
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
const CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(n), m_rtvDescriptorSize);
m_d3dDevice->CreateRenderTargetView(m_renderTargets[n].Get(), &rtvDesc, rtvDescriptor);
}
if (m_options & c_EnableHDR)
{
swapChainBufferDesc.Format = swapChainOptimizedClearValue.Format = m_gameDVRFormat;
for (UINT n = 0; n < m_backBufferCount; n++)
{
ThrowIfFailed(m_d3dDevice->CreateCommittedResource(
&swapChainHeapProperties,
D3D12_HEAP_FLAG_ALLOW_DISPLAY,
&swapChainBufferDesc,
D3D12_RESOURCE_STATE_PRESENT,
&swapChainOptimizedClearValue,
IID_GRAPHICS_PPV_ARGS(m_renderTargetsGameDVR[n].GetAddressOf())));
wchar_t name[25] = {};
swprintf_s(name, L"GameDVR Render target %u", n);
m_renderTargetsGameDVR[n]->SetName(name);
D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
rtvDesc.Format = m_gameDVRFormat;
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptorGameDVR(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(m_backBufferCount + n), m_rtvDescriptorSize);
m_d3dDevice->CreateRenderTargetView(m_renderTargetsGameDVR[n].Get(), &rtvDesc, rtvDescriptorGameDVR);
}
}
// Reset the index to the current back buffer.
m_backBufferIndex = 0;
@ -282,7 +288,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
{
// Allocate a 2-D surface as the depth/stencil buffer and create a depth/stencil view
// on this surface.
CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC depthStencilDesc = CD3DX12_RESOURCE_DESC::Tex2D(
m_depthBufferFormat,
@ -295,7 +301,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = m_depthBufferFormat;
depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
depthOptimizedClearValue.DepthStencil.Depth = (m_options & c_ReverseDepth) ? 0.0f : 1.0f;
depthOptimizedClearValue.DepthStencil.Stencil = 0;
ThrowIfFailed(m_d3dDevice->CreateCommittedResource(
@ -331,10 +337,6 @@ void DeviceResources::CreateWindowSizeDependentResources()
// Prepare the command list and render target for rendering.
void DeviceResources::Prepare(D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState)
{
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, nullptr, D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE, &m_framePipelineToken));
// Reset command list and allocator.
ThrowIfFailed(m_commandAllocators[m_backBufferIndex]->Reset());
ThrowIfFailed(m_commandList->Reset(m_commandAllocators[m_backBufferIndex].Get(), nullptr));
@ -342,23 +344,10 @@ void DeviceResources::Prepare(D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_
if (beforeState != afterState)
{
// Transition the render target into the correct state to allow for drawing into it.
if (m_options & c_EnableHDR)
{
D3D12_RESOURCE_BARRIER barriers[2] =
{
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState),
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargetsGameDVR[m_backBufferIndex].Get(),
beforeState, afterState),
};
m_commandList->ResourceBarrier(_countof(barriers), barriers);
}
else
{
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState);
m_commandList->ResourceBarrier(1, &barrier);
}
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState);
m_commandList->ResourceBarrier(1, &barrier);
}
}
@ -368,20 +357,10 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState, _In_opt_ const
if (beforeState != D3D12_RESOURCE_STATE_PRESENT)
{
// Transition the render target to the state that allows it to be presented to the display.
if (m_options & c_EnableHDR)
{
D3D12_RESOURCE_BARRIER barriers[2] =
{
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT),
CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargetsGameDVR[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT),
};
m_commandList->ResourceBarrier(_countof(barriers), barriers);
}
else
{
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &barrier);
}
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &barrier);
}
// Send the command list off to the GPU for processing.
@ -389,32 +368,24 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState, _In_opt_ const
m_commandQueue->ExecuteCommandLists(1, CommandListCast(m_commandList.GetAddressOf()));
// Present the backbuffer using the PresentX API.
D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParameters[2] = {};
planeParameters[0].Token = planeParameters[1].Token = m_framePipelineToken;
planeParameters[0].ResourceCount = planeParameters[1].ResourceCount = 1;
planeParameters[0].ppResources = m_renderTargets[m_backBufferIndex].GetAddressOf();
D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParameters = {};
planeParameters.Token = m_framePipelineToken;
planeParameters.ResourceCount = 1;
planeParameters.ppResources = m_renderTargets[m_backBufferIndex].GetAddressOf();
if (m_options & c_EnableHDR)
{
planeParameters[0].pSrcViewRects = planeParameters[1].pSrcViewRects = &m_outputSize;
planeParameters[0].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
planeParameters[1].ppResources = m_renderTargetsGameDVR[m_backBufferIndex].GetAddressOf();
planeParameters[1].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
ThrowIfFailed(
m_commandQueue->PresentX(2, planeParameters, params)
);
}
else
{
ThrowIfFailed(
m_commandQueue->PresentX(1, planeParameters, params)
);
planeParameters.ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
}
// Xbox One apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
ThrowIfFailed(
m_commandQueue->PresentX(1, &planeParameters, params)
);
MoveToNextFrame();
// Xbox apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
// Update the back buffer index.
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
}
// Handle GPU suspend/resume
@ -436,13 +407,13 @@ void DeviceResources::WaitForGpu() noexcept
if (m_commandQueue && m_fence && m_fenceEvent.IsValid())
{
// Schedule a Signal command in the GPU queue.
UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
const UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
if (SUCCEEDED(m_commandQueue->Signal(m_fence.Get(), fenceValue)))
{
// Wait until the Signal has been processed.
if (SUCCEEDED(m_fence->SetEventOnCompletion(fenceValue, m_fenceEvent.Get())))
{
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
std::ignore = WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
// Increment the fence value for the current frame.
m_fenceValues[m_backBufferIndex]++;
@ -451,25 +422,17 @@ void DeviceResources::WaitForGpu() noexcept
}
}
// Prepare to render the next frame.
void DeviceResources::MoveToNextFrame()
// For PresentX rendering, we should wait for the origin event just before processing input.
void DeviceResources::WaitForOrigin()
{
// Schedule a Signal command in the queue.
const UINT64 currentFenceValue = m_fenceValues[m_backBufferIndex];
ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), currentFenceValue));
// Update the back buffer index.
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
// If the next frame is not ready to be rendered yet, wait until it is ready.
if (m_fence->GetCompletedValue() < m_fenceValues[m_backBufferIndex])
{
ThrowIfFailed(m_fence->SetEventOnCompletion(m_fenceValues[m_backBufferIndex], m_fenceEvent.Get()));
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
}
// Set the fence value for the next frame.
m_fenceValues[m_backBufferIndex] = currentFenceValue + 1;
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(
D3D12XBOX_FRAME_EVENT_ORIGIN,
INFINITE,
nullptr,
D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE,
&m_framePipelineToken));
}
// Set frame interval and register for frame events

Просмотреть файл

@ -10,8 +10,11 @@ namespace DX
class DeviceResources
{
public:
static constexpr unsigned int c_Enable4K_UHD = 0x1;
static constexpr unsigned int c_EnableHDR = 0x2;
static constexpr unsigned int c_Enable4K_UHD = 0x1;
static constexpr unsigned int c_EnableQHD = 0x2;
static constexpr unsigned int c_EnableHDR = 0x4;
static constexpr unsigned int c_ReverseDepth = 0x8;
static constexpr unsigned int c_AmplificationShaders = 0x10;
DeviceResources(DXGI_FORMAT backBufferFormat = DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D32_FLOAT,
@ -25,7 +28,11 @@ namespace DX
DeviceResources(DeviceResources const&) = delete;
DeviceResources& operator= (DeviceResources const&) = delete;
#ifdef _GAMING_XBOX_SCARLETT
void CreateDeviceResources(D3D12XBOX_CREATE_DEVICE_FLAGS createDeviceFlags = D3D12XBOX_CREATE_DEVICE_FLAG_NONE);
#else
void CreateDeviceResources();
#endif
void CreateWindowSizeDependentResources();
void SetWindow(HWND window) noexcept { m_window = window; }
void Prepare(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_PRESENT,
@ -35,6 +42,7 @@ namespace DX
void Suspend();
void Resume();
void WaitForGpu() noexcept;
void WaitForOrigin();
// Device Accessors.
RECT GetOutputSize() const noexcept { return m_outputSize; }
@ -67,19 +75,7 @@ namespace DX
return CD3DX12_CPU_DESCRIPTOR_HANDLE(m_dsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
}
// Direct3D HDR Game DVR support for Xbox One.
ID3D12Resource* GetGameDVRRenderTarget() const noexcept { return m_renderTargetsGameDVR[m_backBufferIndex].Get(); }
DXGI_FORMAT GetGameDVRFormat() const noexcept { return m_gameDVRFormat; }
CD3DX12_CPU_DESCRIPTOR_HANDLE GetGameDVRRenderTargetView() const noexcept
{
return CD3DX12_CPU_DESCRIPTOR_HANDLE(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(m_backBufferCount + m_backBufferIndex), m_rtvDescriptorSize);
}
private:
void MoveToNextFrame();
void RegisterFrameEvents();
static constexpr size_t MAX_BACK_BUFFER_COUNT = 3;
@ -126,9 +122,5 @@ namespace DX
// DeviceResources options (see flags above)
unsigned int m_options;
// Direct3D HDR Game DVR support for Xbox One.
Microsoft::WRL::ComPtr<ID3D12Resource> m_renderTargetsGameDVR[MAX_BACK_BUFFER_COUNT];
DXGI_FORMAT m_gameDVRFormat;
};
}

Просмотреть файл

@ -1,7 +1,7 @@
//--------------------------------------------------------------------------------------
// Main.cpp
//
// Entry point for Microsoft GDK with Xbox extensions.
// Entry point for Microsoft GDK with Xbox extensions
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
@ -18,16 +18,25 @@
using namespace DirectX;
#ifdef __clang__
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wswitch-enum"
#endif
#pragma warning(disable : 4061)
namespace
{
std::unique_ptr<Sample> g_sample;
HANDLE g_plmSuspendComplete = nullptr;
HANDLE g_plmSignalResume = nullptr;
};
}
bool g_HDRMode = false;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void SetDisplayMode() noexcept;
void ExitSample() noexcept;
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
@ -58,6 +67,8 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
// Register class and create window
PAPPSTATE_REGISTRATION hPLM = {};
PAPPCONSTRAIN_REGISTRATION hPLM2 = {};
{
// Register class
WNDCLASSEXA wcex = {};
@ -66,7 +77,7 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = u8"ComputeParticlesWindowClass";
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
if (!RegisterClassExA(&wcex))
return 1;
@ -79,17 +90,7 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
ShowWindow(hwnd, nCmdShow);
if (g_sample->RequestHDRMode())
{
// Request HDR mode.
auto result = XDisplayTryEnableHdrMode(XDisplayHdrModePreference::PreferHdr, nullptr);
g_HDRMode = (result == XDisplayHdrModeResult::Enabled);
#ifdef _DEBUG
OutputDebugStringA((g_HDRMode) ? "INFO: Display in HDR Mode\n" : "INFO: Display in SDR Mode\n");
#endif
}
SetDisplayMode();
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_sample.get()));
@ -116,7 +117,7 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
PostMessage(reinterpret_cast<HWND>(context), WM_USER, 0, 0);
// To defer suspend, you must wait to exit this callback
(void)WaitForSingleObject(g_plmSuspendComplete, INFINITE);
std::ignore = WaitForSingleObject(g_plmSuspendComplete, INFINITE);
}
else
{
@ -124,6 +125,13 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
}
}, hwnd, &hPLM))
return 1;
if (RegisterAppConstrainedChangeNotification([](BOOLEAN constrained, PVOID context)
{
// To ensure we use the main UI thread to process the notification, we self-post a message
SendMessage(reinterpret_cast<HWND>(context), WM_USER + 1, (constrained) ? 1u : 0u, 0);
}, hwnd, &hPLM2))
return 1;
}
// Main message loop
@ -144,13 +152,14 @@ int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR lp
g_sample.reset();
UnregisterAppStateChangeNotification(hPLM);
UnregisterAppConstrainedChangeNotification(hPLM2);
CloseHandle(g_plmSuspendComplete);
CloseHandle(g_plmSignalResume);
XGameRuntimeUninitialize();
return (int) msg.wParam;
return static_cast<int>(msg.wParam);
}
// Windows procedure
@ -168,18 +177,52 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
// Complete deferral
SetEvent(g_plmSuspendComplete);
(void)WaitForSingleObject(g_plmSignalResume, INFINITE);
std::ignore = WaitForSingleObject(g_plmSignalResume, INFINITE);
SetDisplayMode();
sample->OnResuming();
}
break;
case WM_USER + 1:
if (sample)
{
if (wParam)
{
sample->OnConstrained();
}
else
{
SetDisplayMode();
sample->OnUnConstrained();
}
}
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// HDR helper
void SetDisplayMode() noexcept
{
if (g_sample && g_sample->RequestHDRMode())
{
// Request HDR mode.
auto result = XDisplayTryEnableHdrMode(XDisplayHdrModePreference::PreferHdr, nullptr);
g_HDRMode = (result == XDisplayHdrModeResult::Enabled);
#ifdef _DEBUG
OutputDebugStringA((g_HDRMode) ? "INFO: Display in HDR Mode\n" : "INFO: Display in SDR Mode\n");
#endif
}
}
// Exit helper
void ExitSample()
void ExitSample() noexcept
{
PostQuitMessage(0);
}

Просмотреть файл

@ -111,7 +111,7 @@ namespace DX
timeDelta *= TicksPerSecond;
timeDelta /= static_cast<uint64_t>(m_qpcFrequency.QuadPart);
uint32_t lastFrameCount = m_frameCount;
const uint32_t lastFrameCount = m_frameCount;
if (m_isFixedTimeStep)
{

Просмотреть файл

@ -37,8 +37,8 @@
#include <gxdk.h>
#if _GXDK_VER < 0x4A610D2B /* GXDK Edition 200600 */
#error This sample requires the June 2020 GDK or later
#if _GXDK_VER < 0x55F007B0 /* GDK Edition 211000 */
#error This sample requires the October 2021 GDK or later
#endif
#ifdef _GAMING_XBOX_SCARLETT
@ -56,14 +56,21 @@
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <exception>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <string>
#include <system_error>
#include <tuple>
#include <assert.h>
#include <stdio.h>
#include <pix3.h>
#include <XGame.h>
@ -93,7 +100,7 @@ namespace DX
class com_exception : public std::exception
{
public:
com_exception(HRESULT hr) : result(hr) {}
com_exception(HRESULT hr) noexcept : result(hr) {}
const char* what() const override
{

Двоичные данные
Samples/Graphics/ComputeParticles/readme.docx

Двоичный файл не отображается.

Просмотреть файл

@ -29,7 +29,7 @@ Sample::Sample() noexcept(false) :
m_holeSize(0.1f)
{
// Renders only 2D, so no need for a depth buffer.
m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_UNKNOWN, 2);
m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_UNKNOWN);
m_deviceResources->RegisterDeviceNotify(this);
}
@ -50,7 +50,7 @@ void Sample::Initialize(HWND window, int width, int height)
m_deviceResources->SetWindow(window, width, height);
m_deviceResources->CreateDeviceResources();
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
@ -63,6 +63,10 @@ void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %llu", m_frame);
#ifdef _GAMING_XBOX
m_deviceResources->WaitForOrigin();
#endif
m_timer.Tick([&]()
{
Update(m_timer);
@ -86,7 +90,7 @@ void Sample::Update(DX::StepTimer const& timer)
m_keyboardButtons.Update(kb);
const float SPEED_OF_CHANGE = 0.25f;
constexpr float SPEED_OF_CHANGE = 0.25f;
if (pad.IsConnected())
{
@ -223,8 +227,8 @@ void Sample::RenderHUD(ID3D12GraphicsCommandList* commandList)
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
auto size = m_deviceResources->GetOutputSize();
auto safe = SimpleMath::Viewport::ComputeTitleSafeArea((UINT)size.right, (UINT)size.bottom);
auto const size = m_deviceResources->GetOutputSize();
auto const safe = SimpleMath::Viewport::ComputeTitleSafeArea((UINT)size.right, (UINT)size.bottom);
wchar_t textBuffer[128] = {};
XMFLOAT2 textPos = XMFLOAT2(float(safe.left), float(safe.top));
@ -265,14 +269,6 @@ void Sample::RenderHUD(ID3D12GraphicsCommandList* commandList)
#pragma region Message Handlers
// Message handlers
void Sample::OnActivated()
{
}
void Sample::OnDeactivated()
{
}
void Sample::OnSuspending()
{
m_deviceResources->Suspend();
@ -288,7 +284,7 @@ void Sample::OnResuming()
void Sample::OnWindowMoved()
{
auto r = m_deviceResources->GetOutputSize();
auto const r = m_deviceResources->GetOutputSize();
m_deviceResources->WindowSizeChanged(r.right, r.bottom);
}
@ -314,6 +310,11 @@ void Sample::CreateRaytracingPipeline()
{
auto device = m_deviceResources->GetD3DDevice();
#if defined(_GAMING_XBOX_SCARLETT) && (_GRDK_VER >= 0x55F00C58 /* GDK Edition 220300 */)
// Save the RtPso PDB on the scratch drive
device->SetCompileTimeShaderPdbPathX(L"D:\\");
#endif
CD3DX12_STATE_OBJECT_DESC raytracingPipeline{ D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE };
auto raytracingLibrary = raytracingPipeline.CreateSubobject<CD3DX12_DXIL_LIBRARY_SUBOBJECT>();
@ -387,10 +388,10 @@ void Sample::BuildBottomLevelAccelerationStructure(bool buildEveryFrame)
auto device = m_deviceResources->GetD3DDevice();
auto commandList = m_deviceResources->GetCommandList();
const UINT vertexCount = 3;
const UINT vertexSize = sizeof(XMFLOAT3);
const UINT indexCount = 3;
const UINT indexSize = sizeof(UINT);
constexpr UINT vertexCount = 3;
constexpr UINT vertexSize = sizeof(XMFLOAT3);
constexpr UINT indexCount = 3;
constexpr UINT indexSize = sizeof(UINT);
// Build a BLAS for one triangle...
D3D12_RAYTRACING_GEOMETRY_DESC geometryDesc = { D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, D3D12_RAYTRACING_GEOMETRY_FLAG_NONE, {} };
@ -556,8 +557,8 @@ void Sample::CreateDeviceDependentResources()
resourceUpload.Begin();
// HUD
auto backBufferRts = RenderTargetState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
auto spritePSD = SpriteBatchPipelineStateDescription(backBufferRts, &CommonStates::AlphaBlend);
const RenderTargetState backBufferRts(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
const SpriteBatchPipelineStateDescription spritePSD(backBufferRts, &CommonStates::AlphaBlend);
m_hudBatch = std::make_unique<SpriteBatch>(device, resourceUpload, spritePSD);
wchar_t strFilePath[MAX_PATH] = {};
@ -583,7 +584,7 @@ void Sample::CreateDeviceDependentResources()
void Sample::CreateWindowSizeDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
RECT outputSize = m_deviceResources->GetOutputSize();
auto const outputSize = m_deviceResources->GetOutputSize();
D3D12_HEAP_PROPERTIES defaultHeapProps = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);

Просмотреть файл

@ -13,10 +13,7 @@
struct SimpleTriangleRecord : public ShaderRecord
{
SimpleTriangleRecord() : ShaderRecord()
{
}
SimpleTriangleRecord() = default;
SimpleTriangleRecord(ID3D12StateObjectProperties* props, LPCWSTR exportName)
{
@ -64,8 +61,8 @@ public:
void OnDeviceRestored() override;
// Messages
void OnActivated();
void OnDeactivated();
void OnActivated() {}
void OnDeactivated() {}
void OnSuspending();
void OnResuming();
void OnWindowMoved();

Просмотреть файл

@ -438,6 +438,9 @@
</EntryPointName>
<EntryPointName Condition="'$(Configuration)|$(Platform)'=='Profile|Gaming.Desktop.x64'">
</EntryPointName>
<AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Xbox.Scarlett.x64'">/Qembed_debug %(AdditionalOptions)</AdditionalOptions>
<AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Release|Gaming.Xbox.Scarlett.x64'">/Qembed_debug %(AdditionalOptions)</AdditionalOptions>
<AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Profile|Gaming.Xbox.Scarlett.x64'">/Qembed_debug %(AdditionalOptions)</AdditionalOptions>
</FxCompile>
</ItemGroup>
<ItemGroup>

Просмотреть файл

@ -1,7 +1,7 @@
//
// DeviceResources.cpp - A wrapper for the Direct3D 12/12.X device and swapchain
//
// Modified to use ID3D12Device6/ID3D12GraphicsCommandList5 for DXR access
// Modified to use ID3D12Device8/ID3D12GraphicsCommandList5 for DXR access
//
#include "pch.h"
@ -12,7 +12,6 @@ using namespace DX;
using Microsoft::WRL::ComPtr;
#ifdef _GAMING_DESKTOP
#ifdef __clang__
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wswitch-enum"
@ -20,6 +19,7 @@ using Microsoft::WRL::ComPtr;
#pragma warning(disable : 4061)
#ifdef _GAMING_DESKTOP
namespace
{
inline DXGI_FORMAT NoSRGB(DXGI_FORMAT fmt) noexcept
@ -39,7 +39,8 @@ namespace
DeviceResources::DeviceResources(
DXGI_FORMAT backBufferFormat,
DXGI_FORMAT depthBufferFormat,
UINT backBufferCount) noexcept(false) :
UINT backBufferCount,
unsigned int flags) noexcept(false) :
m_backBufferIndex(0),
m_fenceValues{},
#ifdef _GAMING_XBOX
@ -54,6 +55,7 @@ DeviceResources::DeviceResources(
m_window(nullptr),
m_d3dFeatureLevel(D3D_FEATURE_LEVEL_11_0),
m_outputSize{ 0, 0, 1, 1 },
m_options(flags),
m_deviceNotify(nullptr)
{
if (backBufferCount < 2 || backBufferCount > MAX_BACK_BUFFER_COUNT)
@ -72,7 +74,7 @@ DeviceResources::~DeviceResources()
// Ensure we present a blank screen before cleaning up resources.
if (m_commandQueue)
{
(void)m_commandQueue->PresentX(0, nullptr, nullptr);
std::ignore = m_commandQueue->PresentX(0, nullptr, nullptr);
}
#endif
}
@ -98,6 +100,14 @@ void DeviceResources::CreateDeviceResources()
params.GraphicsScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.ComputeScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
#if defined(_GAMING_XBOX_SCARLETT) && (_GRDK_VER >= 0x585D070E /* GXDK Edition 221000 */)
if (m_options & c_AmplificationShaders)
{
params.AmplificationShaderIndirectArgsBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.AmplificationShaderPayloadBufferSize = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
}
#endif
HRESULT hr = D3D12XboxCreateDevice(
nullptr,
&params,
@ -171,7 +181,7 @@ void DeviceResources::CreateDeviceResources()
#ifdef _DEBUG
if (hr == E_NOINTERFACE)
{
OutputDebugStringA("ERROR: Requires Windows 10 (Version 1903, Build 18362) or later\n");
OutputDebugStringA("ERROR: Requires Windows 10 (Version 2004, Build 19041) or later\n");
}
#endif
ThrowIfFailed(hr);
@ -326,7 +336,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
// Obtain the back buffers for this window which will be the final render targets
// and create render target views for each of them.
CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC swapChainBufferDesc = CD3DX12_RESOURCE_DESC::Tex2D(
m_backBufferFormat,
@ -358,7 +368,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
rtvDesc.Format = m_backBufferFormat;
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
const CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(n), m_rtvDescriptorSize);
m_d3dDevice->CreateRenderTargetView(m_renderTargets[n].Get(), &rtvDesc, rtvDescriptor);
@ -369,7 +379,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
#else // _GAMING_DESKTOP
DXGI_FORMAT backBufferFormat = NoSRGB(m_backBufferFormat);
const DXGI_FORMAT backBufferFormat = NoSRGB(m_backBufferFormat);
// If the swap chain already exists, resize it, otherwise create one.
if (m_swapChain)
@ -452,7 +462,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
rtvDesc.Format = m_backBufferFormat;
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
const CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(n), m_rtvDescriptorSize);
m_d3dDevice->CreateRenderTargetView(m_renderTargets[n].Get(), &rtvDesc, rtvDescriptor);
@ -467,7 +477,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
{
// Allocate a 2-D surface as the depth/stencil buffer and create a depth/stencil view
// on this surface.
CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_HEAP_PROPERTIES depthHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
D3D12_RESOURCE_DESC depthStencilDesc = CD3DX12_RESOURCE_DESC::Tex2D(
m_depthBufferFormat,
@ -480,7 +490,7 @@ void DeviceResources::CreateWindowSizeDependentResources()
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = m_depthBufferFormat;
depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
depthOptimizedClearValue.DepthStencil.Depth = (m_options & c_ReverseDepth) ? 0.0f : 1.0f;
depthOptimizedClearValue.DepthStencil.Stencil = 0;
ThrowIfFailed(m_d3dDevice->CreateCommittedResource(
@ -591,12 +601,6 @@ void DeviceResources::HandleDeviceLost()
// Prepare the command list and render target for rendering.
void DeviceResources::Prepare(D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState)
{
#ifdef _GAMING_XBOX
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, nullptr, D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE, &m_framePipelineToken));
#endif
// Reset command list and allocator.
ThrowIfFailed(m_commandAllocators[m_backBufferIndex]->Reset());
ThrowIfFailed(m_commandList->Reset(m_commandAllocators[m_backBufferIndex].Get(), nullptr));
@ -604,7 +608,8 @@ void DeviceResources::Prepare(D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_
if (beforeState != afterState)
{
// Transition the render target into the correct state to allow for drawing into it.
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(),
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, afterState);
m_commandList->ResourceBarrier(1, &barrier);
}
@ -616,7 +621,9 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState)
if (beforeState != D3D12_RESOURCE_STATE_PRESENT)
{
// Transition the render target to the state that allows it to be presented to the display.
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_backBufferIndex].Get(), beforeState, D3D12_RESOURCE_STATE_PRESENT);
const D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
beforeState, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &barrier);
}
@ -636,9 +643,12 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState)
m_commandQueue->PresentX(1, &planeParameters, nullptr)
);
// Xbox One apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
// Xbox apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
#else
// Update the back buffer index.
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
#else // _GAMING_DESKTOP
// The first argument instructs DXGI to block until VSync, putting the application
// to sleep until the next VSync. This ensures we don't waste any cycles rendering
@ -661,9 +671,8 @@ void DeviceResources::Present(D3D12_RESOURCE_STATES beforeState)
ThrowIfFailed(hr);
}
#endif
MoveToNextFrame();
#endif
}
// Handle GPU suspend/resume
@ -689,13 +698,13 @@ void DeviceResources::WaitForGpu() noexcept
if (m_commandQueue && m_fence && m_fenceEvent.IsValid())
{
// Schedule a Signal command in the GPU queue.
UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
const UINT64 fenceValue = m_fenceValues[m_backBufferIndex];
if (SUCCEEDED(m_commandQueue->Signal(m_fence.Get(), fenceValue)))
{
// Wait until the Signal has been processed.
if (SUCCEEDED(m_fence->SetEventOnCompletion(fenceValue, m_fenceEvent.Get())))
{
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
std::ignore = WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
// Increment the fence value for the current frame.
m_fenceValues[m_backBufferIndex]++;
@ -704,32 +713,20 @@ void DeviceResources::WaitForGpu() noexcept
}
}
// Prepare to render the next frame.
void DeviceResources::MoveToNextFrame()
{
// Schedule a Signal command in the queue.
const UINT64 currentFenceValue = m_fenceValues[m_backBufferIndex];
ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), currentFenceValue));
// Update the back buffer index.
#ifdef _GAMING_XBOX
m_backBufferIndex = (m_backBufferIndex + 1) % m_backBufferCount;
#else
m_backBufferIndex = m_swapChain->GetCurrentBackBufferIndex();
#endif
// If the next frame is not ready to be rendered yet, wait until it is ready.
if (m_fence->GetCompletedValue() < m_fenceValues[m_backBufferIndex])
{
ThrowIfFailed(m_fence->SetEventOnCompletion(m_fenceValues[m_backBufferIndex], m_fenceEvent.Get()));
WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
}
// Set the fence value for the next frame.
m_fenceValues[m_backBufferIndex] = currentFenceValue + 1;
// For PresentX rendering, we should wait for the origin event just before processing input.
void DeviceResources::WaitForOrigin()
{
// Wait until frame start is signaled
m_framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(m_d3dDevice->WaitFrameEventX(
D3D12XBOX_FRAME_EVENT_ORIGIN,
INFINITE,
nullptr,
D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE,
&m_framePipelineToken));
}
#ifdef _GAMING_XBOX
// Set frame interval and register for frame events
void DeviceResources::RegisterFrameEvents()
{
@ -758,7 +755,30 @@ void DeviceResources::RegisterFrameEvents()
nullptr,
D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE));
}
#else
#else // _GAMING_DESKTOP
// Prepare to render the next frame.
void DeviceResources::MoveToNextFrame()
{
// Schedule a Signal command in the queue.
const UINT64 currentFenceValue = m_fenceValues[m_backBufferIndex];
ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), currentFenceValue));
// Update the back buffer index.
m_backBufferIndex = m_swapChain->GetCurrentBackBufferIndex();
// If the next frame is not ready to be rendered yet, wait until it is ready.
if (m_fence->GetCompletedValue() < m_fenceValues[m_backBufferIndex])
{
ThrowIfFailed(m_fence->SetEventOnCompletion(m_fenceValues[m_backBufferIndex], m_fenceEvent.Get()));
std::ignore = WaitForSingleObjectEx(m_fenceEvent.Get(), INFINITE, FALSE);
}
// Set the fence value for the next frame.
m_fenceValues[m_backBufferIndex] = currentFenceValue + 1;
}
// This method acquires the first available hardware adapter that supports Direct3D 12.
// If no such adapter can be found, try WARP. Otherwise throw an exception.
void DeviceResources::GetAdapter(IDXGIAdapter1** ppAdapter)

Просмотреть файл

@ -1,7 +1,7 @@
//
// DeviceResources.h - A wrapper for the Direct3D 12/12.X device and swapchain
//
// Modified to use ID3D12Device6/ID3D12GraphicsCommandList5 for DXR access
// Modified to use ID3D12Device8/ID3D12GraphicsCommandList5 for DXR access
//
#pragma once
@ -22,9 +22,13 @@ namespace DX
class DeviceResources
{
public:
static constexpr unsigned int c_ReverseDepth = 0x1;
static constexpr unsigned int c_AmplificationShaders = 0x2;
DeviceResources(DXGI_FORMAT backBufferFormat = DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D32_FLOAT,
UINT backBufferCount = 2) noexcept(false);
UINT backBufferCount = 2,
unsigned int flags = 0) noexcept(false);
~DeviceResources();
DeviceResources(DeviceResources&&) = default;
@ -45,6 +49,9 @@ namespace DX
void Suspend();
void Resume();
void WaitForGpu() noexcept;
#ifdef _GAMING_XBOX
void WaitForOrigin();
#endif
// Device Accessors.
RECT GetOutputSize() const noexcept { return m_outputSize; }
@ -68,6 +75,7 @@ namespace DX
D3D12_RECT GetScissorRect() const noexcept { return m_scissorRect; }
UINT GetCurrentFrameIndex() const noexcept { return m_backBufferIndex; }
UINT GetBackBufferCount() const noexcept { return m_backBufferCount; }
unsigned int GetDeviceOptions() const noexcept { return m_options; }
CD3DX12_CPU_DESCRIPTOR_HANDLE GetRenderTargetView() const noexcept
{
@ -81,10 +89,10 @@ namespace DX
}
private:
void MoveToNextFrame();
#ifdef _GAMING_XBOX
void RegisterFrameEvents();
#else
void MoveToNextFrame();
void GetAdapter(IDXGIAdapter1** ppAdapter);
#endif
@ -93,7 +101,7 @@ namespace DX
UINT m_backBufferIndex;
// Direct3D objects.
Microsoft::WRL::ComPtr<ID3D12Device6> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D12Device8> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList5> m_commandList;
Microsoft::WRL::ComPtr<ID3D12CommandQueue> m_commandQueue;
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> m_commandAllocators[MAX_BACK_BUFFER_COUNT];
@ -131,6 +139,9 @@ namespace DX
D3D_FEATURE_LEVEL m_d3dFeatureLevel;
RECT m_outputSize;
// DeviceResources options (see flags above)
unsigned int m_options;
// The IDeviceNotify can be held directly as it owns the DeviceResources.
IDeviceNotify* m_deviceNotify;
};

Просмотреть файл

@ -417,7 +417,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
}
else
{
SetWindowLongPtr(hWnd, GWL_STYLE, 0);
SetWindowLongPtr(hWnd, GWL_STYLE, WS_POPUP);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);

Просмотреть файл

@ -111,7 +111,7 @@ namespace DX
timeDelta *= TicksPerSecond;
timeDelta /= static_cast<uint64_t>(m_qpcFrequency.QuadPart);
uint32_t lastFrameCount = m_frameCount;
const uint32_t lastFrameCount = m_frameCount;
if (m_isFixedTimeStep)
{

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше