diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4d70bc3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,187 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Roslyn cache directories +*.ide/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +#NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +## TODO: Comment the next line if you want to checkin your +## web deploy settings but do note that will include unencrypted +## passwords +#*.pubxml + +# NuGet Packages Directory +packages/* +## TODO: If the tool you use requires repositories.config +## uncomment the next line +#!packages/repositories.config + +# Enable "build/" folder in the NuGet Packages folder since +# NuGet packages use it for MSBuild targets. +# This line needs to be after the ignore of the build folder +# (and the packages folder if the line above has been uncommented) +!packages/build/ + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.publishsettings +node_modules/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml \ No newline at end of file diff --git a/DirectXSceneStore/Assets/credits.txt b/DirectXSceneStore/Assets/credits.txt deleted file mode 100644 index 1c9e305..0000000 --- a/DirectXSceneStore/Assets/credits.txt +++ /dev/null @@ -1,30 +0,0 @@ -============================= -MICROSOFT CORPORATION CREDITS -============================= - -The Simple3DGame sample uses several texture assets that were obtained -from various sources listed below. - -From http://www.3dmd.net under the terms of the license found at http://www.3dmd.net/license.htm: - metal_texture.dds - oldWood4_nt.dds -These textures were converted from the original files: - seamless_brushed_aluminum_metal_texture.jpeg - oldWood4_nt.jpeg - -From http://www.filterforge.com (Filter Forge, Rawn (RawArt)) - nightfloor.dds - daywall.dds and dayceiling.dds -These textures were converted from the original files: - "Asteroid" http://www.filterforge.com/filters/3215.html - "cloudy sky" http://www.filterforge.com/filters/4213.jpg - -From http://1-background.com (StarFields, Silvia Harmann, http://www.1-art.eu) - nightwall.dds and nightceiling.dds -These textures were converted from the orginal file: - "Starfield" http://1-background.com/images/stars-1/beautiful-blue-stars-fill.jpg - -From http://www.shutterstock.com (Shutterstock; Zsolt Horvath, 2012 licensed under Shutterstock.) - dayfloor.dds -This texture was converted from the original file: - "Grass" http://image.shutterstock.com/display_pic_with_logo/77946/77946,1168953758,1/stock-photo-seamless-tiling-medium-length-grass-texture-part-of-the-seamless-tiling-collection-2496056.jpg diff --git a/DirectXSceneStore/Common/BasicLoader.cpp b/DirectXSceneStore/Common/BasicLoader.cpp deleted file mode 100644 index f1badb1..0000000 --- a/DirectXSceneStore/Common/BasicLoader.cpp +++ /dev/null @@ -1,873 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "BasicLoader.h" -#include "BasicShapes.h" -#include "DDSTextureLoader.h" -#include "DirectXSample.h" -#include - -using namespace Microsoft::WRL; -using namespace Windows::Storage; -using namespace Windows::Storage::Streams; -using namespace Windows::Foundation; -using namespace Windows::ApplicationModel; -using namespace std; -using namespace concurrency; - -BasicLoader::BasicLoader( - _In_ ID3D11Device* d3dDevice, - _In_opt_ IWICImagingFactory2* wicFactory - ) : - m_d3dDevice(d3dDevice), - m_wicFactory(wicFactory) -{ - // Create a new BasicReaderWriter to do raw file I/O. - m_basicReaderWriter = ref new BasicReaderWriter(); -} - -template -inline void BasicLoader::SetDebugName( - _In_ DeviceChildType* object, - _In_ Platform::String^ name - ) -{ -#if defined(_DEBUG) - // Only assign debug names in debug builds. - - char nameString[1024]; - int nameStringLength = WideCharToMultiByte( - CP_ACP, - 0, - name->Data(), - -1, - nameString, - 1024, - nullptr, - nullptr - ); - - if (nameStringLength == 0) - { - char defaultNameString[] = "BasicLoaderObject"; - DX::ThrowIfFailed( - object->SetPrivateData( - WKPDID_D3DDebugObjectName, - sizeof(defaultNameString) - 1, - defaultNameString - ) - ); - } - else - { - DX::ThrowIfFailed( - object->SetPrivateData( - WKPDID_D3DDebugObjectName, - nameStringLength - 1, - nameString - ) - ); - } -#endif -} - -Platform::String^ BasicLoader::GetExtension( - _In_ Platform::String^ filename - ) -{ - int lastDotIndex = -1; - for (int i = filename->Length() - 1; i >= 0 && lastDotIndex == -1; i--) - { - if (*(filename->Data() + i) == '.') - { - lastDotIndex = i; - } - } - if (lastDotIndex != -1) - { - std::unique_ptr extension(new wchar_t[filename->Length() - lastDotIndex]); - for (unsigned int i = 0; i < filename->Length() - lastDotIndex; i++) - { - extension[i] = tolower(*(filename->Data() + lastDotIndex + 1 + i)); - } - return ref new Platform::String(extension.get()); - } - return ""; -} - -void BasicLoader::CreateTexture( - _In_ bool decodeAsDDS, - _In_reads_bytes_(dataSize) byte* data, - _In_ uint32 dataSize, - _Out_opt_ ID3D11Texture2D** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView, - _In_opt_ Platform::String^ debugName - ) -{ - ComPtr shaderResourceView; - ComPtr texture2D; - - if (decodeAsDDS) - { - ComPtr resource; - - if (textureView == nullptr) - { - CreateDDSTextureFromMemory( - m_d3dDevice.Get(), - data, - dataSize, - &resource, - nullptr - ); - } - else - { - CreateDDSTextureFromMemory( - m_d3dDevice.Get(), - data, - dataSize, - &resource, - &shaderResourceView - ); - } - - DX::ThrowIfFailed( - resource.As(&texture2D) - ); - } - else - { - if (m_wicFactory.Get() == nullptr) - { - // A WIC factory object is required in order to load texture - // assets stored in non-DDS formats. If BasicLoader was not - // initialized with one, create one as needed. - DX::ThrowIfFailed( - CoCreateInstance( - CLSID_WICImagingFactory, - nullptr, - CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(&m_wicFactory) - ) - ); - } - - ComPtr stream; - DX::ThrowIfFailed( - m_wicFactory->CreateStream(&stream) - ); - - DX::ThrowIfFailed( - stream->InitializeFromMemory( - data, - dataSize - ) - ); - - ComPtr bitmapDecoder; - DX::ThrowIfFailed( - m_wicFactory->CreateDecoderFromStream( - stream.Get(), - nullptr, - WICDecodeMetadataCacheOnDemand, - &bitmapDecoder - ) - ); - - ComPtr bitmapFrame; - DX::ThrowIfFailed( - bitmapDecoder->GetFrame(0, &bitmapFrame) - ); - - ComPtr formatConverter; - DX::ThrowIfFailed( - m_wicFactory->CreateFormatConverter(&formatConverter) - ); - - DX::ThrowIfFailed( - formatConverter->Initialize( - bitmapFrame.Get(), - GUID_WICPixelFormat32bppPBGRA, - WICBitmapDitherTypeNone, - nullptr, - 0.0, - WICBitmapPaletteTypeCustom - ) - ); - - uint32 width; - uint32 height; - DX::ThrowIfFailed( - bitmapFrame->GetSize(&width, &height) - ); - - std::unique_ptr bitmapPixels(new byte[width * height * 4]); - DX::ThrowIfFailed( - formatConverter->CopyPixels( - nullptr, - width * 4, - width * height * 4, - bitmapPixels.get() - ) - ); - - D3D11_SUBRESOURCE_DATA initialData; - ZeroMemory(&initialData, sizeof(initialData)); - initialData.pSysMem = bitmapPixels.get(); - initialData.SysMemPitch = width * 4; - initialData.SysMemSlicePitch = 0; - - CD3D11_TEXTURE2D_DESC textureDesc( - DXGI_FORMAT_B8G8R8A8_UNORM, - width, - height, - 1, - 1 - ); - - DX::ThrowIfFailed( - m_d3dDevice->CreateTexture2D( - &textureDesc, - &initialData, - &texture2D - ) - ); - - if (textureView != nullptr) - { - CD3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc( - texture2D.Get(), - D3D11_SRV_DIMENSION_TEXTURE2D - ); - - DX::ThrowIfFailed( - m_d3dDevice->CreateShaderResourceView( - texture2D.Get(), - &shaderResourceViewDesc, - &shaderResourceView - ) - ); - } - } - - SetDebugName(texture2D.Get(), debugName); - - if (texture != nullptr) - { - *texture = texture2D.Detach(); - } - if (textureView != nullptr) - { - *textureView = shaderResourceView.Detach(); - } -} - -void BasicLoader::CreateInputLayout( - _In_reads_bytes_(bytecodeSize) byte* bytecode, - _In_ uint32 bytecodeSize, - _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC* layoutDesc, - _In_ uint32 layoutDescNumElements, - _Out_ ID3D11InputLayout** layout - ) -{ - if (layoutDesc == nullptr) - { - // If no input layout is specified, use the BasicVertex layout. - const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] = - { - { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - }; - - DX::ThrowIfFailed( - m_d3dDevice->CreateInputLayout( - basicVertexLayoutDesc, - ARRAYSIZE(basicVertexLayoutDesc), - bytecode, - bytecodeSize, - layout - ) - ); - } - else - { - DX::ThrowIfFailed( - m_d3dDevice->CreateInputLayout( - layoutDesc, - layoutDescNumElements, - bytecode, - bytecodeSize, - layout - ) - ); - } -} - -void BasicLoader::CreateMesh( - _In_ byte* meshData, - _Out_ ID3D11Buffer** vertexBuffer, - _Out_ ID3D11Buffer** indexBuffer, - _Out_opt_ uint32* vertexCount, - _Out_opt_ uint32* indexCount, - _In_opt_ Platform::String^ debugName - ) -{ - // The first 4 bytes of the BasicMesh format define the number of vertices in the mesh. - uint32 numVertices = *reinterpret_cast(meshData); - - // The following 4 bytes define the number of indices in the mesh. - uint32 numIndices = *reinterpret_cast(meshData + sizeof(uint32)); - - // The next segment of the BasicMesh format contains the vertices of the mesh. - BasicVertex* vertices = reinterpret_cast(meshData + sizeof(uint32) * 2); - - // The last segment of the BasicMesh format contains the indices of the mesh. - uint16* indices = reinterpret_cast(meshData + sizeof(uint32) * 2 + sizeof(BasicVertex) * numVertices); - - // Create the vertex and index buffers with the mesh data. - - D3D11_SUBRESOURCE_DATA vertexBufferData = {0}; - vertexBufferData.pSysMem = vertices; - vertexBufferData.SysMemPitch = 0; - vertexBufferData.SysMemSlicePitch = 0; - CD3D11_BUFFER_DESC vertexBufferDesc(numVertices * sizeof(BasicVertex), D3D11_BIND_VERTEX_BUFFER); - DX::ThrowIfFailed( - m_d3dDevice->CreateBuffer( - &vertexBufferDesc, - &vertexBufferData, - vertexBuffer - ) - ); - - D3D11_SUBRESOURCE_DATA indexBufferData = {0}; - indexBufferData.pSysMem = indices; - indexBufferData.SysMemPitch = 0; - indexBufferData.SysMemSlicePitch = 0; - CD3D11_BUFFER_DESC indexBufferDesc(numIndices * sizeof(uint16), D3D11_BIND_INDEX_BUFFER); - DX::ThrowIfFailed( - m_d3dDevice->CreateBuffer( - &indexBufferDesc, - &indexBufferData, - indexBuffer - ) - ); - - SetDebugName(*vertexBuffer, Platform::String::Concat(debugName, "_VertexBuffer")); - SetDebugName(*indexBuffer, Platform::String::Concat(debugName, "_IndexBuffer")); - - if (vertexCount != nullptr) - { - *vertexCount = numVertices; - } - if (indexCount != nullptr) - { - *indexCount = numIndices; - } -} - -void BasicLoader::LoadTexture( - _In_ Platform::String^ filename, - _Out_opt_ ID3D11Texture2D** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView - ) -{ - Platform::Array^ textureData = m_basicReaderWriter->ReadData(filename); - - CreateTexture( - GetExtension(filename) == "dds", - textureData->Data, - textureData->Length, - texture, - textureView, - filename - ); -} - -task BasicLoader::LoadTextureAsync( - _In_ Platform::String^ filename, - _Out_opt_ ID3D11Texture2D** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView - ) -{ - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ textureData) - { - CreateTexture( - GetExtension(filename) == "dds", - textureData->Data, - textureData->Length, - texture, - textureView, - filename - ); - }); -} - -void BasicLoader::LoadShader( - _In_ Platform::String^ filename, - _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], - _In_ uint32 layoutDescNumElements, - _Out_ ID3D11VertexShader** shader, - _Out_opt_ ID3D11InputLayout** layout - ) -{ - Platform::Array^ bytecode = m_basicReaderWriter->ReadData(filename); - - DX::ThrowIfFailed( - m_d3dDevice->CreateVertexShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - - if (layout != nullptr) - { - CreateInputLayout( - bytecode->Data, - bytecode->Length, - layoutDesc, - layoutDescNumElements, - layout - ); - - SetDebugName(*layout, filename); - } -} - -task BasicLoader::LoadShaderAsync( - _In_ Platform::String^ filename, - _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], - _In_ uint32 layoutDescNumElements, - _Out_ ID3D11VertexShader** shader, - _Out_opt_ ID3D11InputLayout** layout - ) -{ - // This method assumes that the lifetime of input arguments may be shorter - // than the duration of this task. In order to ensure accurate results, a - // copy of all arguments passed by pointer must be made. The method then - // ensures that the lifetime of the copied data exceeds that of the task. - - // Create copies of the layoutDesc array as well as the SemanticName strings, - // both of which are pointers to data whose lifetimes may be shorter than that - // of this method's task. - shared_ptr> layoutDescCopy; - shared_ptr> layoutDescSemanticNamesCopy; - if (layoutDesc != nullptr) - { - layoutDescCopy.reset( - new vector( - layoutDesc, - layoutDesc + layoutDescNumElements - ) - ); - - layoutDescSemanticNamesCopy.reset( - new vector(layoutDescNumElements) - ); - - for (uint32 i = 0; i < layoutDescNumElements; i++) - { - layoutDescSemanticNamesCopy->at(i).assign(layoutDesc[i].SemanticName); - } - } - - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) - { - DX::ThrowIfFailed( - m_d3dDevice->CreateVertexShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - - if (layout != nullptr) - { - if (layoutDesc != nullptr) - { - // Reassign the SemanticName elements of the layoutDesc array copy to point - // to the corresponding copied strings. Performing the assignment inside the - // lambda body ensures that the lambda will take a reference to the shared_ptr - // that holds the data. This will guarantee that the data is still valid when - // CreateInputLayout is called. - for (uint32 i = 0; i < layoutDescNumElements; i++) - { - layoutDescCopy->at(i).SemanticName = layoutDescSemanticNamesCopy->at(i).c_str(); - } - } - - CreateInputLayout( - bytecode->Data, - bytecode->Length, - layoutDesc == nullptr ? nullptr : layoutDescCopy->data(), - layoutDescNumElements, - layout - ); - - SetDebugName(*layout, filename); - } - }); -} - -void BasicLoader::LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11PixelShader** shader - ) -{ - Platform::Array^ bytecode = m_basicReaderWriter->ReadData(filename); - - DX::ThrowIfFailed( - m_d3dDevice->CreatePixelShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); -} - -task BasicLoader::LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11PixelShader** shader - ) -{ - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) - { - DX::ThrowIfFailed( - m_d3dDevice->CreatePixelShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - }); -} - -void BasicLoader::LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11ComputeShader** shader - ) -{ - Platform::Array^ bytecode = m_basicReaderWriter->ReadData(filename); - - DX::ThrowIfFailed( - m_d3dDevice->CreateComputeShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); -} - -task BasicLoader::LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11ComputeShader** shader - ) -{ - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) - { - DX::ThrowIfFailed( - m_d3dDevice->CreateComputeShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - }); -} - -void BasicLoader::LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11GeometryShader** shader - ) -{ - Platform::Array^ bytecode = m_basicReaderWriter->ReadData(filename); - - DX::ThrowIfFailed( - m_d3dDevice->CreateGeometryShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); -} - -task BasicLoader::LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11GeometryShader** shader - ) -{ - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) - { - DX::ThrowIfFailed( - m_d3dDevice->CreateGeometryShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - }); -} - -void BasicLoader::LoadShader( - _In_ Platform::String^ filename, - _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration, - _In_ uint32 numEntries, - _In_reads_opt_(numStrides) const uint32* bufferStrides, - _In_ uint32 numStrides, - _In_ uint32 rasterizedStream, - _Out_ ID3D11GeometryShader** shader - ) -{ - Platform::Array^ bytecode = m_basicReaderWriter->ReadData(filename); - - DX::ThrowIfFailed( - m_d3dDevice->CreateGeometryShaderWithStreamOutput( - bytecode->Data, - bytecode->Length, - streamOutDeclaration, - numEntries, - bufferStrides, - numStrides, - rasterizedStream, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); -} - -task BasicLoader::LoadShaderAsync( - _In_ Platform::String^ filename, - _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration, - _In_ uint32 numEntries, - _In_reads_opt_(numStrides) const uint32* bufferStrides, - _In_ uint32 numStrides, - _In_ uint32 rasterizedStream, - _Out_ ID3D11GeometryShader** shader - ) -{ - // This method assumes that the lifetime of input arguments may be shorter - // than the duration of this task. In order to ensure accurate results, a - // copy of all arguments passed by pointer must be made. The method then - // ensures that the lifetime of the copied data exceeds that of the task. - - // Create copies of the streamOutDeclaration array as well as the SemanticName - // strings, both of which are pointers to data whose lifetimes may be shorter - // than that of this method's task. - shared_ptr> streamOutDeclarationCopy; - shared_ptr> streamOutDeclarationSemanticNamesCopy; - if (streamOutDeclaration != nullptr) - { - streamOutDeclarationCopy.reset( - new vector( - streamOutDeclaration, - streamOutDeclaration + numEntries - ) - ); - - streamOutDeclarationSemanticNamesCopy.reset( - new vector(numEntries) - ); - - for (uint32 i = 0; i < numEntries; i++) - { - streamOutDeclarationSemanticNamesCopy->at(i).assign(streamOutDeclaration[i].SemanticName); - } - } - - // Create a copy of the bufferStrides array, which is a pointer to data - // whose lifetime may be shorter than that of this method's task. - shared_ptr> bufferStridesCopy; - if (bufferStrides != nullptr) - { - bufferStridesCopy.reset( - new vector( - bufferStrides, - bufferStrides + numStrides - ) - ); - } - - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) - { - if (streamOutDeclaration != nullptr) - { - // Reassign the SemanticName elements of the streamOutDeclaration array copy to - // point to the corresponding copied strings. Performing the assignment inside the - // lambda body ensures that the lambda will take a reference to the shared_ptr - // that holds the data. This will guarantee that the data is still valid when - // CreateGeometryShaderWithStreamOutput is called. - for (uint32 i = 0; i < numEntries; i++) - { - streamOutDeclarationCopy->at(i).SemanticName = streamOutDeclarationSemanticNamesCopy->at(i).c_str(); - } - } - - DX::ThrowIfFailed( - m_d3dDevice->CreateGeometryShaderWithStreamOutput( - bytecode->Data, - bytecode->Length, - streamOutDeclaration == nullptr ? nullptr : streamOutDeclarationCopy->data(), - numEntries, - bufferStrides == nullptr ? nullptr : bufferStridesCopy->data(), - numStrides, - rasterizedStream, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - }); -} - -void BasicLoader::LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11HullShader** shader - ) -{ - Platform::Array^ bytecode = m_basicReaderWriter->ReadData(filename); - - DX::ThrowIfFailed( - m_d3dDevice->CreateHullShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); -} - -task BasicLoader::LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11HullShader** shader - ) -{ - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) - { - DX::ThrowIfFailed( - m_d3dDevice->CreateHullShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - }); -} - -void BasicLoader::LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11DomainShader** shader - ) -{ - Platform::Array^ bytecode = m_basicReaderWriter->ReadData(filename); - - DX::ThrowIfFailed( - m_d3dDevice->CreateDomainShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); -} - -task BasicLoader::LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11DomainShader** shader - ) -{ - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) - { - DX::ThrowIfFailed( - m_d3dDevice->CreateDomainShader( - bytecode->Data, - bytecode->Length, - nullptr, - shader - ) - ); - - SetDebugName(*shader, filename); - }); -} - -void BasicLoader::LoadMesh( - _In_ Platform::String^ filename, - _Out_ ID3D11Buffer** vertexBuffer, - _Out_ ID3D11Buffer** indexBuffer, - _Out_opt_ uint32* vertexCount, - _Out_opt_ uint32* indexCount - ) -{ - Platform::Array^ meshData = m_basicReaderWriter->ReadData(filename); - - CreateMesh( - meshData->Data, - vertexBuffer, - indexBuffer, - vertexCount, - indexCount, - filename - ); -} - -task BasicLoader::LoadMeshAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11Buffer** vertexBuffer, - _Out_ ID3D11Buffer** indexBuffer, - _Out_opt_ uint32* vertexCount, - _Out_opt_ uint32* indexCount - ) -{ - return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ meshData) - { - CreateMesh( - meshData->Data, - vertexBuffer, - indexBuffer, - vertexCount, - indexCount, - filename - ); - }); -} diff --git a/DirectXSceneStore/Common/BasicLoader.h b/DirectXSceneStore/Common/BasicLoader.h deleted file mode 100644 index e332dbe..0000000 --- a/DirectXSceneStore/Common/BasicLoader.h +++ /dev/null @@ -1,176 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -#include "BasicReaderWriter.h" - -// A simple loader class that provides support for loading shaders, textures, -// and meshes from files on disk. Provides synchronous and asynchronous methods. -ref class BasicLoader -{ -internal: - BasicLoader( - _In_ ID3D11Device* d3dDevice, - _In_opt_ IWICImagingFactory2* wicFactory = nullptr - ); - - void LoadTexture( - _In_ Platform::String^ filename, - _Out_opt_ ID3D11Texture2D** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView - ); - - concurrency::task LoadTextureAsync( - _In_ Platform::String^ filename, - _Out_opt_ ID3D11Texture2D** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView - ); - - void LoadShader( - _In_ Platform::String^ filename, - _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], - _In_ uint32 layoutDescNumElements, - _Out_ ID3D11VertexShader** shader, - _Out_opt_ ID3D11InputLayout** layout - ); - - concurrency::task LoadShaderAsync( - _In_ Platform::String^ filename, - _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], - _In_ uint32 layoutDescNumElements, - _Out_ ID3D11VertexShader** shader, - _Out_opt_ ID3D11InputLayout** layout - ); - - void LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11PixelShader** shader - ); - - concurrency::task LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11PixelShader** shader - ); - - void LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11ComputeShader** shader - ); - - concurrency::task LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11ComputeShader** shader - ); - - void LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11GeometryShader** shader - ); - - concurrency::task LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11GeometryShader** shader - ); - - void LoadShader( - _In_ Platform::String^ filename, - _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration, - _In_ uint32 numEntries, - _In_reads_opt_(numStrides) const uint32* bufferStrides, - _In_ uint32 numStrides, - _In_ uint32 rasterizedStream, - _Out_ ID3D11GeometryShader** shader - ); - - concurrency::task LoadShaderAsync( - _In_ Platform::String^ filename, - _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration, - _In_ uint32 numEntries, - _In_reads_opt_(numStrides) const uint32* bufferStrides, - _In_ uint32 numStrides, - _In_ uint32 rasterizedStream, - _Out_ ID3D11GeometryShader** shader - ); - - void LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11HullShader** shader - ); - - concurrency::task LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11HullShader** shader - ); - - void LoadShader( - _In_ Platform::String^ filename, - _Out_ ID3D11DomainShader** shader - ); - - concurrency::task LoadShaderAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11DomainShader** shader - ); - - void LoadMesh( - _In_ Platform::String^ filename, - _Out_ ID3D11Buffer** vertexBuffer, - _Out_ ID3D11Buffer** indexBuffer, - _Out_opt_ uint32* vertexCount, - _Out_opt_ uint32* indexCount - ); - - concurrency::task LoadMeshAsync( - _In_ Platform::String^ filename, - _Out_ ID3D11Buffer** vertexBuffer, - _Out_ ID3D11Buffer** indexBuffer, - _Out_opt_ uint32* vertexCount, - _Out_opt_ uint32* indexCount - ); - -private: - Microsoft::WRL::ComPtr m_d3dDevice; - Microsoft::WRL::ComPtr m_wicFactory; - BasicReaderWriter^ m_basicReaderWriter; - - template - inline void SetDebugName( - _In_ DeviceChildType* object, - _In_ Platform::String^ name - ); - - Platform::String^ GetExtension( - _In_ Platform::String^ filename - ); - - void CreateTexture( - _In_ bool decodeAsDDS, - _In_reads_bytes_(dataSize) byte* data, - _In_ uint32 dataSize, - _Out_opt_ ID3D11Texture2D** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView, - _In_opt_ Platform::String^ debugName - ); - - void CreateInputLayout( - _In_reads_bytes_(bytecodeSize) byte* bytecode, - _In_ uint32 bytecodeSize, - _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC* layoutDesc, - _In_ uint32 layoutDescNumElements, - _Out_ ID3D11InputLayout** layout - ); - - void CreateMesh( - _In_ byte* meshData, - _Out_ ID3D11Buffer** vertexBuffer, - _Out_ ID3D11Buffer** indexBuffer, - _Out_opt_ uint32* vertexCount, - _Out_opt_ uint32* indexCount, - _In_opt_ Platform::String^ debugName - ); -}; diff --git a/DirectXSceneStore/Common/BasicMath.h b/DirectXSceneStore/Common/BasicMath.h deleted file mode 100644 index 4cf02d7..0000000 --- a/DirectXSceneStore/Common/BasicMath.h +++ /dev/null @@ -1,518 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -#define _USE_MATH_DEFINES -#include - -// This header defines math and matrix helper functions and structures used -// by DirectX SDK samples. - -// Common Constants - -#define PI_F 3.1415927f - -// Template Vector & Matrix Classes - -template struct Vector2 -{ - union - { - struct - { - T x; - T y; - }; - struct - { - T r; - T g; - }; - struct - { - T u; - T v; - }; - }; - - T& operator[](unsigned int index) - { - return static_cast(this)[index]; - } - - Vector2(T _x = 0, T _y = 0) : x(_x), y(_y) { } -}; - -template struct Vector3 -{ - union - { - struct - { - T x; - T y; - T z; - }; - struct - { - T r; - T g; - T b; - }; - struct - { - T u; - T v; - T w; - }; - }; - - T& operator[](unsigned int index) - { - return static_cast(this)[index]; - } - - Vector3(T _x = 0, T _y = 0, T _z = 0) : x(_x), y(_y), z(_z) { } -}; - -template struct Vector4 -{ - union - { - struct - { - T x; - T y; - T z; - T w; - }; - struct - { - T r; - T g; - T b; - T a; - }; - }; - - T& operator[](unsigned int index) - { - return static_cast(this)[index]; - } - - Vector4(T _x = 0, T _y = 0, T _z = 0, T _w = 0) : x(_x), y(_y), z(_z), w(_w) { } -}; - -template struct Matrix4x4 -{ - union - { - struct - { - T _11; T _12; T _13; T _14; - T _21; T _22; T _23; T _24; - T _31; T _32; T _33; T _34; - T _41; T _42; T _43; T _44; - }; - struct - { - T _m00; T _m01; T _m02; T _m03; - T _m10; T _m11; T _m12; T _m13; - T _m20; T _m21; T _m22; T _m23; - T _m30; T _m31; T _m32; T _m33; - }; - }; - - Matrix4x4(T value = 0) - { - _11 = _12 = _13 = _14 = value; - _21 = _22 = _23 = _24 = value; - _31 = _32 = _33 = _34 = value; - _41 = _42 = _43 = _44 = value; - } - - Matrix4x4( - T i11, T i12, T i13, T i14, - T i21, T i22, T i23, T i24, - T i31, T i32, T i33, T i34, - T i41, T i42, T i43, T i44 - ) - { - _11 = i11; _12 = i12; _13 = i13; _14 = i14; - _21 = i21; _22 = i22; _23 = i23; _24 = i24; - _31 = i31; _32 = i32; _33 = i33; _34 = i34; - _41 = i41; _42 = i42; _43 = i43; _44 = i44; - } - - T* operator[](unsigned int index) - { - return &(reinterpret_cast(this)[index*4]); - } -}; - -// Template Vector Operations - -template -T dot(Vector2 a, Vector2 b) -{ - return a.x * b.x + a.y * b.y; -} - -template -T dot(Vector3 a, Vector3 b) -{ - return a.x * b.x + a.y * b.y + a.z * b.z; -} - -template -T dot(Vector4 a, Vector4 b) -{ - return a.x * b.x + a.y * b.y + a.z * b.z + a.w + b.w; -} - -template -T length(Vector2 a) -{ - return sqrt(a.x * a.x + a.y * a.y); -} - -template -T length(Vector3 a) -{ - return sqrt(a.x * a.x + a.y * a.y + a.z * a.z); -} - -template -T length(Vector4 a) -{ - return sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); -} - -template -Vector3 cross(Vector3 a, Vector3 b) -{ - return Vector3((a.y*b.z)-(a.z*b.y), (a.z*b.x)-(a.x*b.z), (a.x*b.y)-(a.y*b.x)); -} - -template -Vector2 normalize(Vector2 a) -{ - T len = length(a); - return Vector2(a.x / len, a.y / len); -} - -template -Vector3 normalize(Vector3 a) -{ - T len = length(a); - return Vector3(a.x / len, a.y / len, a.z / len); -} - -template -Vector4 normalize(Vector4 a) -{ - T len = length(a); - return Vector4(a.x / len, a.y / len, a.z / len, a.w / len); -} - -// Template Vector Operators - -template -Vector2 operator-(Vector2 a, Vector2 b) -{ - return Vector2(a.x - b.x, a.y - b.y); -} - -template -Vector2 operator-(Vector2 a) -{ - return Vector2(-a.x, -a.y); -} - -template -Vector3 operator-(Vector3 a, Vector3 b) -{ - return Vector3(a.x - b.x, a.y - b.y, a.z - b.z); -} - -template -Vector3 operator-(Vector3 a) -{ - return Vector3(-a.x, -a.y, -a.z); -} - -template -Vector4 operator-(Vector4 a, Vector4 b) -{ - return Vector4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); -} - -template -Vector4 operator-(Vector4 a) -{ - return Vector4(-a.x, -a.y, -a.z, -a.w); -} - -template -Vector2 operator+(Vector2 a, Vector2 b) -{ - return Vector2(a.x + b.x, a.y + b.y); -} - -template -Vector3 operator+(Vector3 a, Vector3 b) -{ - return Vector3(a.x + b.x, a.y + b.y, a.z + b.z); -} - -template -Vector4 operator+(Vector4 a, Vector4 b) -{ - return Vector4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); -} - -template -Vector2 operator*(Vector2 a, T s) -{ - return Vector2(a.x * s, a.y * s); -} - -template -Vector2 operator*(T s, Vector2 a) -{ - return a * s; -} - -template -Vector2 operator*(Vector2 a, Vector2 b) -{ - return Vector2(a.x * b.x, a.y * b.y); -} - -template -Vector2 operator/(Vector2 a, T s) -{ - return Vector2(a.x / s, a.y / s); -} - -template -Vector3 operator*(Vector3 a, T s) -{ - return Vector3(a.x * s, a.y * s, a.z * s); -} - -template -Vector3 operator*(T s, Vector3 a) -{ - return a * s; -} - -template -Vector3 operator*(Vector3 a, Vector3 b) -{ - return Vector3(a.x * b.x, a.y * b.y, a.z * b.z); -} - -template -Vector3 operator/(Vector3 a, T s) -{ - return Vector3(a.x / s, a.y / s, a.z / s); -} - -template -Vector4 operator*(Vector4 a, T s) -{ - return Vector4(a.x * s, a.y * s, a.z * s, a.w * s); -} - -template -Vector4 operator*(T s, Vector4 a) -{ - return a * s; -} - -template -Vector4 operator*(Vector4 a, Vector4 b) -{ - return Vector4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); -} - -template -Vector4 operator/(Vector4 a, T s) -{ - return Vector4(a.x / s, a.y / s, a.z / s, a.w / s); -} - - - -// Template Matrix Operations - -template -Matrix4x4 transpose(Matrix4x4 m) -{ - return Matrix4x4( - m._11, m._21, m._31, m._41, - m_.12, m._22, m._32, m._42, - m._13, m._23, m._33, m._43, - m._14, m._24, m._34, m._44 - ); -} - -template -Matrix4x4 mul(Matrix4x4 m1, Matrix4x4 m2) -{ - Matrix4x4 mOut; - - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < 4; j++) - { - for (int k = 0; k < 4; k++) - { - mOut[i][j] += m1[i][k] * m2[k][j]; - } - } - } - - return mOut; -} - -// Common HLSL-compatible vector typedefs - -typedef unsigned int uint; - -typedef Vector2 float2; -typedef Vector3 float3; -typedef Vector4 float4; - -typedef Matrix4x4 float4x4; - -// Standard Matrix Intializers - -inline float4x4 identity() -{ - float4x4 mOut; - - mOut._11 = 1.0f; mOut._12 = 0.0f; mOut._13 = 0.0f; mOut._14 = 0.0f; - mOut._21 = 0.0f; mOut._22 = 1.0f; mOut._23 = 0.0f; mOut._24 = 0.0f; - mOut._31 = 0.0f; mOut._32 = 0.0f; mOut._33 = 1.0f; mOut._34 = 0.0f; - mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f; - - return mOut; -} - -inline float4x4 translation(float x, float y, float z) -{ - float4x4 mOut; - - mOut._11 = 1.0f; mOut._12 = 0.0f; mOut._13 = 0.0f; mOut._14 = x; - mOut._21 = 0.0f; mOut._22 = 1.0f; mOut._23 = 0.0f; mOut._24 = y; - mOut._31 = 0.0f; mOut._32 = 0.0f; mOut._33 = 1.0f; mOut._34 = z; - mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f; - - return mOut; -} - -inline float4x4 scale(float x, float y, float z) -{ - float4x4 mOut; - - mOut._11 = x; mOut._12 = 0.0f; mOut._13 = 0.0f; mOut._14 = 0.0f; - mOut._21 = 0.0f; mOut._22 = y; mOut._23 = 0.0f; mOut._24 = 0.0f; - mOut._31 = 0.0f; mOut._32 = 0.0f; mOut._33 = z; mOut._34 = 0.0f; - mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f; - - return mOut; -} - -inline float4x4 rotationX(float degreeX) -{ - float angleInRadians = degreeX * (PI_F / 180.0f); - - float sinAngle = sinf(angleInRadians); - float cosAngle = cosf(angleInRadians); - - float4x4 mOut; - - mOut._11 = 1.0f; mOut._12 = 0.0f; mOut._13 = 0.0f; mOut._14 = 0.0f; - mOut._21 = 0.0f; mOut._22 = cosAngle; mOut._23 = -sinAngle; mOut._24 = 0.0f; - mOut._31 = 0.0f; mOut._32 = sinAngle; mOut._33 = cosAngle; mOut._34 = 0.0f; - mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f; - - return mOut; -} - -inline float4x4 rotationY(float degreeY) -{ - float angleInRadians = degreeY * (PI_F / 180.0f); - - float sinAngle = sinf(angleInRadians); - float cosAngle = cosf(angleInRadians); - - float4x4 mOut; - - mOut._11 = cosAngle; mOut._12 = 0.0f; mOut._13 = sinAngle; mOut._14 = 0.0f; - mOut._21 = 0.0f; mOut._22 = 1.0f; mOut._23 = 0.0f; mOut._24 = 0.0f; - mOut._31 = -sinAngle; mOut._32 = 0.0f; mOut._33 = cosAngle; mOut._34 = 0.0f; - mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f; - - return mOut; -} - -inline float4x4 rotationZ(float degreeZ) -{ - float angleInRadians = degreeZ * (PI_F / 180.0f); - - float sinAngle = sinf(angleInRadians); - float cosAngle = cosf(angleInRadians); - - float4x4 mOut; - - mOut._11 = cosAngle; mOut._12 = -sinAngle; mOut._13 = 0.0f; mOut._14 = 0.0f; - mOut._21 = sinAngle; mOut._22 = cosAngle; mOut._23 = 0.0f; mOut._24 = 0.0f; - mOut._31 = 0.0f; mOut._32 = 0.0f; mOut._33 = 1.0f; mOut._34 = 0.0f; - mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f; - - return mOut; -} - -// 3D Rotation matrix for an arbitrary axis specified by x, y and z -inline float4x4 rotationArbitrary(float3 axis, float degree) -{ - axis = normalize(axis); - - float angleInRadians = degree * (PI_F / 180.0f); - - float sinAngle = sinf(angleInRadians); - float cosAngle = cosf(angleInRadians); - float oneMinusCosAngle = 1 - cosAngle; - - float4x4 mOut; - - mOut._11 = 1.0f + oneMinusCosAngle * (axis.x * axis.x - 1.0f); - mOut._12 = axis.z * sinAngle + oneMinusCosAngle * axis.x * axis.y; - mOut._13 = -axis.y * sinAngle + oneMinusCosAngle * axis.x * axis.z; - mOut._41 = 0.0f; - - mOut._21 = -axis.z * sinAngle + oneMinusCosAngle * axis.y * axis.x; - mOut._22 = 1.0f + oneMinusCosAngle * (axis.y * axis.y - 1.0f); - mOut._23 = axis.x * sinAngle + oneMinusCosAngle * axis.y * axis.z; - mOut._24 = 0.0f; - - mOut._31 = axis.y * sinAngle + oneMinusCosAngle * axis.z * axis.x; - mOut._32 = -axis.x * sinAngle + oneMinusCosAngle * axis.z * axis.y; - mOut._33 = 1.0f + oneMinusCosAngle * (axis.z * axis.z - 1.0f); - mOut._34 = 0.0f; - - mOut._41 = 0.0f; - mOut._42 = 0.0f; - mOut._43 = 0.0f; - mOut._44 = 1.0f; - - return mOut; -} diff --git a/DirectXSceneStore/Common/BasicReaderWriter.cpp b/DirectXSceneStore/Common/BasicReaderWriter.cpp deleted file mode 100644 index def22cb..0000000 --- a/DirectXSceneStore/Common/BasicReaderWriter.cpp +++ /dev/null @@ -1,167 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "BasicReaderWriter.h" - -using namespace Microsoft::WRL; -using namespace Windows::Storage; -using namespace Windows::Storage::FileProperties; -using namespace Windows::Storage::Streams; -using namespace Windows::Foundation; -using namespace Windows::ApplicationModel; -using namespace concurrency; - -BasicReaderWriter::BasicReaderWriter() -{ - m_location = Package::Current->InstalledLocation; -} - -BasicReaderWriter::BasicReaderWriter( - _In_ Windows::Storage::StorageFolder^ folder - ) -{ - m_location = folder; - Platform::String^ path = m_location->Path; - if (path->Length() == 0) - { - // Applications are not permitted to access certain - // folders, such as the Documents folder, using this - // code path. In such cases, the Path property for - // the folder will be an empty string. - throw ref new Platform::FailureException(); - } -} - -Platform::Array^ BasicReaderWriter::ReadData( - _In_ Platform::String^ filename - ) -{ - CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0}; - extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); - extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; - extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN; - extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; - extendedParams.lpSecurityAttributes = nullptr; - extendedParams.hTemplateFile = nullptr; - - Wrappers::FileHandle file( - CreateFile2( - filename->Data(), - GENERIC_READ, - FILE_SHARE_READ, - OPEN_EXISTING, - &extendedParams - ) - ); - if (file.Get() == INVALID_HANDLE_VALUE) - { - throw ref new Platform::FailureException(); - } - - FILE_STANDARD_INFO fileInfo = {0}; - if (!GetFileInformationByHandleEx( - file.Get(), - FileStandardInfo, - &fileInfo, - sizeof(fileInfo) - )) - { - throw ref new Platform::FailureException(); - } - - if (fileInfo.EndOfFile.HighPart != 0) - { - throw ref new Platform::OutOfMemoryException(); - } - - Platform::Array^ fileData = ref new Platform::Array(fileInfo.EndOfFile.LowPart); - - if (!ReadFile( - file.Get(), - fileData->Data, - fileData->Length, - nullptr, - nullptr - )) - { - throw ref new Platform::FailureException(); - } - - return fileData; -} - -task^> BasicReaderWriter::ReadDataAsync( - _In_ Platform::String^ filename - ) -{ - return task(m_location->GetFileAsync(filename)).then([=](StorageFile^ file) - { - return FileIO::ReadBufferAsync(file); - }).then([=](IBuffer^ buffer) - { - auto fileData = ref new Platform::Array(buffer->Length); - DataReader::FromBuffer(buffer)->ReadBytes(fileData); - return fileData; - }); -} - -uint32 BasicReaderWriter::WriteData( - _In_ Platform::String^ filename, - _In_ const Platform::Array^ fileData - ) -{ - CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0}; - extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); - extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; - extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN; - extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; - extendedParams.lpSecurityAttributes = nullptr; - extendedParams.hTemplateFile = nullptr; - - Wrappers::FileHandle file( - CreateFile2( - filename->Data(), - GENERIC_WRITE, - 0, - CREATE_ALWAYS, - &extendedParams - ) - ); - if (file.Get() == INVALID_HANDLE_VALUE) - { - throw ref new Platform::FailureException(); - } - - DWORD numBytesWritten; - if ( - !WriteFile( - file.Get(), - fileData->Data, - fileData->Length, - &numBytesWritten, - nullptr - ) || - numBytesWritten != fileData->Length - ) - { - throw ref new Platform::FailureException(); - } - - return numBytesWritten; -} - -task BasicReaderWriter::WriteDataAsync( - _In_ Platform::String^ filename, - _In_ const Platform::Array^ fileData - ) -{ - return task(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file) - { - FileIO::WriteBytesAsync(file, fileData); - }); -} diff --git a/DirectXSceneStore/Common/BasicReaderWriter.h b/DirectXSceneStore/Common/BasicReaderWriter.h deleted file mode 100644 index a911b3e..0000000 --- a/DirectXSceneStore/Common/BasicReaderWriter.h +++ /dev/null @@ -1,42 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -#include - -// A simple reader/writer class that provides support for reading and writing -// files on disk. Provides synchronous and asynchronous methods. -ref class BasicReaderWriter -{ -private: - Windows::Storage::StorageFolder^ m_location; - -internal: - BasicReaderWriter(); - BasicReaderWriter( - _In_ Windows::Storage::StorageFolder^ folder - ); - - Platform::Array^ ReadData( - _In_ Platform::String^ filename - ); - - concurrency::task^> ReadDataAsync( - _In_ Platform::String^ filename - ); - - uint32 WriteData( - _In_ Platform::String^ filename, - _In_ const Platform::Array^ fileData - ); - - concurrency::task WriteDataAsync( - _In_ Platform::String^ filename, - _In_ const Platform::Array^ fileData - ); -}; diff --git a/DirectXSceneStore/Common/BasicShapes.h b/DirectXSceneStore/Common/BasicShapes.h deleted file mode 100644 index 3abeab1..0000000 --- a/DirectXSceneStore/Common/BasicShapes.h +++ /dev/null @@ -1,88 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -#include "BasicMath.h" - -// Defines the vertex format for the shapes generated in the functions below. -struct BasicVertex -{ - float3 pos; // position - float3 norm; // surface normal vector - float2 tex; // texture coordinate -}; - -// Defines the vertex format for all shapes generated in the functions below. -struct TangentVertex -{ - float3 pos; // position - float2 tex; // texture coordinate - float3 uTan; // texture coordinate u-tangent vector - float3 vTan; // texture coordinate v-tangent vector -}; - -// A helper class that provides convenient functions for creating common -// geometrical shapes used by DirectX SDK samples. -ref class BasicShapes -{ -internal: - BasicShapes(ID3D11Device *d3dDevice); - void CreateCube( - _Out_ ID3D11Buffer **vertexBuffer, - _Out_ ID3D11Buffer **indexBuffer, - _Out_opt_ unsigned int *vertexCount, - _Out_opt_ unsigned int *indexCount - ); - void CreateBox( - float3 radii, - _Out_ ID3D11Buffer **vertexBuffer, - _Out_ ID3D11Buffer **indexBuffer, - _Out_opt_ unsigned int *vertexCount, - _Out_opt_ unsigned int *indexCount - ); - void CreateSphere( - _Out_ ID3D11Buffer **vertexBuffer, - _Out_ ID3D11Buffer **indexBuffer, - _Out_opt_ unsigned int *vertexCount, - _Out_opt_ unsigned int *indexCount - ); - void CreateTangentSphere( - _Out_ ID3D11Buffer **vertexBuffer, - _Out_ ID3D11Buffer **indexBuffer, - _Out_opt_ unsigned int *vertexCount, - _Out_opt_ unsigned int *indexCount - ); - void CreateReferenceAxis( - _Out_ ID3D11Buffer **vertexBuffer, - _Out_ ID3D11Buffer **indexBuffer, - _Out_opt_ unsigned int *vertexCount, - _Out_opt_ unsigned int *indexCount - ); - -private: - Microsoft::WRL::ComPtr m_d3dDevice; - - void CreateVertexBuffer( - _In_ unsigned int numVertices, - _In_ BasicVertex *vertexData, - _Out_ ID3D11Buffer **vertexBuffer - ); - - void CreateIndexBuffer( - _In_ unsigned int numIndices, - _In_ unsigned short *indexData, - _Out_ ID3D11Buffer **indexBuffer - ); - - void CreateTangentVertexBuffer( - _In_ unsigned int numVertices, - _In_ TangentVertex *vertexData, - _Out_ ID3D11Buffer **vertexBuffer - ); - -}; diff --git a/DirectXSceneStore/Common/DDSTextureLoader.cpp b/DirectXSceneStore/Common/DDSTextureLoader.cpp deleted file mode 100644 index 7897a26..0000000 --- a/DirectXSceneStore/Common/DDSTextureLoader.cpp +++ /dev/null @@ -1,1282 +0,0 @@ -//-------------------------------------------------------------------------------------- -// File: DDSTextureLoader.cpp -// -// Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it -// -// Note these functions are useful as a light-weight runtime loader for DDS files. For -// a full-featured DDS file reader, writer, and texture processing pipeline see -// the 'Texconv' sample and the 'DirectXTex' library. -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// http://go.microsoft.com/fwlink/?LinkId=248926 -// http://go.microsoft.com/fwlink/?LinkId=248929 -//-------------------------------------------------------------------------------------- - -#include "pch.h" -#include -#include -#include -#include -#include "DDSTextureLoader.h" -#include "DirectXSample.h" - -using namespace Microsoft::WRL; - -//-------------------------------------------------------------------------------------- -// Macros -//-------------------------------------------------------------------------------------- -#ifndef MAKEFOURCC - #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ - ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) | \ - ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24)) -#endif /* defined(MAKEFOURCC) */ - -//-------------------------------------------------------------------------------------- -// DDS file structure definitions -// -// See DDS.h in the 'Texconv' sample and the 'DirectXTex' library -//-------------------------------------------------------------------------------------- -#pragma pack(push, 1) - -#define DDS_MAGIC 0x20534444 // "DDS " - -struct DDS_PIXELFORMAT -{ - uint32 size; - uint32 flags; - uint32 fourCC; - uint32 RGBBitCount; - uint32 RBitMask; - uint32 GBitMask; - uint32 BBitMask; - uint32 ABitMask; -}; - -#define DDS_FOURCC 0x00000004 // DDPF_FOURCC -#define DDS_RGB 0x00000040 // DDPF_RGB -#define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS -#define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE -#define DDS_LUMINANCEA 0x00020001 // DDPF_LUMINANCE | DDPF_ALPHAPIXELS -#define DDS_ALPHA 0x00000002 // DDPF_ALPHA -#define DDS_PAL8 0x00000020 // DDPF_PALETTEINDEXED8 - -#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT -#define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT -#define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH -#define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH -#define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE - -#define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT -#define DDS_WIDTH 0x00000004 // DDSD_WIDTH - -#define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE -#define DDS_SURFACE_FLAGS_MIPMAP 0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP -#define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX - -#define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX -#define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX -#define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY -#define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY -#define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ -#define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ - -#define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\ - DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\ - DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ) - -#define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP - -#define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME - -enum DDS_MISC_FLAGS2 -{ - DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L, -}; - -enum DDS_ALPHA_MODE -{ - DDS_ALPHA_MODE_UNKNOWN = 0, - DDS_ALPHA_MODE_STRAIGHT = 1, - DDS_ALPHA_MODE_PREMULTIPLIED = 2, - DDS_ALPHA_MODE_OPAQUE = 3, - DDS_ALPHA_MODE_CUSTOM = 4, -}; - -typedef struct -{ - uint32 size; - uint32 flags; - uint32 height; - uint32 width; - uint32 pitchOrLinearSize; - uint32 depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags - uint32 mipMapCount; - uint32 reserved1[11]; - DDS_PIXELFORMAT ddspf; - uint32 caps; - uint32 caps2; - uint32 caps3; - uint32 caps4; - uint32 reserved2; -} DDS_HEADER; - -typedef struct -{ - DXGI_FORMAT dxgiFormat; - uint32 resourceDimension; - uint32 miscFlag; // see D3D11_RESOURCE_MISC_FLAG - uint32 arraySize; - uint32 miscFlags2; -} DDS_HEADER_DXT10; - -#pragma pack(pop) - -//-------------------------------------------------------------------------------------- -// Return the BPP for a particular format -//-------------------------------------------------------------------------------------- -static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt) -{ - switch (fmt) - { - case DXGI_FORMAT_R32G32B32A32_TYPELESS: - case DXGI_FORMAT_R32G32B32A32_FLOAT: - case DXGI_FORMAT_R32G32B32A32_UINT: - case DXGI_FORMAT_R32G32B32A32_SINT: - return 128; - - case DXGI_FORMAT_R32G32B32_TYPELESS: - case DXGI_FORMAT_R32G32B32_FLOAT: - case DXGI_FORMAT_R32G32B32_UINT: - case DXGI_FORMAT_R32G32B32_SINT: - return 96; - - case DXGI_FORMAT_R16G16B16A16_TYPELESS: - case DXGI_FORMAT_R16G16B16A16_FLOAT: - case DXGI_FORMAT_R16G16B16A16_UNORM: - case DXGI_FORMAT_R16G16B16A16_UINT: - case DXGI_FORMAT_R16G16B16A16_SNORM: - case DXGI_FORMAT_R16G16B16A16_SINT: - case DXGI_FORMAT_R32G32_TYPELESS: - case DXGI_FORMAT_R32G32_FLOAT: - case DXGI_FORMAT_R32G32_UINT: - case DXGI_FORMAT_R32G32_SINT: - case DXGI_FORMAT_R32G8X24_TYPELESS: - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: - return 64; - - case DXGI_FORMAT_R10G10B10A2_TYPELESS: - case DXGI_FORMAT_R10G10B10A2_UNORM: - case DXGI_FORMAT_R10G10B10A2_UINT: - case DXGI_FORMAT_R11G11B10_FLOAT: - case DXGI_FORMAT_R8G8B8A8_TYPELESS: - case DXGI_FORMAT_R8G8B8A8_UNORM: - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - case DXGI_FORMAT_R8G8B8A8_UINT: - case DXGI_FORMAT_R8G8B8A8_SNORM: - case DXGI_FORMAT_R8G8B8A8_SINT: - case DXGI_FORMAT_R16G16_TYPELESS: - case DXGI_FORMAT_R16G16_FLOAT: - case DXGI_FORMAT_R16G16_UNORM: - case DXGI_FORMAT_R16G16_UINT: - case DXGI_FORMAT_R16G16_SNORM: - case DXGI_FORMAT_R16G16_SINT: - case DXGI_FORMAT_R32_TYPELESS: - case DXGI_FORMAT_D32_FLOAT: - case DXGI_FORMAT_R32_FLOAT: - case DXGI_FORMAT_R32_UINT: - case DXGI_FORMAT_R32_SINT: - case DXGI_FORMAT_R24G8_TYPELESS: - case DXGI_FORMAT_D24_UNORM_S8_UINT: - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: - case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: - case DXGI_FORMAT_R8G8_B8G8_UNORM: - case DXGI_FORMAT_G8R8_G8B8_UNORM: - case DXGI_FORMAT_B8G8R8A8_UNORM: - case DXGI_FORMAT_B8G8R8X8_UNORM: - case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: - case DXGI_FORMAT_B8G8R8A8_TYPELESS: - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - case DXGI_FORMAT_B8G8R8X8_TYPELESS: - case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: - return 32; - - case DXGI_FORMAT_R8G8_TYPELESS: - case DXGI_FORMAT_R8G8_UNORM: - case DXGI_FORMAT_R8G8_UINT: - case DXGI_FORMAT_R8G8_SNORM: - case DXGI_FORMAT_R8G8_SINT: - case DXGI_FORMAT_R16_TYPELESS: - case DXGI_FORMAT_R16_FLOAT: - case DXGI_FORMAT_D16_UNORM: - case DXGI_FORMAT_R16_UNORM: - case DXGI_FORMAT_R16_UINT: - case DXGI_FORMAT_R16_SNORM: - case DXGI_FORMAT_R16_SINT: - case DXGI_FORMAT_B5G6R5_UNORM: - case DXGI_FORMAT_B5G5R5A1_UNORM: - case DXGI_FORMAT_B4G4R4A4_UNORM: - return 16; - - case DXGI_FORMAT_R8_TYPELESS: - case DXGI_FORMAT_R8_UNORM: - case DXGI_FORMAT_R8_UINT: - case DXGI_FORMAT_R8_SNORM: - case DXGI_FORMAT_R8_SINT: - case DXGI_FORMAT_A8_UNORM: - return 8; - - case DXGI_FORMAT_R1_UNORM: - return 1; - - case DXGI_FORMAT_BC1_TYPELESS: - case DXGI_FORMAT_BC1_UNORM: - case DXGI_FORMAT_BC1_UNORM_SRGB: - case DXGI_FORMAT_BC4_TYPELESS: - case DXGI_FORMAT_BC4_UNORM: - case DXGI_FORMAT_BC4_SNORM: - return 4; - - case DXGI_FORMAT_BC2_TYPELESS: - case DXGI_FORMAT_BC2_UNORM: - case DXGI_FORMAT_BC2_UNORM_SRGB: - case DXGI_FORMAT_BC3_TYPELESS: - case DXGI_FORMAT_BC3_UNORM: - case DXGI_FORMAT_BC3_UNORM_SRGB: - case DXGI_FORMAT_BC5_TYPELESS: - case DXGI_FORMAT_BC5_UNORM: - case DXGI_FORMAT_BC5_SNORM: - case DXGI_FORMAT_BC6H_TYPELESS: - case DXGI_FORMAT_BC6H_UF16: - case DXGI_FORMAT_BC6H_SF16: - case DXGI_FORMAT_BC7_TYPELESS: - case DXGI_FORMAT_BC7_UNORM: - case DXGI_FORMAT_BC7_UNORM_SRGB: - return 8; - - default: - return 0; - } -} - - -//-------------------------------------------------------------------------------------- -// Get surface information for a particular format -//-------------------------------------------------------------------------------------- -static void GetSurfaceInfo( - _In_ size_t width, - _In_ size_t height, - _In_ DXGI_FORMAT fmt, - _Out_opt_ size_t* outNumBytes, - _Out_opt_ size_t* outRowBytes, - _Out_opt_ size_t* outNumRows - ) -{ - size_t numBytes = 0; - size_t rowBytes = 0; - size_t numRows = 0; - - bool bc = false; - bool packed = false; - size_t bcnumBytesPerBlock = 0; - switch (fmt) - { - case DXGI_FORMAT_BC1_TYPELESS: - case DXGI_FORMAT_BC1_UNORM: - case DXGI_FORMAT_BC1_UNORM_SRGB: - case DXGI_FORMAT_BC4_TYPELESS: - case DXGI_FORMAT_BC4_UNORM: - case DXGI_FORMAT_BC4_SNORM: - bc = true; - bcnumBytesPerBlock = 8; - break; - - case DXGI_FORMAT_BC2_TYPELESS: - case DXGI_FORMAT_BC2_UNORM: - case DXGI_FORMAT_BC2_UNORM_SRGB: - case DXGI_FORMAT_BC3_TYPELESS: - case DXGI_FORMAT_BC3_UNORM: - case DXGI_FORMAT_BC3_UNORM_SRGB: - case DXGI_FORMAT_BC5_TYPELESS: - case DXGI_FORMAT_BC5_UNORM: - case DXGI_FORMAT_BC5_SNORM: - case DXGI_FORMAT_BC6H_TYPELESS: - case DXGI_FORMAT_BC6H_UF16: - case DXGI_FORMAT_BC6H_SF16: - case DXGI_FORMAT_BC7_TYPELESS: - case DXGI_FORMAT_BC7_UNORM: - case DXGI_FORMAT_BC7_UNORM_SRGB: - bc = true; - bcnumBytesPerBlock = 16; - break; - - case DXGI_FORMAT_R8G8_B8G8_UNORM: - case DXGI_FORMAT_G8R8_G8B8_UNORM: - packed = true; - break; - } - - if (bc) - { - size_t numBlocksWide = 0; - if (width > 0) - { - numBlocksWide = std::max(1, (width + 3) / 4); - } - size_t numBlocksHigh = 0; - if (height > 0) - { - numBlocksHigh = std::max(1, (height + 3) / 4); - } - rowBytes = numBlocksWide * bcnumBytesPerBlock; - numRows = numBlocksHigh; - } - else if (packed) - { - rowBytes = ((width + 1) >> 1) * 4; - numRows = height; - } - else - { - size_t bpp = BitsPerPixel(fmt); - rowBytes = (width * bpp + 7) / 8; // round up to nearest byte - numRows = height; - } - - numBytes = rowBytes * numRows; - if (outNumBytes) - { - *outNumBytes = numBytes; - } - if (outRowBytes) - { - *outRowBytes = rowBytes; - } - if (outNumRows) - { - *outNumRows = numRows; - } -} - - -//-------------------------------------------------------------------------------------- -#define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a) - -static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf) -{ - if (ddpf.flags & DDS_RGB) - { - // Note that sRGB formats are written using the "DX10" extended header - - switch (ddpf.RGBBitCount) - { - case 32: - if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) - { - return DXGI_FORMAT_R8G8B8A8_UNORM; - } - - if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) - { - return DXGI_FORMAT_B8G8R8A8_UNORM; - } - - if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000)) - { - return DXGI_FORMAT_B8G8R8X8_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8 - - // Note that many common DDS reader/writers (including D3DX) swap the - // the RED/BLUE masks for 10:10:10:2 formats. We assumme - // below that the 'backwards' header mask is being used since it is most - // likely written by D3DX. The more robust solution is to use the 'DX10' - // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly - - // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data - if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000)) - { - return DXGI_FORMAT_R10G10B10A2_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10 - - if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) - { - return DXGI_FORMAT_R16G16_UNORM; - } - - if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000)) - { - // Only 32-bit color channel format in D3D9 was R32F - return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114 - } - break; - - case 24: - // No 24bpp DXGI formats aka D3DFMT_R8G8B8 - break; - - case 16: - if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000)) - { - return DXGI_FORMAT_B5G5R5A1_UNORM; - } - if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000)) - { - return DXGI_FORMAT_B5G6R5_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5 - if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) - { - return DXGI_FORMAT_B4G4R4A4_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4 - - // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc. - break; - } - } - else if (ddpf.flags & DDS_LUMINANCE) - { - if (8 == ddpf.RGBBitCount) - { - if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000)) - { - return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension - } - - // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4 - } - - if (16 == ddpf.RGBBitCount) - { - if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000)) - { - return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension - } - if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) - { - return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension - } - } - } - else if (ddpf.flags & DDS_ALPHA) - { - if (8 == ddpf.RGBBitCount) - { - return DXGI_FORMAT_A8_UNORM; - } - } - else if (ddpf.flags & DDS_FOURCC) - { - if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC) - { - return DXGI_FORMAT_BC1_UNORM; - } - if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC) - { - return DXGI_FORMAT_BC2_UNORM; - } - if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC) - { - return DXGI_FORMAT_BC3_UNORM; - } - - // While pre-mulitplied alpha isn't directly supported by the DXGI formats, - // they are basically the same as these BC formats so they can be mapped - if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC) - { - return DXGI_FORMAT_BC2_UNORM; - } - if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC) - { - return DXGI_FORMAT_BC3_UNORM; - } - - if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC) - { - return DXGI_FORMAT_BC4_UNORM; - } - if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC) - { - return DXGI_FORMAT_BC4_UNORM; - } - if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC) - { - return DXGI_FORMAT_BC4_SNORM; - } - - if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC) - { - return DXGI_FORMAT_BC5_UNORM; - } - if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC) - { - return DXGI_FORMAT_BC5_UNORM; - } - if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC) - { - return DXGI_FORMAT_BC5_SNORM; - } - - // BC6H and BC7 are written using the "DX10" extended header - - if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC) - { - return DXGI_FORMAT_R8G8_B8G8_UNORM; - } - if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC) - { - return DXGI_FORMAT_G8R8_G8B8_UNORM; - } - - // Check for D3DFORMAT enums being set here - switch (ddpf.fourCC) - { - case 36: // D3DFMT_A16B16G16R16 - return DXGI_FORMAT_R16G16B16A16_UNORM; - - case 110: // D3DFMT_Q16W16V16U16 - return DXGI_FORMAT_R16G16B16A16_SNORM; - - case 111: // D3DFMT_R16F - return DXGI_FORMAT_R16_FLOAT; - - case 112: // D3DFMT_G16R16F - return DXGI_FORMAT_R16G16_FLOAT; - - case 113: // D3DFMT_A16B16G16R16F - return DXGI_FORMAT_R16G16B16A16_FLOAT; - - case 114: // D3DFMT_R32F - return DXGI_FORMAT_R32_FLOAT; - - case 115: // D3DFMT_G32R32F - return DXGI_FORMAT_R32G32_FLOAT; - - case 116: // D3DFMT_A32B32G32R32F - return DXGI_FORMAT_R32G32B32A32_FLOAT; - } - } - - return DXGI_FORMAT_UNKNOWN; -} - - -//-------------------------------------------------------------------------------------- -static DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format) -{ - switch (format) - { - case DXGI_FORMAT_R8G8B8A8_UNORM: - return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - - case DXGI_FORMAT_BC1_UNORM: - return DXGI_FORMAT_BC1_UNORM_SRGB; - - case DXGI_FORMAT_BC2_UNORM: - return DXGI_FORMAT_BC2_UNORM_SRGB; - - case DXGI_FORMAT_BC3_UNORM: - return DXGI_FORMAT_BC3_UNORM_SRGB; - - case DXGI_FORMAT_B8G8R8A8_UNORM: - return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; - - case DXGI_FORMAT_B8G8R8X8_UNORM: - return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; - - case DXGI_FORMAT_BC7_UNORM: - return DXGI_FORMAT_BC7_UNORM_SRGB; - - default: - return format; - } -} - - -//-------------------------------------------------------------------------------------- -static void FillInitData( - _In_ size_t width, - _In_ size_t height, - _In_ size_t depth, - _In_ size_t mipCount, - _In_ size_t arraySize, - _In_ DXGI_FORMAT format, - _In_ size_t maxsize, - _In_ size_t bitSize, - _In_reads_bytes_(bitSize) const byte* bitData, - _Out_ size_t& twidth, - _Out_ size_t& theight, - _Out_ size_t& tdepth, - _Out_ size_t& skipMip, - _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData - ) -{ - if (!bitData || !initData) - { - throw ref new Platform::InvalidArgumentException(); - } - - skipMip = 0; - twidth = 0; - theight = 0; - tdepth = 0; - - size_t NumBytes = 0; - size_t RowBytes = 0; - size_t NumRows = 0; - const byte* pSrcBits = bitData; - const byte* pEndBits = bitData + bitSize; - - size_t index = 0; - for (size_t j = 0; j < arraySize; j++) - { - size_t w = width; - size_t h = height; - size_t d = depth; - for (size_t i = 0; i < mipCount; i++) - { - GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows); - - if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize)) - { - if (!twidth) - { - twidth = w; - theight = h; - tdepth = d; - } - - assert(index < mipCount * arraySize); - _Analysis_assume_(index < mipCount * arraySize); - initData[index].pSysMem = (const void*)pSrcBits; - initData[index].SysMemPitch = static_cast(RowBytes); - initData[index].SysMemSlicePitch = static_cast(NumBytes); - ++index; - } - else if (!j) - { - // Count number of skipped mipmaps (first item only) - ++skipMip; - } - - if (pSrcBits + (NumBytes*d) > pEndBits) - { - throw ref new Platform::OutOfBoundsException(); - } - - pSrcBits += NumBytes * d; - - w = w >> 1; - h = h >> 1; - d = d >> 1; - if (w == 0) - { - w = 1; - } - if (h == 0) - { - h = 1; - } - if (d == 0) - { - d = 1; - } - } - } - - if (!index) - { - throw ref new Platform::FailureException(); - } -} - - -//-------------------------------------------------------------------------------------- -static HRESULT CreateD3DResources( - _In_ ID3D11Device* d3dDevice, - _In_ uint32 resDim, - _In_ size_t width, - _In_ size_t height, - _In_ size_t depth, - _In_ size_t mipCount, - _In_ size_t arraySize, - _In_ DXGI_FORMAT format, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ bool forceSRGB, - _In_ bool isCubeMap, - _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView - ) -{ - if (!d3dDevice || !initData) - { - return E_INVALIDARG; - } - - HRESULT hr = E_FAIL; - - if (forceSRGB) - { - format = MakeSRGB(format); - } - - switch (resDim) - { - case D3D11_RESOURCE_DIMENSION_TEXTURE1D: - { - D3D11_TEXTURE1D_DESC desc; - desc.Width = static_cast(width); - desc.MipLevels = static_cast(mipCount); - desc.ArraySize = static_cast(arraySize); - desc.Format = format; - desc.Usage = usage; - desc.BindFlags = bindFlags; - desc.CPUAccessFlags = cpuAccessFlags; - desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; - - ID3D11Texture1D* tex = nullptr; - hr = d3dDevice->CreateTexture1D(&desc, initData, &tex); - - if (SUCCEEDED(hr) && tex != 0) - { - if (textureView != 0) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - memset(&SRVDesc, 0, sizeof(SRVDesc)); - SRVDesc.Format = format; - - if (arraySize > 1) - { - SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY; - SRVDesc.Texture1DArray.MipLevels = desc.MipLevels; - SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); - } - else - { - SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D; - SRVDesc.Texture1D.MipLevels = desc.MipLevels; - } - - hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); - - if (FAILED(hr)) - { - tex->Release(); - return hr; - } - } - - if (texture != 0) - { - *texture = tex; - } - else - { - tex->Release(); - } - } - } - break; - - case D3D11_RESOURCE_DIMENSION_TEXTURE2D: - { - D3D11_TEXTURE2D_DESC desc; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.MipLevels = static_cast(mipCount); - desc.ArraySize = static_cast(arraySize); - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - desc.Usage = usage; - desc.BindFlags = bindFlags; - desc.CPUAccessFlags = cpuAccessFlags; - if (isCubeMap) - { - desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE; - } - else - { - desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; - } - - ID3D11Texture2D* tex = nullptr; - hr = d3dDevice->CreateTexture2D(&desc, initData, &tex); - - if (SUCCEEDED(hr) && tex != 0) - { - if (textureView != 0) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - memset(&SRVDesc, 0, sizeof(SRVDesc)); - SRVDesc.Format = format; - - if (isCubeMap) - { - if (arraySize > 6) - { - SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY; - SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels; - - // Earlier we set arraySize to (NumCubes * 6) - SRVDesc.TextureCubeArray.NumCubes = static_cast(arraySize / 6); - } - else - { - SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE; - SRVDesc.TextureCube.MipLevels = desc.MipLevels; - } - } - else if (arraySize > 1) - { - SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY; - SRVDesc.Texture2DArray.MipLevels = desc.MipLevels; - SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); - } - else - { - SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Texture2D.MipLevels = desc.MipLevels; - } - - hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); - - if (FAILED(hr)) - { - tex->Release(); - return hr; - } - } - - if (texture != 0) - { - *texture = tex; - } - else - { - tex->Release(); - } - } - } - break; - - case D3D11_RESOURCE_DIMENSION_TEXTURE3D: - { - D3D11_TEXTURE3D_DESC desc; - desc.Width = static_cast(width); - desc.Height = static_cast(height); - desc.Depth = static_cast(depth); - desc.MipLevels = static_cast(mipCount); - desc.Format = format; - desc.Usage = usage; - desc.BindFlags = bindFlags; - desc.CPUAccessFlags = cpuAccessFlags; - desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; - - ID3D11Texture3D* tex = nullptr; - hr = d3dDevice->CreateTexture3D(&desc, initData, &tex); - - if (SUCCEEDED(hr) && tex != 0) - { - if (textureView != 0) - { - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - memset(&SRVDesc, 0, sizeof(SRVDesc)); - SRVDesc.Format = format; - SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D; - SRVDesc.Texture3D.MipLevels = desc.MipLevels; - - hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); - - if (FAILED(hr)) - { - tex->Release(); - return hr; - } - } - - if (texture != 0) - { - *texture = tex; - } - else - { - tex->Release(); - } - } - } - break; - } - - return hr; -} - - -//-------------------------------------------------------------------------------------- -static void CreateTextureFromDDS( - _In_ ID3D11Device* d3dDevice, - _In_ const DDS_HEADER* header, - _In_reads_bytes_(bitSize) const byte* bitData, - _In_ size_t bitSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ bool forceSRGB, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView - ) -{ - HRESULT hr = S_OK; - - size_t width = header->width; - size_t height = header->height; - size_t depth = header->depth; - - uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN; - size_t arraySize = 1; - DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; - bool isCubeMap = false; - - size_t mipCount = header->mipMapCount; - if (0 == mipCount) - { - mipCount = 1; - } - - if ((header->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) - { - auto d3d10ext = reinterpret_cast((const char*)header + sizeof(DDS_HEADER)); - - arraySize = d3d10ext->arraySize; - if (arraySize == 0) - { - throw ref new Platform::FailureException(); - } - - if (BitsPerPixel(d3d10ext->dxgiFormat) == 0) - { - throw ref new Platform::FailureException(); - } - - format = d3d10ext->dxgiFormat; - - switch (d3d10ext->resourceDimension) - { - case D3D11_RESOURCE_DIMENSION_TEXTURE1D: - // D3DX writes 1D textures with a fixed Height of 1 - if ((header->flags & DDS_HEIGHT) && height != 1) - { - throw ref new Platform::FailureException(); - } - height = depth = 1; - break; - - case D3D11_RESOURCE_DIMENSION_TEXTURE2D: - if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE) - { - arraySize *= 6; - isCubeMap = true; - } - depth = 1; - break; - - case D3D11_RESOURCE_DIMENSION_TEXTURE3D: - if (!(header->flags & DDS_HEADER_FLAGS_VOLUME)) - { - throw ref new Platform::FailureException(); - } - - if (arraySize > 1) - { - throw ref new Platform::FailureException(); - } - break; - - default: - return throw ref new Platform::FailureException(); - } - - resDim = d3d10ext->resourceDimension; - } - else - { - format = GetDXGIFormat(header->ddspf); - - if (format == DXGI_FORMAT_UNKNOWN) - { - return throw ref new Platform::FailureException(); - } - - if (header->flags & DDS_HEADER_FLAGS_VOLUME) - { - resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D; - } - else - { - if (header->caps2 & DDS_CUBEMAP) - { - // We require all six faces to be defined - if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES) - { - return throw ref new Platform::FailureException(); - } - - arraySize = 6; - isCubeMap = true; - } - - depth = 1; - resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D; - - // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture - } - - assert(BitsPerPixel(format) != 0); - } - - // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements) - if (mipCount > D3D11_REQ_MIP_LEVELS) - { - return throw ref new Platform::FailureException(); - } - - switch (resDim) - { - case D3D11_RESOURCE_DIMENSION_TEXTURE1D: - if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) - { - return throw ref new Platform::FailureException(); - } - break; - - case D3D11_RESOURCE_DIMENSION_TEXTURE2D: - if (isCubeMap) - { - // This is the right bound because we set arraySize to (NumCubes*6) above - if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURECUBE_DIMENSION) || - (height > D3D11_REQ_TEXTURECUBE_DIMENSION)) - { - return throw ref new Platform::FailureException(); - } - } - else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) || - (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) - { - return throw ref new Platform::FailureException(); - } - break; - - case D3D11_RESOURCE_DIMENSION_TEXTURE3D: - if ((arraySize > 1) || - (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) - { - return throw ref new Platform::FailureException(); - } - break; - } - - // Create the texture - std::unique_ptr initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]); - - size_t skipMip = 0; - size_t twidth = 0; - size_t theight = 0; - size_t tdepth = 0; - FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get()); - - hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView); - - if (FAILED(hr) && !maxsize && (mipCount > 1)) - { - // Retry with a maxsize determined by feature level - switch (d3dDevice->GetFeatureLevel()) - { - case D3D_FEATURE_LEVEL_9_1: - case D3D_FEATURE_LEVEL_9_2: - if (isCubeMap) - { - maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION; - } - else - { - maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION - : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION; - } - break; - - case D3D_FEATURE_LEVEL_9_3: - maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION - : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION; - break; - - default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1 - maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION - : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; - break; - } - - FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get()); - - hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView); - } - - DX::ThrowIfFailed(hr); -} - - -//-------------------------------------------------------------------------------------- -static D2D1_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header) -{ - if (header->ddspf.flags & DDS_FOURCC) - { - if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC) - { - auto d3d10ext = reinterpret_cast((const char*)header + sizeof(DDS_HEADER)); - switch (d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK) - { - case DDS_ALPHA_MODE_STRAIGHT: - return D2D1_ALPHA_MODE_STRAIGHT; - - case DDS_ALPHA_MODE_PREMULTIPLIED: - return D2D1_ALPHA_MODE_PREMULTIPLIED; - - case DDS_ALPHA_MODE_OPAQUE: - case DDS_ALPHA_MODE_CUSTOM: - // No D2D1_ALPHA_MODE equivalent, so return "Ignore" for now - return D2D1_ALPHA_MODE_IGNORE; - } - } - else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC) - || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC)) - { - return D2D1_ALPHA_MODE_PREMULTIPLIED; - } - // DXT1, DXT3, and DXT5 legacy files could be straight alpha or something else, so return "Unknown" to leave it up to the app - } - - return D2D1_ALPHA_MODE_UNKNOWN; -} - - -//-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -void CreateDDSTextureFromMemory( - ID3D11Device* d3dDevice, - const uint8_t* ddsData, - size_t ddsDataSize, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - size_t maxsize, - D2D1_ALPHA_MODE* alphaMode - ) -{ - return CreateDDSTextureFromMemoryEx(d3dDevice, ddsData, ddsDataSize, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, texture, textureView, alphaMode); -} - - -//-------------------------------------------------------------------------------------- -_Use_decl_annotations_ -void CreateDDSTextureFromMemoryEx( - ID3D11Device* d3dDevice, - const uint8_t* ddsData, - size_t ddsDataSize, - size_t maxsize, - D3D11_USAGE usage, - unsigned int bindFlags, - unsigned int cpuAccessFlags, - unsigned int miscFlags, - bool forceSRGB, - ID3D11Resource** texture, - ID3D11ShaderResourceView** textureView, - D2D1_ALPHA_MODE* alphaMode - ) -{ - if (texture) - { - *texture = nullptr; - } - if (textureView) - { - *textureView = nullptr; - } - if (alphaMode) - { - *alphaMode = D2D1_ALPHA_MODE_UNKNOWN; - } - - if (!d3dDevice || !ddsData || (!texture && !textureView)) - { - throw ref new Platform::InvalidArgumentException(); - } - - // Validate DDS file in memory - if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER))) - { - throw ref new Platform::FailureException(); - } - - uint32 dwMagicNumber = *(const uint32*)(ddsData); - if (dwMagicNumber != DDS_MAGIC) - { - throw ref new Platform::FailureException(); - } - - auto header = reinterpret_cast(ddsData + sizeof(uint32)); - - // Verify header to validate DDS file - if (header->size != sizeof(DDS_HEADER) || - header->ddspf.size != sizeof(DDS_PIXELFORMAT)) - { - throw ref new Platform::FailureException(); - } - - // Check for DX10 extension - bool bDXT10Header = false; - if ((header->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) - { - // Must be long enough for both headers and magic value - if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10))) - { - throw ref new Platform::FailureException(); - } - - bDXT10Header = true; - } - - ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); - - CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView); - - if (alphaMode) - *alphaMode = GetAlphaMode(header); -} diff --git a/DirectXSceneStore/Common/DDSTextureLoader.h b/DirectXSceneStore/Common/DDSTextureLoader.h deleted file mode 100644 index aaacf95..0000000 --- a/DirectXSceneStore/Common/DDSTextureLoader.h +++ /dev/null @@ -1,46 +0,0 @@ -//-------------------------------------------------------------------------------------- -// File: DDSTextureLoader.h -// -// Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it -// -// Note these functions are useful as a light-weight runtime loader for DDS files. For -// a full-featured DDS file reader, writer, and texture processing pipeline see -// the 'Texconv' sample and the 'DirectXTex' library. -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// http://go.microsoft.com/fwlink/?LinkId=248926 -// http://go.microsoft.com/fwlink/?LinkId=248929 -//-------------------------------------------------------------------------------------- - -#pragma once - -void CreateDDSTextureFromMemory( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(ddsDataSize) const byte* ddsData, - _In_ size_t ddsDataSize, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize = 0, - _Out_opt_ D2D1_ALPHA_MODE* alphaMode = nullptr - ); - -void CreateDDSTextureFromMemoryEx( - _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, - _In_ size_t ddsDataSize, - _In_ size_t maxsize, - _In_ D3D11_USAGE usage, - _In_ unsigned int bindFlags, - _In_ unsigned int cpuAccessFlags, - _In_ unsigned int miscFlags, - _In_ bool forceSRGB, - _Outptr_opt_ ID3D11Resource** texture, - _Outptr_opt_ ID3D11ShaderResourceView** textureView, - _Out_opt_ D2D1_ALPHA_MODE* alphaMode = nullptr - ); diff --git a/DirectXSceneStore/Common/DeviceResources.cpp b/DirectXSceneStore/Common/DeviceResources.cpp deleted file mode 100644 index 60ebb92..0000000 --- a/DirectXSceneStore/Common/DeviceResources.cpp +++ /dev/null @@ -1,809 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "DeviceResources.h" -#include "DirectXSample.h" -#include - -using namespace D2D1; -using namespace DirectX; -using namespace Microsoft::WRL; -using namespace Windows::Foundation; -using namespace Windows::Graphics::Display; -using namespace Windows::UI::Core; -using namespace Windows::UI::Xaml::Controls; -using namespace Platform; - -// Constants used to calculate screen rotations. -namespace ScreenRotation -{ - // 0-degree Z-rotation - static const XMFLOAT4X4 Rotation0( - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); - - // 90-degree Z-rotation - static const XMFLOAT4X4 Rotation90( - 0.0f, 1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); - - // 180-degree Z-rotation - static const XMFLOAT4X4 Rotation180( - -1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, -1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); - - // 270-degree Z-rotation - static const XMFLOAT4X4 Rotation270( - 0.0f, -1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); -}; - -// Constructor for DeviceResources. -DX::DeviceResources::DeviceResources() : - m_screenViewport(), - m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1), - m_d3dRenderTargetSize(), - m_outputSize(), - m_logicalSize(), - m_nativeOrientation(DisplayOrientations::None), - m_currentOrientation(DisplayOrientations::None), - m_dpi(-1.0f), - m_compositionScaleX(1.0f), - m_compositionScaleY(1.0f), - m_deviceNotify(nullptr) -{ - CreateDeviceIndependentResources(); - CreateDeviceResources(); -} - -// Configures resources that don't depend on the Direct3D device. -void DX::DeviceResources::CreateDeviceIndependentResources() -{ - // Initialize Direct2D resources. - D2D1_FACTORY_OPTIONS options; - ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS)); - -#if defined(_DEBUG) - // If the project is in a debug build, enable Direct2D debugging via SDK Layers. - options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION; -#endif - - // Initialize the Direct2D Factory. - DX::ThrowIfFailed( - D2D1CreateFactory( - D2D1_FACTORY_TYPE_SINGLE_THREADED, - __uuidof(ID2D1Factory2), - &options, - &m_d2dFactory - ) - ); - - // Initialize the DirectWrite Factory. - DX::ThrowIfFailed( - DWriteCreateFactory( - DWRITE_FACTORY_TYPE_SHARED, - __uuidof(IDWriteFactory2), - &m_dwriteFactory - ) - ); - - // Initialize the Windows Imaging Component (WIC) Factory. - DX::ThrowIfFailed( - CoCreateInstance( - CLSID_WICImagingFactory2, - nullptr, - CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(&m_wicFactory) - ) - ); -} - -// Configures the Direct3D device, and stores handles to it and the device context. -void DX::DeviceResources::CreateDeviceResources() -{ - // This flag adds support for surfaces with a different color channel ordering - // than the API default. It is required for compatibility with Direct2D. - UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; - -#if defined(_DEBUG) - if (DX::SdkLayersAvailable()) - { - // If the project is in a debug build, enable debugging via SDK Layers with this flag. - creationFlags |= D3D11_CREATE_DEVICE_DEBUG; - } -#endif - - // This array defines the set of DirectX hardware feature levels this app will support. - // Note the ordering should be preserved. - // Don't forget to declare your application's minimum required feature level in its - // description. All applications are assumed to support 9.1 unless otherwise stated. - D3D_FEATURE_LEVEL featureLevels [] = - { - D3D_FEATURE_LEVEL_11_1, - D3D_FEATURE_LEVEL_11_0, - D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0, - D3D_FEATURE_LEVEL_9_3, - D3D_FEATURE_LEVEL_9_2, - D3D_FEATURE_LEVEL_9_1 - }; - - // Create the Direct3D 11 API device object and a corresponding context. - ComPtr device; - ComPtr context; - - HRESULT hr = D3D11CreateDevice( - nullptr, // Specify nullptr to use the default adapter. - D3D_DRIVER_TYPE_HARDWARE, // Create a device using the hardware graphics driver. - 0, // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE. - creationFlags, // Set debug and Direct2D compatibility flags. - featureLevels, // List of feature levels this app can support. - ARRAYSIZE(featureLevels), // Size of the list above. - D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps. - &device, // Returns the Direct3D device created. - &m_d3dFeatureLevel, // Returns feature level of device created. - &context // Returns the device immediate context. - ); - - if (FAILED(hr)) - { - // If the initialization fails, fall back to the WARP device. - // For more information on WARP, see: - // http://go.microsoft.com/fwlink/?LinkId=286690 - DX::ThrowIfFailed( - D3D11CreateDevice( - nullptr, - D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device. - 0, - creationFlags, - featureLevels, - ARRAYSIZE(featureLevels), - D3D11_SDK_VERSION, - &device, - &m_d3dFeatureLevel, - &context - ) - ); - } - - // Store pointers to the Direct3D 11.1 API device and immediate context. - DX::ThrowIfFailed( - device.As(&m_d3dDevice) - ); - - DX::ThrowIfFailed( - context.As(&m_d3dContext) - ); - - // Create the Direct2D device object and a corresponding context. - ComPtr dxgiDevice; - DX::ThrowIfFailed( - m_d3dDevice.As(&dxgiDevice) - ); - - DX::ThrowIfFailed( - m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice) - ); - - DX::ThrowIfFailed( - m_d2dDevice->CreateDeviceContext( - D2D1_DEVICE_CONTEXT_OPTIONS_NONE, - &m_d2dContext - ) - ); -} - -// These resources need to be recreated every time the window size is changed. -void DX::DeviceResources::CreateWindowSizeDependentResources() -{ - // Clear the previous window size specific context. - ID3D11RenderTargetView* nullViews [] = { nullptr }; - m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr); - m_d3dRenderTargetView = nullptr; - m_d3dRenderTargetViewRight = nullptr; - m_d2dContext->SetTarget(nullptr); - m_d2dTargetBitmap = nullptr; - m_d2dTargetBitmapRight = nullptr; - m_d3dDepthStencilView = nullptr; - m_d3dContext->Flush(); - - // Calculate the necessary swap chain and render target size in pixels. - m_outputSize.Width = m_logicalSize.Width * m_compositionScaleX; - m_outputSize.Height = m_logicalSize.Height * m_compositionScaleY; - - // Prevent zero size DirectX content from being created. - m_outputSize.Width = max(m_outputSize.Width, 1); - m_outputSize.Height = max(m_outputSize.Height, 1); - -#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP - // The WindowsPhone version of SwapChainPanel always automatically rotates the - // the swapchain to the screen orientation. For Windows Phone we disable - // the optimization of doing drawing in the native orientation to avoid a - // rotate copy. - auto displayRotation = DXGI_MODE_ROTATION_IDENTITY; - m_d3dRenderTargetSize.Width = m_outputSize.Width; - m_d3dRenderTargetSize.Height = m_outputSize.Height; -#else - // The width and height of the swap chain must be based on the window's - // natively-oriented width and height. If the window is not in the native - // orientation, the dimensions must be reversed. - // We do this to take advantage on an optimization that allows for the - // application to draw the content in the proper orientation and then - // indicate to DXGI that the content has been pre-rotated. - DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation(); - - bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270; - m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width; - m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height; -#endif - - if (m_swapChain != nullptr) - { - // If the swap chain already exists, resize it. - HRESULT hr = m_swapChain->ResizeBuffers( - 2, // Double-buffered swap chain. - static_cast(m_d3dRenderTargetSize.Width), - static_cast(m_d3dRenderTargetSize.Height), - DXGI_FORMAT_B8G8R8A8_UNORM, - 0 - ); - - if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) - { - // If the device was removed for any reason, a new device and swap chain will need to be created. - HandleDeviceLost(); - - // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method - // and correctly set up the new device. - return; - } - else - { - DX::ThrowIfFailed(hr); - } - } - else - { - CheckStereoEnabledStatus(); - - // Otherwise, create a new one using the same adapter as the existing Direct3D device. - DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 }; - - swapChainDesc.Width = static_cast(m_d3dRenderTargetSize.Width); // Match the size of the window. - swapChainDesc.Height = static_cast(m_d3dRenderTargetSize.Height); - swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format. - swapChainDesc.Stereo = m_stereoEnabled; - swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling. - swapChainDesc.SampleDesc.Quality = 0; - swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency. - swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect. - swapChainDesc.Flags = 0; - swapChainDesc.Scaling = DXGI_SCALING_STRETCH; - swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; - - // This sequence obtains the DXGI factory that was used to create the Direct3D device above. - ComPtr dxgiDevice; - DX::ThrowIfFailed( - m_d3dDevice.As(&dxgiDevice) - ); - - ComPtr dxgiAdapter; - DX::ThrowIfFailed( - dxgiDevice->GetAdapter(&dxgiAdapter) - ); - - ComPtr dxgiFactory; - DX::ThrowIfFailed( - dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory)) - ); - - // When using XAML interop, the swap chain must be created for composition. - DX::ThrowIfFailed( - dxgiFactory->CreateSwapChainForComposition( - m_d3dDevice.Get(), - &swapChainDesc, - nullptr, - &m_swapChain - ) - ); - - // Associate swap chain with SwapChainPanel - // UI changes will need to be dispatched back to the UI thread - m_swapChainPanel->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([=]() - { - // Get backing native interface for SwapChainPanel - ComPtr panelNative; - DX::ThrowIfFailed( - reinterpret_cast(m_swapChainPanel)->QueryInterface(IID_PPV_ARGS(&panelNative)) - ); - - DX::ThrowIfFailed( - panelNative->SetSwapChain(m_swapChain.Get()) - ); - }, CallbackContext::Any)); - - // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and - // ensures that the application will only render after each VSync, minimizing power consumption. - DX::ThrowIfFailed( - dxgiDevice->SetMaximumFrameLatency(1) - ); - } - - // Set the proper orientation for the swap chain, and generate 2D and - // 3D matrix transformations for rendering to the rotated swap chain. - // Note the rotation angle for the 2D and 3D transforms are different. - // This is due to the difference in coordinate spaces. Additionally, - // the 3D matrix is specified explicitly to avoid rounding errors. - - switch (displayRotation) - { - case DXGI_MODE_ROTATION_IDENTITY: - m_orientationTransform2D = Matrix3x2F::Identity(); - m_orientationTransform3D = ScreenRotation::Rotation0; - break; - - case DXGI_MODE_ROTATION_ROTATE90: - m_orientationTransform2D = - Matrix3x2F::Rotation(90.0f) * - Matrix3x2F::Translation(m_logicalSize.Height, 0.0f); - m_orientationTransform3D = ScreenRotation::Rotation270; - break; - - case DXGI_MODE_ROTATION_ROTATE180: - m_orientationTransform2D = - Matrix3x2F::Rotation(180.0f) * - Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height); - m_orientationTransform3D = ScreenRotation::Rotation180; - break; - - case DXGI_MODE_ROTATION_ROTATE270: - m_orientationTransform2D = - Matrix3x2F::Rotation(270.0f) * - Matrix3x2F::Translation(0.0f, m_logicalSize.Width); - m_orientationTransform3D = ScreenRotation::Rotation90; - break; - - default: - throw ref new FailureException(); - } - - DX::ThrowIfFailed( - m_swapChain->SetRotation(displayRotation) - ); - - // Setup inverse scale on the swap chain - DXGI_MATRIX_3X2_F inverseScale = { 0 }; - inverseScale._11 = 1.0f / m_compositionScaleX; - inverseScale._22 = 1.0f / m_compositionScaleY; - ComPtr spSwapChain2; - DX::ThrowIfFailed( - m_swapChain.As(&spSwapChain2) - ); - - DX::ThrowIfFailed( - spSwapChain2->SetMatrixTransform(&inverseScale) - ); - - // Create a render target view of the swap chain back buffer. - ComPtr backBuffer; - DX::ThrowIfFailed( - m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer)) - ); - - DX::ThrowIfFailed( - m_d3dDevice->CreateRenderTargetView( - backBuffer.Get(), - nullptr, - &m_d3dRenderTargetView - ) - ); - - // Stereo swapchains have an arrayed resource, so create a second Render Target - // for the right eye buffer. - if (m_stereoEnabled) - { - CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewRightDesc( - D3D11_RTV_DIMENSION_TEXTURE2DARRAY, - DXGI_FORMAT_B8G8R8A8_UNORM, - 0, - 1, - 1 - ); - - DX::ThrowIfFailed( - m_d3dDevice->CreateRenderTargetView( - backBuffer.Get(), - &renderTargetViewRightDesc, - &m_d3dRenderTargetViewRight - ) - ); - } - - // Create a depth stencil view for use with 3D rendering if needed. - CD3D11_TEXTURE2D_DESC depthStencilDesc( - DXGI_FORMAT_D24_UNORM_S8_UINT, - static_cast(m_d3dRenderTargetSize.Width), - static_cast(m_d3dRenderTargetSize.Height), - 1, // This depth stencil view has only one texture. - 1, // Use a single mipmap level. - D3D11_BIND_DEPTH_STENCIL - ); - - ComPtr depthStencil; - DX::ThrowIfFailed( - m_d3dDevice->CreateTexture2D( - &depthStencilDesc, - nullptr, - &depthStencil - ) - ); - - CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D); - DX::ThrowIfFailed( - m_d3dDevice->CreateDepthStencilView( - depthStencil.Get(), - &depthStencilViewDesc, - &m_d3dDepthStencilView - ) - ); - - // Set the 3D rendering viewport to target the entire window. - m_screenViewport = CD3D11_VIEWPORT( - 0.0f, - 0.0f, - m_d3dRenderTargetSize.Width, - m_d3dRenderTargetSize.Height - ); - - m_d3dContext->RSSetViewports(1, &m_screenViewport); - - // Create a Direct2D target bitmap associated with the - // swap chain back buffer and set it as the current target. - D2D1_BITMAP_PROPERTIES1 bitmapProperties = - D2D1::BitmapProperties1( - D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, - D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED - ), - m_dpi, - m_dpi - ); - - ComPtr dxgiBackBuffer; - DX::ThrowIfFailed( - m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer)) - ); - - ComPtr dxgiSurface; - DX::ThrowIfFailed( - dxgiBackBuffer->CreateSubresourceSurface(0, &dxgiSurface) - ); - - DX::ThrowIfFailed( - m_d2dContext->CreateBitmapFromDxgiSurface( - dxgiSurface.Get(), - &bitmapProperties, - &m_d2dTargetBitmap - ) - ); - - // Stereo swapchains have an arrayed resource, so create a second Target Bitmap - // for the right eye buffer. - if (m_stereoEnabled) - { - DX::ThrowIfFailed( - dxgiBackBuffer->CreateSubresourceSurface(1, &dxgiSurface) - ); - DX::ThrowIfFailed( - m_d2dContext->CreateBitmapFromDxgiSurface( - dxgiSurface.Get(), - &bitmapProperties, - &m_d2dTargetBitmapRight - ) - ); - } - - m_d2dContext->SetTarget(m_d2dTargetBitmap.Get()); - - // Grayscale text anti-aliasing is recommended for all Windows Store apps. - m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE); -} - -// This method is called when the XAML control is created (or re-created). -void DX::DeviceResources::SetSwapChainPanel(SwapChainPanel^ panel) -{ - DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); - - m_swapChainPanel = panel; - m_logicalSize = Windows::Foundation::Size(static_cast(panel->ActualWidth), static_cast(panel->ActualHeight)); - m_nativeOrientation = currentDisplayInformation->NativeOrientation; - m_currentOrientation = currentDisplayInformation->CurrentOrientation; - m_compositionScaleX = panel->CompositionScaleX; - m_compositionScaleY = panel->CompositionScaleY; - m_dpi = currentDisplayInformation->LogicalDpi; - m_d2dContext->SetDpi(m_dpi, m_dpi); - - CreateWindowSizeDependentResources(); -} - -// This method is called in the event handler for the SizeChanged event. -void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize) -{ - if (m_logicalSize != logicalSize) - { - m_logicalSize = logicalSize; - CreateWindowSizeDependentResources(); - } -} - -// This method is called in the event handler for the DpiChanged event. -void DX::DeviceResources::SetDpi(float dpi) -{ - if (dpi != m_dpi) - { - m_dpi = dpi; - m_d2dContext->SetDpi(m_dpi, m_dpi); - CreateWindowSizeDependentResources(); - } -} - -// This method is called in the event handler for the OrientationChanged event. -void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation) -{ - if (m_currentOrientation != currentOrientation) - { - m_currentOrientation = currentOrientation; - CreateWindowSizeDependentResources(); - } -} - -// This method is called in the event handler for the CompositionScaleChanged event. -void DX::DeviceResources::SetCompositionScale(float compositionScaleX, float compositionScaleY) -{ - if (m_compositionScaleX != compositionScaleX || - m_compositionScaleY != compositionScaleY) - { - m_compositionScaleX = compositionScaleX; - m_compositionScaleY = compositionScaleY; - CreateWindowSizeDependentResources(); - } -} - -// This method is called in the event handler for the DisplayContentsInvalidated event. -void DX::DeviceResources::ValidateDevice() -{ - // The D3D Device is no longer valid if the default adapter changed since the device - // was created or if the device has been removed. - - // First, get the information for the default adapter from when the device was created. - - ComPtr dxgiDevice; - DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice)); - - ComPtr deviceAdapter; - DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter)); - - ComPtr deviceFactory; - DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory))); - - ComPtr previousDefaultAdapter; - DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter)); - - DXGI_ADAPTER_DESC previousDesc; - DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc)); - - // Next, get the information for the current default adapter. - - ComPtr currentFactory; - DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(¤tFactory))); - - ComPtr currentDefaultAdapter; - DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, ¤tDefaultAdapter)); - - DXGI_ADAPTER_DESC currentDesc; - DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(¤tDesc)); - - // If the adapter LUIDs don't match, or if the device reports that it has been removed, - // a new D3D device must be created. - - if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart || - previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart || - FAILED(m_d3dDevice->GetDeviceRemovedReason())) - { - // Release references to resources related to the old device. - dxgiDevice = nullptr; - deviceAdapter = nullptr; - deviceFactory = nullptr; - previousDefaultAdapter = nullptr; - - // Create a new device and swap chain. - HandleDeviceLost(); - } -} - -// Recreate all device resources and set them back to the current state. -void DX::DeviceResources::HandleDeviceLost() -{ - m_swapChain = nullptr; - - if (m_deviceNotify != nullptr) - { - m_deviceNotify->OnDeviceLost(); - } - - // Make sure the rendering state has been released. - m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr); - m_d3dDepthStencilView = nullptr; - m_d3dRenderTargetView = nullptr; - m_d3dRenderTargetViewRight = nullptr; - - m_d2dContext->SetTarget(nullptr); - m_d2dTargetBitmap = nullptr; - m_d2dTargetBitmapRight = nullptr; - m_d2dContext = nullptr; - m_d2dDevice = nullptr; - - m_d3dContext->Flush(); - - CreateDeviceResources(); - m_d2dContext->SetDpi(m_dpi, m_dpi); - CreateWindowSizeDependentResources(); - - if (m_deviceNotify != nullptr) - { - m_deviceNotify->OnDeviceRestored(); - } -} - -// Register our DeviceNotify to be informed on device lost and creation. -void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify) -{ - m_deviceNotify = deviceNotify; -} - -// Call this method when the app suspends. It provides a hint to the driver that the app -// is entering an idle state and that temporary buffers can be reclaimed for use by other apps. -void DX::DeviceResources::Trim() -{ - ComPtr dxgiDevice; - m_d3dDevice.As(&dxgiDevice); - - dxgiDevice->Trim(); -} - -// Present the contents of the swap chain to the screen. -void DX::DeviceResources::Present() -{ - // 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 - // frames that will never be displayed to the screen. - HRESULT hr = m_swapChain->Present(1, 0); - - // Discard the contents of the render target. - // This is a valid operation only when the existing contents will be entirely - // overwritten. If dirty or scroll rects are used, this call should be removed. - m_d3dContext->DiscardView(m_d3dRenderTargetView.Get()); - - // Discard the contents of the depth stencil. - m_d3dContext->DiscardView(m_d3dDepthStencilView.Get()); - - // If the device was removed either by a disconnection or a driver upgrade, we - // must recreate all device resources. - if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) - { - HandleDeviceLost(); - } - else - { - DX::ThrowIfFailed(hr); - } -} - -// This method determines the rotation between the display device's native Orientation and the -// current display orientation. -DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation() -{ - DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED; - - // Note: NativeOrientation can only be Landscape or Portrait even though - // the DisplayOrientations enum has other values. - switch (m_nativeOrientation) - { - case DisplayOrientations::Landscape: - switch (m_currentOrientation) - { - case DisplayOrientations::Landscape: - rotation = DXGI_MODE_ROTATION_IDENTITY; - break; - - case DisplayOrientations::Portrait: - rotation = DXGI_MODE_ROTATION_ROTATE270; - break; - - case DisplayOrientations::LandscapeFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE180; - break; - - case DisplayOrientations::PortraitFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE90; - break; - } - break; - - case DisplayOrientations::Portrait: - switch (m_currentOrientation) - { - case DisplayOrientations::Landscape: - rotation = DXGI_MODE_ROTATION_ROTATE90; - break; - - case DisplayOrientations::Portrait: - rotation = DXGI_MODE_ROTATION_IDENTITY; - break; - - case DisplayOrientations::LandscapeFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE270; - break; - - case DisplayOrientations::PortraitFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE180; - break; - } - break; - } - return rotation; -} - -void DX::DeviceResources::UpdateStereoState() -{ - bool previousStereoState = m_stereoEnabled; - CheckStereoEnabledStatus(); - if (previousStereoState != m_stereoEnabled) - { - // Swap chain needs to be recreated so release the existing one. - // The rest of the dependent resources with be released in CreateWindowSizeDependentResources. - m_swapChain = nullptr; - CreateWindowSizeDependentResources(); - } - -} - -void DX::DeviceResources::CheckStereoEnabledStatus() -{ - // first, retrieve the underlying DXGI Device from the D3D Device - ComPtr dxgiDevice; - DX::ThrowIfFailed( - m_d3dDevice.As(&dxgiDevice) - ); - - // next, get the associated adapter from the DXGI Device - ComPtr dxgiAdapter; - DX::ThrowIfFailed( - dxgiDevice->GetAdapter(&dxgiAdapter) - ); - - // next, get the parent factory from the DXGI adapter - ComPtr dxgiFactory; - DX::ThrowIfFailed( - dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory)) - ); - - m_stereoEnabled = dxgiFactory->IsWindowedStereoEnabled() ? true : false; -} diff --git a/DirectXSceneStore/Common/DeviceResources.h b/DirectXSceneStore/Common/DeviceResources.h deleted file mode 100644 index 162ff42..0000000 --- a/DirectXSceneStore/Common/DeviceResources.h +++ /dev/null @@ -1,115 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -namespace DX -{ - // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created. - interface IDeviceNotify - { - virtual void OnDeviceLost() = 0; - virtual void OnDeviceRestored() = 0; - }; - - // Controls all the DirectX device resources. - class DeviceResources - { - public: - DeviceResources(); - void SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^ panel); - void SetLogicalSize(Windows::Foundation::Size logicalSize); - void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation); - void SetDpi(float dpi); - void SetCompositionScale(float compositionScaleX, float compositionScaleY); - void UpdateStereoState(); - void ValidateDevice(); - void HandleDeviceLost(); - void RegisterDeviceNotify(IDeviceNotify* deviceNotify); - void Trim(); - void Present(); - - // Device Accessors. - Windows::Foundation::Size GetOutputSize() const { return m_outputSize; } - Windows::Foundation::Size GetLogicalSize() const { return m_logicalSize; } - Windows::Foundation::Size GetRenderTargetSize() const { return m_d3dRenderTargetSize; } - bool GetStereoState() const { return m_stereoEnabled; } - Windows::UI::Xaml::Controls::SwapChainPanel^ GetSwapChainPanel() const { return m_swapChainPanel; } - - // D3D Accessors. - ID3D11Device2* GetD3DDevice() const { return m_d3dDevice.Get(); } - ID3D11DeviceContext2* GetD3DDeviceContext() const { return m_d3dContext.Get(); } - IDXGISwapChain1* GetSwapChain() const { return m_swapChain.Get(); } - D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return m_d3dFeatureLevel; } - ID3D11RenderTargetView* GetBackBufferRenderTargetView() const { return m_d3dRenderTargetView.Get(); } - ID3D11RenderTargetView* GetBackBufferRenderTargetViewRight() const { return m_d3dRenderTargetViewRight.Get(); } - ID3D11DepthStencilView* GetDepthStencilView() const { return m_d3dDepthStencilView.Get(); } - D3D11_VIEWPORT GetScreenViewport() const { return m_screenViewport; } - DirectX::XMFLOAT4X4 GetOrientationTransform3D() const { return m_orientationTransform3D; } - - // D2D Accessors. - ID2D1Factory2* GetD2DFactory() const { return m_d2dFactory.Get(); } - ID2D1Device1* GetD2DDevice() const { return m_d2dDevice.Get(); } - ID2D1DeviceContext1* GetD2DDeviceContext() const { return m_d2dContext.Get(); } - ID2D1Bitmap1* GetD2DTargetBitmap() const { return m_d2dTargetBitmap.Get(); } - ID2D1Bitmap1* GetD2DTargetBitmapRight() const { return m_d2dTargetBitmapRight.Get(); } - IDWriteFactory2* GetDWriteFactory() const { return m_dwriteFactory.Get(); } - IWICImagingFactory2* GetWicImagingFactory() const { return m_wicFactory.Get(); } - D2D1::Matrix3x2F GetOrientationTransform2D() const { return m_orientationTransform2D; } - - private: - void CreateDeviceIndependentResources(); - void CreateDeviceResources(); - void CreateWindowSizeDependentResources(); - DXGI_MODE_ROTATION ComputeDisplayRotation(); - void CheckStereoEnabledStatus(); - - // Direct3D objects. - Microsoft::WRL::ComPtr m_d3dDevice; - Microsoft::WRL::ComPtr m_d3dContext; - Microsoft::WRL::ComPtr m_swapChain; - - // Direct3D rendering objects. Required for 3D. - Microsoft::WRL::ComPtr m_d3dRenderTargetView; - Microsoft::WRL::ComPtr m_d3dRenderTargetViewRight; - Microsoft::WRL::ComPtr m_d3dDepthStencilView; - D3D11_VIEWPORT m_screenViewport; - - // Direct2D drawing components. - Microsoft::WRL::ComPtr m_d2dFactory; - Microsoft::WRL::ComPtr m_d2dDevice; - Microsoft::WRL::ComPtr m_d2dContext; - Microsoft::WRL::ComPtr m_d2dTargetBitmap; - Microsoft::WRL::ComPtr m_d2dTargetBitmapRight; - - // DirectWrite drawing components. - Microsoft::WRL::ComPtr m_dwriteFactory; - Microsoft::WRL::ComPtr m_wicFactory; - - // Cached reference to the XAML panel. - Windows::UI::Xaml::Controls::SwapChainPanel^ m_swapChainPanel; - - // Cached device properties. - D3D_FEATURE_LEVEL m_d3dFeatureLevel; - Windows::Foundation::Size m_d3dRenderTargetSize; - Windows::Foundation::Size m_outputSize; - Windows::Foundation::Size m_logicalSize; - Windows::Graphics::Display::DisplayOrientations m_nativeOrientation; - Windows::Graphics::Display::DisplayOrientations m_currentOrientation; - float m_dpi; - float m_compositionScaleX; - float m_compositionScaleY; - bool m_stereoEnabled; - - // Transforms used for display orientation. - D2D1::Matrix3x2F m_orientationTransform2D; - DirectX::XMFLOAT4X4 m_orientationTransform3D; - - // The IDeviceNotify can be held directly as it owns the DeviceResources. - IDeviceNotify* m_deviceNotify; - }; -} \ No newline at end of file diff --git a/DirectXSceneStore/Common/DirectXSample.h b/DirectXSceneStore/Common/DirectXSample.h deleted file mode 100644 index 06898a0..0000000 --- a/DirectXSceneStore/Common/DirectXSample.h +++ /dev/null @@ -1,65 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once -#include - -namespace DX -{ - // Convert DirectX error codes to exceptions. - inline void ThrowIfFailed(HRESULT hr) - { - if (FAILED(hr)) - { - // Set a breakpoint on this line to catch DX API errors. - throw Platform::Exception::CreateException(hr); - } - } - - // Converts a length in device-independent pixels (DIPs) to a length in physical pixels. - inline float ConvertDipsToPixels(float dips, float dpi) - { - static const float dipsPerInch = 96.0f; - return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer. - } - - // Converts a length in physical pixels to a length in device-independent pixels (DIPs). - inline float ConvertPixelsToDips(float pixels) - { - static const float dipsPerInch = 96.0f; - return pixels * dipsPerInch / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; // Do not round. - } - - // Converts a length in physical pixels to a length in device-independent pixels (DIPs) using the provided DPI. This removes the need - // to call this function from a thread associated with a CoreWindow, which is required by DisplayInformation::GetForCurrentView(). - inline float ConvertPixelsToDips(float pixels, float dpi) - { - static const float dipsPerInch = 96.0f; - return pixels * dipsPerInch / dpi; // Do not round. - } - -#if defined(_DEBUG) - // Check for SDK Layer support. - inline bool SdkLayersAvailable() - { - HRESULT hr = D3D11CreateDevice( - nullptr, - D3D_DRIVER_TYPE_NULL, // There is no need to create a real hardware device. - 0, - D3D11_CREATE_DEVICE_DEBUG, // Check for the SDK layers. - nullptr, // Any feature level will do. - 0, - D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps. - nullptr, // No need to keep the D3D device reference. - nullptr, // No need to know the feature level. - nullptr // No need to keep the D3D device context reference. - ); - - return SUCCEEDED(hr); - } -#endif -} diff --git a/DirectXSceneStore/Common/PersistentState.cpp b/DirectXSceneStore/Common/PersistentState.cpp deleted file mode 100644 index 18bcb90..0000000 --- a/DirectXSceneStore/Common/PersistentState.cpp +++ /dev/null @@ -1,136 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "PersistentState.h" -#include "DirectXSample.h" - -using namespace Microsoft::WRL; -using namespace Windows::Foundation; -using namespace Windows::Foundation::Collections; -using namespace Windows::Storage; -using namespace DirectX; - -void PersistentState::Initialize( - _In_ IPropertySet^ settingsValues, - _In_ Platform::String^ key - ) -{ - m_settingsValues = settingsValues; - m_keyName = key; -} - -void PersistentState::SaveBool(Platform::String^ key, bool value) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - m_settingsValues->Remove(fullKey); - } - m_settingsValues->Insert(fullKey, PropertyValue::CreateInt32(value ? 1 : 0)); -} - -void PersistentState::SaveInt32(Platform::String^ key, int value) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - m_settingsValues->Remove(fullKey); - } - m_settingsValues->Insert(fullKey, PropertyValue::CreateInt32(value)); -} - -void PersistentState::SaveSingle(Platform::String^ key, float value) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - m_settingsValues->Remove(fullKey); - } - m_settingsValues->Insert(fullKey, PropertyValue::CreateSingle(value)); -} - -void PersistentState::SaveXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 value) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - m_settingsValues->Remove(fullKey); - } - Platform::Array^ array3 = ref new Platform::Array(3); - array3[0] = value.x; - array3[1] = value.y; - array3[2] = value.z; - m_settingsValues->Insert(fullKey, PropertyValue::CreateSingleArray(array3)); -} - -void PersistentState::SaveString(Platform::String^ key, Platform::String^ string) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - m_settingsValues->Remove(fullKey); - } - m_settingsValues->Insert(fullKey, PropertyValue::CreateString(string)); -} - -bool PersistentState::LoadBool(Platform::String^ key, bool defaultValue) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - int state = safe_cast(m_settingsValues->Lookup(fullKey))->GetInt32(); - return state ? true : false; - } - return defaultValue; -} - -int PersistentState::LoadInt32(Platform::String^ key, int defaultValue) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - return safe_cast(m_settingsValues->Lookup(fullKey))->GetInt32(); - } - return defaultValue; -} - -float PersistentState::LoadSingle(Platform::String^ key, float defaultValue) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - return safe_cast(m_settingsValues->Lookup(fullKey))->GetSingle(); - } - return defaultValue; -} - -XMFLOAT3 PersistentState::LoadXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 defaultValue) -{ - XMFLOAT3 value; - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - Platform::Array^ array3; - safe_cast(m_settingsValues->Lookup(fullKey))->GetSingleArray(&array3); - value.x = array3[0]; - value.y = array3[1]; - value.z = array3[2]; - return value; - } - return defaultValue; -} - -Platform::String^ PersistentState::LoadString(Platform::String^ key, Platform::String^ defaultValue) -{ - Platform::String^ fullKey = Platform::String::Concat(m_keyName, key); - if (m_settingsValues->HasKey(fullKey)) - { - return safe_cast(m_settingsValues->Lookup(fullKey))->GetString(); - } - return defaultValue; -} diff --git a/DirectXSceneStore/Common/PersistentState.h b/DirectXSceneStore/Common/PersistentState.h deleted file mode 100644 index 4cb0591..0000000 --- a/DirectXSceneStore/Common/PersistentState.h +++ /dev/null @@ -1,36 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// A simple helper class that provides support for saving and loading various -// data types to an IPropertySet. Used by DirectX SDK samples to implement -// process lifetime management (PLM). -ref class PersistentState -{ -internal: - void Initialize( - _In_ Windows::Foundation::Collections::IPropertySet^ settingsValues, - _In_ Platform::String^ key - ); - - void SaveBool(Platform::String^ key, bool value); - void SaveInt32(Platform::String^ key, int value); - void SaveSingle(Platform::String^ key, float value); - void SaveXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 value); - void SaveString(Platform::String^ key, Platform::String^ string); - - bool LoadBool(Platform::String^ key, bool defaultValue); - int LoadInt32(Platform::String^ key, int defaultValue); - float LoadSingle(Platform::String^ key, float defaultValue); - DirectX::XMFLOAT3 LoadXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 defaultValue); - Platform::String^ LoadString(Platform::String^ key, Platform::String^ defaultValue); - -private: - Platform::String^ m_keyName; - Windows::Foundation::Collections::IPropertySet^ m_settingsValues; -}; diff --git a/DirectXSceneStore/DirectXSceneStore.sln b/DirectXSceneStore/DirectXSceneStore.sln deleted file mode 100644 index 9985453..0000000 --- a/DirectXSceneStore/DirectXSceneStore.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DirectXSceneStore", "DirectXSceneStore.vcxproj", "{BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|ARM = Debug|ARM - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|ARM = Release|ARM - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Debug|ARM.ActiveCfg = Debug|ARM - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Debug|ARM.Build.0 = Debug|ARM - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Debug|Win32.ActiveCfg = Debug|x64 - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Debug|Win32.Build.0 = Debug|x64 - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Debug|x64.ActiveCfg = Debug|x64 - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Debug|x64.Build.0 = Debug|x64 - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Release|ARM.ActiveCfg = Release|ARM - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Release|ARM.Build.0 = Release|ARM - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Release|Win32.ActiveCfg = Release|Win32 - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Release|Win32.Build.0 = Release|Win32 - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Release|x64.ActiveCfg = Release|x64 - {BAEE9C43-2161-4B24-BDEE-A00CEAFF7F09}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/DirectXSceneStore/DirectXSceneStore.vcxproj b/DirectXSceneStore/DirectXSceneStore.vcxproj deleted file mode 100644 index 85c8a23..0000000 --- a/DirectXSceneStore/DirectXSceneStore.vcxproj +++ /dev/null @@ -1,475 +0,0 @@ - - - - - Debug - ARM - - - Debug - Win32 - - - Debug - x64 - - - Release - ARM - - - Release - Win32 - - - Release - x64 - - - - {baee9c43-2161-4b24-bdee-a00ceaff7f09} - Win32Proj - DirectXSceneStore - DirectXSceneStore - en-US - 12.0 - true - Windows Store - 8.1 - - - - DynamicLibrary - true - v120 - - - DynamicLibrary - true - v120 - - - DynamicLibrary - true - v120 - - - DynamicLibrary - false - true - v120 - - - DynamicLibrary - false - true - v120 - - - DynamicLibrary - false - true - v120 - - - - - - - - - - - - - - - - - - - - - - - - false - - - false - - - false - - - false - - - false - - - false - - - - Use - _WINRT_DLL;%(PreprocessorDefinitions) - pch.h - $(IntDir)$(TargetName).pch - $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories) - /bigobj %(AdditionalOptions) - 28204 - $(ProjectDir);$(IntermediateOutputPath);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories) - - - Console - d2d1.lib; d3d11.lib; dxgi.lib; dwrite.lib; dxguid.lib; xaudio2.lib; xinput.lib; mfcore.lib; mfplat.lib; mfreadwrite.lib; mfuuid.lib; %(AdditionalDependencies) - false - - - - - Use - _WINRT_DLL;NDEBUG;%(PreprocessorDefinitions) - pch.h - $(IntDir)$(TargetName).pch - $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories) - /bigobj %(AdditionalOptions) - 28204 - $(ProjectDir);$(IntermediateOutputPath);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories) - - - Console - d2d1.lib; d3d11.lib; dxgi.lib; dwrite.lib; dxguid.lib; xaudio2.lib; xinput.lib; mfcore.lib; mfplat.lib; mfreadwrite.lib; mfuuid.lib; %(AdditionalDependencies) - false - - - - - Use - _WINRT_DLL;%(PreprocessorDefinitions) - pch.h - $(IntDir)$(TargetName).pch - $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories) - /bigobj %(AdditionalOptions) - 28204 - $(ProjectDir);$(IntermediateOutputPath);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories) - - - Console - d2d1.lib; d3d11.lib; dxgi.lib; dwrite.lib; dxguid.lib; xaudio2.lib; xinput.lib; mfcore.lib; mfplat.lib; mfreadwrite.lib; mfuuid.lib; %(AdditionalDependencies) - false - - - - - Use - _WINRT_DLL;NDEBUG;%(PreprocessorDefinitions) - pch.h - $(IntDir)$(TargetName).pch - $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories) - /bigobj %(AdditionalOptions) - 28204 - $(ProjectDir);$(IntermediateOutputPath);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories) - - - Console - d2d1.lib; d3d11.lib; dxgi.lib; dwrite.lib; dxguid.lib; xaudio2.lib; xinput.lib; mfcore.lib; mfplat.lib; mfreadwrite.lib; mfuuid.lib; %(AdditionalDependencies) - false - - - - - Use - _WINRT_DLL;%(PreprocessorDefinitions) - pch.h - $(IntDir)$(TargetName).pch - $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories) - /bigobj %(AdditionalOptions) - 28204 - $(ProjectDir);$(IntermediateOutputPath);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories) - - - Console - d2d1.lib; d3d11.lib; dxgi.lib; dwrite.lib; dxguid.lib; xaudio2.lib; xinput.lib; mfcore.lib; mfplat.lib; mfreadwrite.lib; mfuuid.lib; %(AdditionalDependencies) - false - - - - - Use - _WINRT_DLL;NDEBUG;%(PreprocessorDefinitions) - pch.h - $(IntDir)$(TargetName).pch - $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories) - /bigobj %(AdditionalOptions) - 28204 - $(ProjectDir);$(IntermediateOutputPath);$(GeneratedFilesDir);$(IntDir);%(AdditionalIncludeDirectories) - - - Console - d2d1.lib; d3d11.lib; dxgi.lib; dwrite.lib; dxguid.lib; xaudio2.lib; xinput.lib; mfcore.lib; mfplat.lib; mfreadwrite.lib; mfuuid.lib; %(AdditionalDependencies) - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ScenePanel.xaml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create - Create - Create - Create - Create - Create - - - - ScenePanel.xaml - - - - - - true - true - true - true - true - true - - - - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - true - true - true - true - true - true - - - - - - - - - - - - - - Document - true - true - true - true - true - true - - - Document - true - true - true - true - true - true - - - - - Pixel - Pixel - Pixel - Pixel - Pixel - Pixel - - - Pixel - Pixel - Pixel - Pixel - Pixel - Pixel - - - Vertex - Vertex - Vertex - Vertex - Vertex - Vertex - - - Vertex - Vertex - Vertex - Vertex - Vertex - Vertex - - - - - - \ No newline at end of file diff --git a/DirectXSceneStore/DirectXSceneStore.vcxproj.filters b/DirectXSceneStore/DirectXSceneStore.vcxproj.filters deleted file mode 100644 index b4b8e65..0000000 --- a/DirectXSceneStore/DirectXSceneStore.vcxproj.filters +++ /dev/null @@ -1,330 +0,0 @@ - - - - - 21130433-2975-4432-9fdd-ecb71e7cdec2 - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tga;tiff;tif;png;wav;mfcribbon-ms - - - {b7366082-85f1-4a16-95c2-96f656e6fe3a} - - - {9d62ba3b-6f8e-4926-8db5-7cc696190e3c} - - - {b77004f0-7782-4dd9-9bed-2c71fbebab1e} - - - {5cf92ed1-736d-4069-a52f-7b9643ebcc24} - - - {81e6d1b4-3095-4975-a0c7-d2c53e97675f} - - - {aa54b69e-35ea-482b-8782-580551d1d3b7} - - - {bec36483-b299-44ba-834b-f41cdc262dd1} - - - {015bb0c6-6ec5-415d-964c-cb55e8878aae} - - - {0871943c-b4eb-45f6-8310-4b78f329039c} - - - - - - - Audio - - - Audio - - - Audio - - - GameLevels - - - GameLevels - - - GameObjects - - - GameObjects - - - GameObjects - - - GameObjects - - - GameObjects - - - GameObjects - - - Input - - - Meshes - - - Meshes - - - Meshes - - - Meshes - - - Meshes - - - Rendering - - - Rendering - - - Rendering - - - Rendering - - - Rendering - - - Rendering - - - Utilities - - - Utilities - - - Utilities - - - Utilities - - - Utilities - - - - - - - - - - - - Audio - - - Audio - - - Audio - - - GameLevels - - - GameLevels - - - GameObjects - - - GameObjects - - - GameObjects - - - GameObjects - - - GameObjects - - - GameObjects - - - GameObjects - - - Input - - - Meshes - - - Meshes - - - Meshes - - - Meshes - - - Meshes - - - Rendering - - - Rendering - - - Rendering - - - Rendering - - - Rendering - - - Rendering - - - Rendering - - - Utilities - - - Utilities - - - Utilities - - - Utilities - - - Utilities - - - Utilities - - - Utilities - - - Utilities - - - - - - - - - - - - - - - - Assets - - - Assets - - - Assets - - - Assets - - - Assets - - - Assets - - - Assets - - - Assets - - - Assets - - - - - Shaders - - - Shaders - - - Shaders - - - Shaders - - - - - Shaders - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - Resources - - - \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Animate.cpp b/DirectXSceneStore/GameContent/Animate.cpp deleted file mode 100644 index 290f8d2..0000000 --- a/DirectXSceneStore/GameContent/Animate.cpp +++ /dev/null @@ -1,308 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Animate.h" - -using namespace DirectX; - -//---------------------------------------------------------------------- - -Animate::Animate(): - m_continuous(false), - m_startTime(0.0f), - m_duration(10.0f) -{ -} - -//---------------------------------------------------------------------- - -float Animate::Start() -{ - return m_startTime; -} - -//---------------------------------------------------------------------- - -void Animate::Start(_In_ float start) -{ - m_startTime = start; -} - -//---------------------------------------------------------------------- - -float Animate::Duration() -{ - return m_duration; -} - -//---------------------------------------------------------------------- - -void Animate::Duration(_In_ float duration) -{ - m_duration = duration; -} - -//---------------------------------------------------------------------- - -bool Animate::Continuous() -{ - return m_continuous; -} - -//---------------------------------------------------------------------- - -void Animate::Continuous(_In_ bool continuous) -{ - m_continuous = continuous; -} - -//---------------------------------------------------------------------- - -AnimateLinePosition::AnimateLinePosition( - _In_ XMFLOAT3 startPosition, - _In_ XMFLOAT3 endPosition, - _In_ float duration, - _In_ bool continuous) -{ - m_startPosition = startPosition; - m_endPosition = endPosition; - m_duration = duration; - m_continuous = continuous; - - m_length = XMVectorGetX( - XMVector3Length(XMLoadFloat3(&endPosition) - XMLoadFloat3(&startPosition)) - ); -} - -//---------------------------------------------------------------------- - -XMFLOAT3 AnimateLinePosition::Evaluate(_In_ float t) -{ - if (t <= m_startTime) - { - return m_startPosition; - } - - if ((t >= (m_startTime + m_duration)) && !m_continuous) - { - return m_endPosition; - } - - float startTime = m_startTime; - if (m_continuous) - { - // For continuous operation move the start time forward to - // eliminate previous iterations. - startTime += ((int)((t - m_startTime) / m_duration)) * m_duration; - } - - float u = (t - startTime) / m_duration; - XMFLOAT3 currentPosition; - currentPosition.x = m_startPosition.x + (m_endPosition.x - m_startPosition.x)*u; - currentPosition.y = m_startPosition.y + (m_endPosition.y - m_startPosition.y)*u; - currentPosition.z = m_startPosition.z + (m_endPosition.z - m_startPosition.z)*u; - - return currentPosition; -} - -//---------------------------------------------------------------------- - -AnimateLineListPosition::AnimateLineListPosition( - _In_ unsigned int count, - _In_reads_(count) XMFLOAT3 position[], - _In_ float duration, - _In_ bool continuous) -{ - m_duration = duration; - m_continuous = continuous; - m_count = count; - - std::vector segment(m_count); - m_segment = segment; - m_totalLength = 0.0f; - - m_segment[0].position = position[0]; - for (unsigned int i = 1; i < count; i++) - { - m_segment[i].position = position[i]; - m_segment[i - 1].length = XMVectorGetX( - XMVector3Length( - XMLoadFloat3(&m_segment[i].position) - - XMLoadFloat3(&m_segment[i - 1].position) - ) - ); - m_totalLength += m_segment[i - 1].length; - } - - // Parameterize the segments to ensure uniform evaluation along the path. - float u = 0.0f; - for (unsigned int i = 0; i < (count - 1); i++) - { - m_segment[i].uStart = u; - m_segment[i].uLength = (m_segment[i].length / m_totalLength); - u += m_segment[i].uLength; - } - m_segment[count-1].uStart = 1.0f; -} - -//---------------------------------------------------------------------- - -XMFLOAT3 AnimateLineListPosition::Evaluate(_In_ float t) -{ - if (t <= m_startTime) - { - return m_segment[0].position; - } - - if ((t >= (m_startTime + m_duration)) && !m_continuous) - { - return m_segment[m_count-1].position; - } - - float startTime = m_startTime; - if (m_continuous) - { - // For continuous operation move the start time forward to - // eliminate previous iterations. - startTime += ((int)((t - m_startTime) / m_duration)) * m_duration; - } - - float u = (t - startTime) / m_duration; - // Find the right segment. - unsigned int i = 0; - while (u > m_segment[i + 1].uStart) - { - i++; - } - - u -= m_segment[i].uStart; - u /= m_segment[i].uLength; - - XMFLOAT3 currentPosition; - currentPosition.x = m_segment[i].position.x + (m_segment[i + 1].position.x - m_segment[i].position.x)*u; - currentPosition.y = m_segment[i].position.y + (m_segment[i + 1].position.y - m_segment[i].position.y)*u; - currentPosition.z = m_segment[i].position.z + (m_segment[i + 1].position.z - m_segment[i].position.z)*u; - - return currentPosition; -} - -//---------------------------------------------------------------------- - -AnimateCirclePosition:: AnimateCirclePosition( - _In_ XMFLOAT3 center, - _In_ XMFLOAT3 startPosition, - _In_ XMFLOAT3 planeNormal, - _In_ float duration, - _In_ bool continuous, - _In_ bool clockwise) -{ - m_center = center; - m_planeNormal = planeNormal; - m_startPosition = startPosition; - m_duration = duration; - m_continuous = continuous; - m_clockwise = clockwise; - - XMVECTOR coordX = XMLoadFloat3(&m_startPosition) - XMLoadFloat3(&m_center); - m_radius = XMVectorGetX(XMVector3Length(coordX)); - - XMVector3Normalize(coordX); - - XMVECTOR coordZ = XMLoadFloat3(&m_planeNormal); - XMVector3Normalize(coordZ); - - XMVECTOR coordY; - if (m_clockwise) - { - coordY = XMVector3Cross(coordZ, coordX); - } - else - { - coordY = XMVector3Cross(coordX, coordZ); - } - - XMVECTOR vectorX = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f); - XMVECTOR vectorY = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f); - XMMATRIX mat1 = XMMatrixIdentity(); - XMMATRIX mat2 = XMMatrixIdentity(); - - if (!XMVector3Equal(coordX, vectorX)) - { - float angle; - angle = XMVectorGetX( - XMVector3AngleBetweenVectors(vectorX, coordX) - ); - if ((angle * angle) > 0.025) - { - XMVECTOR axis1 = XMVector3Cross(vectorX, coordX); - - mat1 = XMMatrixRotationAxis(axis1, angle); - vectorY = XMVector3TransformCoord(vectorY, mat1); - } - } - if (!XMVector3Equal(vectorY, coordY)) - { - float angle; - angle = XMVectorGetX( - XMVector3AngleBetweenVectors(vectorY, coordY) - ); - if ((angle * angle) > 0.025) - { - XMVECTOR axis2 = XMVector3Cross(vectorY, coordY); - mat2 = XMMatrixRotationAxis(axis2, angle); - } - } - XMStoreFloat4x4( - &m_rotationMatrix, - mat1 * - mat2 * - XMMatrixTranslation(m_center.x, m_center.y, m_center.z) - ); -} - -//---------------------------------------------------------------------- - -XMFLOAT3 AnimateCirclePosition::Evaluate(_In_ float t) -{ - if (t <= m_startTime) - { - return m_startPosition; - } - - if ((t >= (m_startTime + m_duration)) && !m_continuous) - { - return m_startPosition; - } - - float startTime = m_startTime; - if (m_continuous) - { - // For continuous operation move the start time forward to - // eliminate previous iterations. - startTime += ((int)((t - m_startTime) / m_duration)) * m_duration; - } - - float u = (t - startTime) / m_duration * XM_2PI; - - XMFLOAT3 currentPosition; - currentPosition.x = m_radius * cos(u); - currentPosition.y = m_radius * sin(u); - currentPosition.z = 0.0f; - - XMStoreFloat3( - ¤tPosition, - XMVector3TransformCoord( - XMLoadFloat3(¤tPosition), - XMLoadFloat4x4(&m_rotationMatrix) - ) - ); - - return currentPosition; -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/Animate.h b/DirectXSceneStore/GameContent/Animate.h deleted file mode 100644 index 102f777..0000000 --- a/DirectXSceneStore/GameContent/Animate.h +++ /dev/null @@ -1,135 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Animate: -// This is an abstract class for animations. It defines a set of -// capabilities for animating XMFLOAT3 variables. An animation has the following -// characteristics: -// Start - the time for the animation to start. -// Duration - the length of time the animation is to run. -// Continuous - whether the animation loops after duration is reached or just -// stops. -// There are two query functions: -// IsActive - determines if the animation is active at time t. -// IsFinished - determines if the animation is done at time t. -// It is expected that each derived class will provide an Evaluate method for the -// specific kind of animation. - -ref class Animate abstract -{ -internal: - Animate(); - - virtual DirectX::XMFLOAT3 Evaluate (_In_ float t) = 0; - - bool IsActive(_In_ float t) { return ((t >= m_startTime) && (m_continuous || (t < (m_startTime + m_duration)))); }; - bool IsFinished(_In_ float t) { return (!m_continuous && (t >= (m_startTime + m_duration))); } - float Start(); - void Start(_In_ float start); - float Duration(); - void Duration(_In_ float duration); - bool Continuous(); - void Continuous(_In_ bool continuous); - -protected private: - bool m_continuous; // if true means at end cycle back to beginning - float m_startTime; // time at which animation begins - float m_duration; // for continuous this is the duration of 1 cycle through path -}; - -//---------------------------------------------------------------------- - -// AnimateLinePosition: -// This class is a specialization of Animate that defines an animation of a position vector -// along a straight line defined in world coordinates from startPosition to endPosition. - -ref class AnimateLinePosition: public Animate -{ -internal: - AnimateLinePosition( - _In_ DirectX::XMFLOAT3 startPosition, - _In_ DirectX::XMFLOAT3 endPosition, - _In_ float duration, - _In_ bool continuous - ); - virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override; - -private: - DirectX::XMFLOAT3 m_startPosition; - DirectX::XMFLOAT3 m_endPosition; - float m_length; -}; - -//---------------------------------------------------------------------- - -struct LineSegment -{ - DirectX::XMFLOAT3 position; - float length; - float uStart; - float uLength; -}; - -// AnimateLineListPosition: -// This class is a specialization of Animate that defines an animation of a position vector -// along a set of line segments defined by a set of points. The animation along the path is -// such that the evaluation of the position along the path will be uniform independent of -// the length of each of the line segments. A continuous loop can be achieved by having the -// first and last points of the list be the same. - -ref class AnimateLineListPosition: public Animate -{ -internal: - AnimateLineListPosition( - _In_ unsigned int count, - _In_reads_(count) DirectX::XMFLOAT3 position[], - _In_ float duration, - _In_ bool continuous - ); - virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override; - -private: - unsigned int m_count; - float m_totalLength; - std::vector m_segment; -}; - -//---------------------------------------------------------------------- - -// AnimateCirclePosition: -// This class is a specialization of Animate that defines an animation of a position vector -// along a circular path centered at 'center' with a starting point of 'startPosition'. The -// distance between 'center' and 'startPosition' defines the radius of the circle. The plane -// of the circle will pass through 'center' and 'startPosition' and have a normal of 'planeNormal'. -// The direction of the animation can be either clockwise or counterclockwise based -// on the 'clockwise' parameter. - -ref class AnimateCirclePosition: public Animate -{ -internal: - AnimateCirclePosition( - _In_ DirectX::XMFLOAT3 center, - _In_ DirectX::XMFLOAT3 startPosition, - _In_ DirectX::XMFLOAT3 planeNormal, - _In_ float duration, - _In_ bool continuous, - _In_ bool clockwise - ); - virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override; - -private: - DirectX::XMFLOAT4X4 m_rotationMatrix; - DirectX::XMFLOAT3 m_center; - DirectX::XMFLOAT3 m_planeNormal; - DirectX::XMFLOAT3 m_startPosition; - float m_radius; - bool m_clockwise; -}; - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/Audio.cpp b/DirectXSceneStore/GameContent/Audio.cpp deleted file mode 100644 index 8a398c3..0000000 --- a/DirectXSceneStore/GameContent/Audio.cpp +++ /dev/null @@ -1,92 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Audio.h" -#include "Common\DirectXSample.h" - -using namespace Microsoft::WRL; -using namespace Windows::Foundation; -using namespace Windows::UI::Core; -using namespace Windows::Graphics::Display; - -Audio::Audio(): - m_audioAvailable(false) -{ -} - -void Audio::Initialize() -{ -} - -void Audio::CreateDeviceIndependentResources() -{ - UINT32 flags = 0; - - DX::ThrowIfFailed( - XAudio2Create(&m_musicEngine, flags) - ); - -#if defined(_DEBUG) - XAUDIO2_DEBUG_CONFIGURATION debugConfiguration = {0}; - debugConfiguration.BreakMask = XAUDIO2_LOG_ERRORS; - debugConfiguration.TraceMask = XAUDIO2_LOG_ERRORS; - m_musicEngine->SetDebugConfiguration(&debugConfiguration); -#endif - - - HRESULT hr = m_musicEngine->CreateMasteringVoice(&m_musicMasteringVoice); - if (FAILED(hr)) - { - // Unable to create an audio device - m_audioAvailable = false; - return; - } - - DX::ThrowIfFailed( - XAudio2Create(&m_soundEffectEngine, flags) - ); - -#if defined(_DEBUG) - m_soundEffectEngine->SetDebugConfiguration(&debugConfiguration); -#endif - - DX::ThrowIfFailed( - m_soundEffectEngine->CreateMasteringVoice(&m_soundEffectMasteringVoice) - ); - - m_audioAvailable = true; -} - -IXAudio2* Audio::MusicEngine() -{ - return m_musicEngine.Get(); -} - -IXAudio2* Audio::SoundEffectEngine() -{ - return m_soundEffectEngine.Get(); -} - -void Audio::SuspendAudio() -{ - if (m_audioAvailable) - { - m_musicEngine->StopEngine(); - m_soundEffectEngine->StopEngine(); - } -} - -void Audio::ResumeAudio() -{ - if (m_audioAvailable) - { - DX::ThrowIfFailed(m_musicEngine->StartEngine()); - DX::ThrowIfFailed(m_soundEffectEngine->StartEngine()); - } -} - diff --git a/DirectXSceneStore/GameContent/Audio.h b/DirectXSceneStore/GameContent/Audio.h deleted file mode 100644 index 8a5c335..0000000 --- a/DirectXSceneStore/GameContent/Audio.h +++ /dev/null @@ -1,35 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Audio: -// This class uses XAudio2 to provide sound output. It creates two -// engines - one for music and the other for sound effects - each as -// a separate mastering voice. -// The SuspendAudio and ResumeAudio methods can be used to stop -// and start all audio playback. - -ref class Audio -{ -internal: - Audio(); - - void Initialize(); - void CreateDeviceIndependentResources(); - IXAudio2* MusicEngine(); - IXAudio2* SoundEffectEngine(); - void SuspendAudio(); - void ResumeAudio(); - -protected private: - bool m_audioAvailable; - Microsoft::WRL::ComPtr m_musicEngine; - Microsoft::WRL::ComPtr m_soundEffectEngine; - IXAudio2MasteringVoice* m_musicMasteringVoice; - IXAudio2MasteringVoice* m_soundEffectMasteringVoice; -}; diff --git a/DirectXSceneStore/GameContent/Camera.cpp b/DirectXSceneStore/GameContent/Camera.cpp deleted file mode 100644 index b689e27..0000000 --- a/DirectXSceneStore/GameContent/Camera.cpp +++ /dev/null @@ -1,217 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Camera.h" -#include "StereoProjection.h" - -using namespace DirectX; - -#undef min // Use __min instead. -#undef max // Use __max instead. - -//-------------------------------------------------------------------------------------- - -Camera::Camera() -{ - // Setup the view matrix. - SetViewParams( - XMFLOAT3(0.0f, 0.0f, 0.0f), // Default eye position. - XMFLOAT3(0.0f, 0.0f, 1.0f), // Default look at position. - XMFLOAT3(0.0f, 1.0f, 0.0f) // Default up vector. - ); - - // Setup the projection matrix. - SetProjParams(XM_PI / 4, 1.0f, 1.0f, 1000.0f); -} - -//-------------------------------------------------------------------------------------- - -void Camera::LookDirection (_In_ XMFLOAT3 lookDirection) -{ - XMFLOAT3 lookAt; - lookAt.x = m_eye.x + lookDirection.x; - lookAt.y = m_eye.y + lookDirection.y; - lookAt.z = m_eye.z + lookDirection.z; - - SetViewParams(m_eye, lookAt, m_up); -} - -//-------------------------------------------------------------------------------------- - -void Camera::Eye(_In_ XMFLOAT3 eye) -{ - SetViewParams(eye, m_lookAt, m_up); -} - -//-------------------------------------------------------------------------------------- - -void Camera::SetViewParams( - _In_ XMFLOAT3 eye, - _In_ XMFLOAT3 lookAt, - _In_ XMFLOAT3 up - ) -{ - m_eye = eye; - m_lookAt = lookAt; - m_up = up; - - // Calculate the view matrix. - XMMATRIX view = XMMatrixLookAtLH( - XMLoadFloat3(&m_eye), - XMLoadFloat3(&m_lookAt), - XMLoadFloat3(&m_up) - ); - - XMVECTOR det; - XMMATRIX inverseView = XMMatrixInverse(&det, view); - XMStoreFloat4x4(&m_viewMatrix, view); - XMStoreFloat4x4(&m_inverseView, inverseView); - - // The axis basis vectors and camera position are stored inside the - // position matrix in the 4 rows of the camera's world matrix. - // To figure out the yaw/pitch of the camera, we just need the Z basis vector. - XMFLOAT3 zBasis; - XMStoreFloat3(&zBasis, inverseView.r[2]); - - m_cameraYawAngle = atan2f(zBasis.x, zBasis.z); - - float len = sqrtf(zBasis.z * zBasis.z + zBasis.x * zBasis.x); - m_cameraPitchAngle = atan2f(zBasis.y, len); -} - -//-------------------------------------------------------------------------------------- - -void Camera::SetProjParams( - _In_ float fieldOfView, - _In_ float aspectRatio, - _In_ float nearPlane, - _In_ float farPlane - ) -{ - // Set attributes for the projection matrix. - m_fieldOfView = fieldOfView; - m_aspectRatio = aspectRatio; - m_nearPlane = nearPlane; - m_farPlane = farPlane; - XMStoreFloat4x4( - &m_projectionMatrix, - XMMatrixPerspectiveFovLH( - m_fieldOfView, - m_aspectRatio, - m_nearPlane, - m_farPlane - ) - ); - - STEREO_PARAMETERS* stereoParams = nullptr; - // Update the projection matrix. - XMStoreFloat4x4( - &m_projectionMatrixLeft, - MatrixStereoProjectionFovLH( - stereoParams, - STEREO_CHANNEL::LEFT, - m_fieldOfView, - m_aspectRatio, - m_nearPlane, - m_farPlane, - STEREO_MODE::NORMAL - ) - ); - - XMStoreFloat4x4( - &m_projectionMatrixRight, - MatrixStereoProjectionFovLH( - stereoParams, - STEREO_CHANNEL::RIGHT, - m_fieldOfView, - m_aspectRatio, - m_nearPlane, - m_farPlane, - STEREO_MODE::NORMAL - ) - ); -} - -//-------------------------------------------------------------------------------------- - -DirectX::XMMATRIX Camera::View() -{ - return XMLoadFloat4x4(&m_viewMatrix); -} - -//-------------------------------------------------------------------------------------- - -DirectX::XMMATRIX Camera::Projection() -{ - return XMLoadFloat4x4(&m_projectionMatrix); -} - -//-------------------------------------------------------------------------------------- - -DirectX::XMMATRIX Camera::LeftEyeProjection() -{ - return XMLoadFloat4x4(&m_projectionMatrixLeft); -} - -//-------------------------------------------------------------------------------------- - -DirectX::XMMATRIX Camera::RightEyeProjection() -{ - return XMLoadFloat4x4(&m_projectionMatrixRight); -} - -//-------------------------------------------------------------------------------------- - -DirectX::XMMATRIX Camera::World() -{ - return XMLoadFloat4x4(&m_inverseView); -} - -//-------------------------------------------------------------------------------------- - -DirectX::XMFLOAT3 Camera::Eye() -{ - return m_eye; -} - -//-------------------------------------------------------------------------------------- - -DirectX::XMFLOAT3 Camera::LookAt() -{ - return m_lookAt; -} - -//-------------------------------------------------------------------------------------- - -float Camera::NearClipPlane() -{ - return m_nearPlane; -} - -//-------------------------------------------------------------------------------------- - -float Camera::FarClipPlane() -{ - return m_farPlane; -} - -//-------------------------------------------------------------------------------------- - -float Camera::Pitch() -{ - return m_cameraPitchAngle; -} - -//-------------------------------------------------------------------------------------- - -float Camera::Yaw() -{ - return m_cameraYawAngle; -} - -//-------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Camera.h b/DirectXSceneStore/GameContent/Camera.h deleted file mode 100644 index 7d9ca7b..0000000 --- a/DirectXSceneStore/GameContent/Camera.h +++ /dev/null @@ -1,57 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Camera: -// This class defines the position, orientation and viewing frustum of a camera looking into -// a 3D world. It will generate both the View matrix and Projection matrix. It can also -// provide a pair of Projection matrices to be used when stereoscopic 3D is used. - -ref class Camera -{ -internal: - Camera(); - - void SetViewParams(_In_ DirectX::XMFLOAT3 eye, _In_ DirectX::XMFLOAT3 lookAt, _In_ DirectX::XMFLOAT3 up); - void SetProjParams(_In_ float fieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane); - - void LookDirection (_In_ DirectX::XMFLOAT3 lookDirection); - void Eye (_In_ DirectX::XMFLOAT3 position); - - DirectX::XMMATRIX View(); - DirectX::XMMATRIX Projection(); - DirectX::XMMATRIX LeftEyeProjection(); - DirectX::XMMATRIX RightEyeProjection(); - DirectX::XMMATRIX World(); - DirectX::XMFLOAT3 Eye(); - DirectX::XMFLOAT3 LookAt(); - DirectX::XMFLOAT3 Up(); - float NearClipPlane(); - float FarClipPlane(); - float Pitch(); - float Yaw(); - -protected private: - DirectX::XMFLOAT4X4 m_viewMatrix; - DirectX::XMFLOAT4X4 m_projectionMatrix; - DirectX::XMFLOAT4X4 m_projectionMatrixLeft; - DirectX::XMFLOAT4X4 m_projectionMatrixRight; - - DirectX::XMFLOAT4X4 m_inverseView; - - DirectX::XMFLOAT3 m_eye; - DirectX::XMFLOAT3 m_lookAt; - DirectX::XMFLOAT3 m_up; - float m_cameraYawAngle; - float m_cameraPitchAngle; - - float m_fieldOfView; - float m_aspectRatio; - float m_nearPlane; - float m_farPlane; -}; diff --git a/DirectXSceneStore/GameContent/ConstantBuffers.h b/DirectXSceneStore/GameContent/ConstantBuffers.h deleted file mode 100644 index 908be16..0000000 --- a/DirectXSceneStore/GameContent/ConstantBuffers.h +++ /dev/null @@ -1,48 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -struct PNTVertex -{ - DirectX::XMFLOAT3 position; - DirectX::XMFLOAT3 normal; - DirectX::XMFLOAT2 textureCoordinate; -}; - -static D3D11_INPUT_ELEMENT_DESC PNTVertexLayout[] = -{ - {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0}, -}; - -struct ConstantBufferNeverChanges -{ - DirectX::XMFLOAT4 lightPosition[4]; - DirectX::XMFLOAT4 lightColor; -}; - -struct ConstantBufferChangeOnResize -{ - DirectX::XMFLOAT4X4 projection; -}; - -struct ConstantBufferChangesEveryFrame -{ - DirectX::XMFLOAT4X4 view; -}; - -struct ConstantBufferChangesEveryPrim -{ - DirectX::XMFLOAT4X4 worldMatrix; - DirectX::XMFLOAT4 meshColor; - DirectX::XMFLOAT4 diffuseColor; - DirectX::XMFLOAT4 specularColor; - float specularPower; -}; - diff --git a/DirectXSceneStore/GameContent/ConstantBuffers.hlsli b/DirectXSceneStore/GameContent/ConstantBuffers.hlsli deleted file mode 100644 index e913283..0000000 --- a/DirectXSceneStore/GameContent/ConstantBuffers.hlsli +++ /dev/null @@ -1,60 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -Texture2D diffuseTexture : register(t0); -SamplerState linearSampler : register(s0); - -cbuffer ConstantBufferNeverChanges : register(b0) -{ - float4 lightPosition[4]; - float4 lightColor; -} - -cbuffer ConstantBufferChangeOnResize : register(b1) -{ - matrix projection; -}; - -cbuffer ConstantBufferChangesEveryFrame : register(b2) -{ - matrix view; -}; - -cbuffer ConstantBufferChangesEveryPrim : register (b3) -{ - matrix world; - float4 meshColor; - float4 diffuseColor; - float4 specularColor; - float specularExponent; -}; - -struct VertextShaderInput -{ - float4 position : POSITION; - float4 normal : NORMAL; - float2 textureUV : TEXCOORD0; -}; - -struct PixelShaderInput -{ - float4 position : SV_POSITION; - float2 textureUV : TEXCOORD0; - float3 vertexToEye : TEXCOORD1; - float3 normal : TEXCOORD2; - float3 vertexToLight0 : TEXCOORD3; - float3 vertexToLight1 : TEXCOORD4; - float3 vertexToLight2 : TEXCOORD5; - float3 vertexToLight3 : TEXCOORD6; -}; - -struct PixelShaderFlatInput -{ - float4 position : SV_POSITION; - float2 textureUV : TEXCOORD0; - float4 diffuseColor : TEXCOORD1; -}; diff --git a/DirectXSceneStore/GameContent/Cylinder.cpp b/DirectXSceneStore/GameContent/Cylinder.cpp deleted file mode 100644 index a883de5..0000000 --- a/DirectXSceneStore/GameContent/Cylinder.cpp +++ /dev/null @@ -1,136 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Cylinder.h" - -using namespace DirectX; - -//---------------------------------------------------------------------- - -Cylinder::Cylinder() -{ - Initialize(XMFLOAT3(0.0f, 0.0f, 0.0f), 1.0f, XMFLOAT3(0.0f, 0.0f, 1.0f)); -} - -//---------------------------------------------------------------------- - -Cylinder::Cylinder( - XMFLOAT3 position, - float radius, - XMFLOAT3 direction - ) -{ - Initialize(position, radius, direction); -} - -//---------------------------------------------------------------------- - -void Cylinder::Initialize( - XMFLOAT3 position, - float radius, - XMFLOAT3 direction - ) -{ - m_position = position; - m_radius = radius; - m_length = XMVectorGetX(XMVector3Length(XMLoadFloat3(&direction))); - XMStoreFloat3(&m_axis, XMVector3Normalize(XMLoadFloat3(&direction))); - - XMVECTOR up = XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f); - float angle1 = XMVectorGetX( - XMVector3AngleBetweenVectors(up, XMLoadFloat3(&m_axis)) - ); - - XMMATRIX mat1 = XMMatrixIdentity(); - - if ((angle1 * angle1) > 0.025) - { - XMVECTOR axis1 = XMVector3Cross(up, XMLoadFloat3(&m_axis)); - - mat1 = XMMatrixRotationAxis(axis1, angle1); - } - XMStoreFloat4x4(&m_rotationMatrix, mat1); - - XMStoreFloat4x4( - &m_modelMatrix, - XMMatrixScaling(m_radius, m_radius, m_length) * - mat1 * - XMMatrixTranslation(m_position.x, m_position.y, m_position.z) - ); -} - -//-------------------------------------------------------------------------------- - -void Cylinder::UpdatePosition() -{ - XMStoreFloat4x4( - &m_modelMatrix, - XMMatrixScaling(m_radius, m_radius, m_length) * - XMLoadFloat4x4(&m_rotationMatrix) * - XMMatrixTranslation(m_position.x, m_position.y, m_position.z) - ); -} - -//-------------------------------------------------------------------------------- - -bool Cylinder::IsTouching( - XMFLOAT3 point, - float radius, - _Out_ XMFLOAT3 *contact, - _Out_ XMFLOAT3 *normal - ) -{ - XMVECTOR p0; - XMVECTOR axis; - XMVECTOR p1; - XMVECTOR px; - - // Determine if a point is within radius distance of the cylinder and - // return the point of contact (projection of the point onto the cylinder). - - p0 = XMLoadFloat3(&m_position); - axis = XMLoadFloat3(&m_axis); - p1 = p0 + axis * m_length; - px = XMLoadFloat3(&point); - - float dist = XMVectorGetX( - XMVector3LinePointDistance(p0, p1, px) - ); - - // Projection of the point onto the Vector. - float dist2 = XMVectorGetX( - XMVector3Dot(px - p0, axis) - ); - - XMVECTOR ptOnVector = p0 + dist2 * axis; - - XMVECTOR normalVector = XMVector3Normalize(px - ptOnVector); - - XMStoreFloat3(normal, normalVector); - XMStoreFloat3(contact, ptOnVector + normalVector * m_radius); - - if (dist < 0.0f) - { - dist *= -1.0f; - } - - if (dist < (radius + m_radius)) - { - if (dist2 >= 0.0f && dist2 <= m_length) - { - return true; - } - else - { - return false; - } - } - return false; -} - -//-------------------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/Cylinder.h b/DirectXSceneStore/GameContent/Cylinder.h deleted file mode 100644 index 056d849..0000000 --- a/DirectXSceneStore/GameContent/Cylinder.h +++ /dev/null @@ -1,49 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Cylinder: -// This class is a specialization of GameObject that represents a cylinder primitive. -// The cylinder is defined by a vector starting at 'position' and oriented along the -// 'direction' vector. The length of the cylinder is just the length of the 'direction' -// vector. - -#include "GameObject.h" - -ref class Cylinder: public GameObject -{ -internal: - Cylinder(); - Cylinder( - DirectX::XMFLOAT3 position, - float radius, - DirectX::XMFLOAT3 direction - ); - - virtual bool IsTouching( - DirectX::XMFLOAT3 point, - float radius, - _Out_ DirectX::XMFLOAT3 *contact, - _Out_ DirectX::XMFLOAT3 *normal - ) override; - -protected: - virtual void UpdatePosition() override; - -private: - void Initialize( - DirectX::XMFLOAT3 position, - float radius, - DirectX::XMFLOAT3 direction - ); - - DirectX::XMFLOAT3 m_axis; - float m_length; - float m_radius; - DirectX::XMFLOAT4X4 m_rotationMatrix; -}; \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/CylinderMesh.cpp b/DirectXSceneStore/GameContent/CylinderMesh.cpp deleted file mode 100644 index 9a73981..0000000 --- a/DirectXSceneStore/GameContent/CylinderMesh.cpp +++ /dev/null @@ -1,124 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "CylinderMesh.h" -#include "Common\DirectXSample.h" -#include "ConstantBuffers.h" - -using namespace Microsoft::WRL; -using namespace DirectX; - -CylinderMesh::CylinderMesh(_In_ ID3D11Device *device, uint32 segments) -{ - D3D11_BUFFER_DESC bd = {0}; - D3D11_SUBRESOURCE_DATA initData = {0}; - - uint32 numVertices = 6 * (segments + 1) + 1; - uint32 numIndices = 3 * segments * 3 * 2; - - std::vector point(numVertices); - std::vector index(numIndices); - - uint32 p = 0; - // Top center point (multiple points for texture coordinates). - for (uint32 a = 0; a <= segments; a++) - { - point[p].position = XMFLOAT3(0.0f, 0.0f, 1.0f); - point[p].normal = XMFLOAT3(0.0f, 0.0f, 1.0f); - point[p].textureCoordinate = XMFLOAT2(static_cast(a) / static_cast(segments), 0.0f); - p++; - } - // Top edge of cylinder: Normals point up for lighting of top surface. - for (uint32 a = 0; a <= segments; a++) - { - float angle = static_cast(a) / static_cast(segments) * XM_2PI; - point[p].position = XMFLOAT3(cos(angle), sin(angle), 1.0f); - point[p].normal = XMFLOAT3(0.0f, 0.0f, 1.0f); - point[p].textureCoordinate = XMFLOAT2(static_cast(a) / static_cast(segments), 0.0f); - p++; - } - // Top edge of cylinder: Normals point out for lighting of the side surface. - for (uint32 a = 0; a <= segments; a++) - { - float angle = static_cast(a) / static_cast(segments) * XM_2PI; - point[p].position = XMFLOAT3(cos(angle), sin(angle), 1.0f); - point[p].normal = XMFLOAT3(cos(angle), sin(angle), 0.0f); - point[p].textureCoordinate = XMFLOAT2(static_cast(a) / static_cast(segments), 0.0f); - p++; - } - // Bottom edge of cylinder: Normals point out for lighting of the side surface. - for (uint32 a = 0; a <= segments; a++) - { - float angle = static_cast(a) / static_cast(segments) * XM_2PI; - point[p].position = XMFLOAT3(cos(angle), sin(angle), 0.0f); - point[p].normal = XMFLOAT3(cos(angle), sin(angle), 0.0f); - point[p].textureCoordinate = XMFLOAT2(static_cast(a) / static_cast(segments), 1.0f); - p++; - } - // Bottom edge of cylinder: Normals point down for lighting of the bottom surface. - for (uint32 a = 0; a <= segments; a++) - { - float angle = static_cast(a) / static_cast(segments) * XM_2PI; - point[p].position = XMFLOAT3(cos(angle), sin(angle), 0.0f); - point[p].normal = XMFLOAT3(0.0f, 0.0f, -1.0f); - point[p].textureCoordinate = XMFLOAT2(static_cast(a) / static_cast(segments), 1.0f); - p++; - } - // Bottom center of cylinder: Normals point down for lighting on the bottom surface. - for (uint32 a = 0; a <= segments; a++) - { - point[p].position = XMFLOAT3(0.0f, 0.0f, 0.0f); - point[p].normal = XMFLOAT3(0.0f, 0.0f, -1.0f); - point[p].textureCoordinate = XMFLOAT2(static_cast(a) / static_cast(segments), 1.0f); - p++; - } - m_vertexCount = p; - - p = 0; - for (uint16 a = 0; a < 6; a += 2) - { - uint16 p1 = a*(segments + 1); - uint16 p2 = (a+1)*(segments + 1); - for (uint16 b = 0; b < segments; b++) - { - if (a < 4) - { - index[p] = b + p1; - index[p+1] = b + p2; - index[p+2] = b + p2 + 1; - p = p + 3; - } - if (a > 0) - { - index[p] = b + p1; - index[p+1] = b + p2 + 1; - index[p+2] = b + p1 + 1; - p = p + 3; - } - } - } - m_indexCount = p; - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount; - bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = point.data(); - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_vertexBuffer) - ); - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(uint16) * m_indexCount; - bd.BindFlags = D3D11_BIND_INDEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = index.data(); - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_indexBuffer) - ); -} diff --git a/DirectXSceneStore/GameContent/CylinderMesh.h b/DirectXSceneStore/GameContent/CylinderMesh.h deleted file mode 100644 index 3a80136..0000000 --- a/DirectXSceneStore/GameContent/CylinderMesh.h +++ /dev/null @@ -1,22 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// CylinderMesh: -// This class derives from MeshObject and creates a ID3D11Buffer of -// vertices and indices to represent a canonical cylinder (capped at -// both ends) that is positioned at the origin with a radius of 1.0, -// a height of 1.0 and with its axis in the +Z direction. - -#include "MeshObject.h" - -ref class CylinderMesh: public MeshObject -{ -internal: - CylinderMesh(_In_ ID3D11Device *device, uint32 segments); -}; diff --git a/DirectXSceneStore/GameContent/Face.cpp b/DirectXSceneStore/GameContent/Face.cpp deleted file mode 100644 index a8a1171..0000000 --- a/DirectXSceneStore/GameContent/Face.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Face.h" - -using namespace DirectX; - -//---------------------------------------------------------------------- - -Face::Face() -{ - SetPlane( - XMFLOAT3(0.0f, 0.0f, 0.0f), - XMFLOAT3(1.0f, 0.0f, 0.0f), - XMFLOAT3(0.0f, 1.0f, 0.0f) - ); -} - -//---------------------------------------------------------------------- - -Face::Face( - XMFLOAT3 origin, - XMFLOAT3 p1, - XMFLOAT3 p2 - ) -{ - SetPlane(origin, p1, p2); -} - -//-------------------------------------------------------------------------------- - -void Face::SetPlane( - XMFLOAT3 origin, - XMFLOAT3 p1, - XMFLOAT3 p2 - ) -{ - m_position = origin; - XMStoreFloat3(&m_widthVector, XMLoadFloat3(&p1) - XMLoadFloat3(&origin)); - XMStoreFloat3(&m_heightVector, XMLoadFloat3(&p2) - XMLoadFloat3(&origin)); - - m_point[0] = m_position; - m_point[1] = p1; - m_point[3] = p2; - XMStoreFloat3(&m_point[2], XMLoadFloat3(&p1) + XMLoadFloat3(&m_heightVector)); - - XMStoreFloat(&m_width, XMVector3Length(XMLoadFloat3(&m_widthVector))); - XMStoreFloat(&m_height, XMVector3Length(XMLoadFloat3(&m_heightVector))); - - XMStoreFloat3( - &m_normal, - XMVector3Normalize( - XMVector3Cross( - XMLoadFloat3(&m_widthVector), - XMLoadFloat3(&m_heightVector) - ) - ) - ); - UpdateMatrix(); -} - -//-------------------------------------------------------------------------------- - -void Face::UpdatePosition() -{ - m_point[0] = m_position; - XMStoreFloat3(&m_point[1], XMLoadFloat3(&m_position) + XMLoadFloat3(&m_widthVector)); - XMStoreFloat3(&m_point[3], XMLoadFloat3(&m_position) + XMLoadFloat3(&m_heightVector)); - XMStoreFloat3(&m_point[2], XMLoadFloat3(&m_point[1]) + XMLoadFloat3(&m_heightVector)); - - XMStoreFloat4x4( - &m_modelMatrix, - XMMatrixScaling(m_width, m_height, 1.0f) * - XMLoadFloat4x4(&m_rotationMatrix) * - XMMatrixTranslation(m_position.x, m_position.y, m_position.z) - ); -} - -//-------------------------------------------------------------------------------- - -bool Face::IsTouching( - XMFLOAT3 point, - float radius, - _Out_ XMFLOAT3 *contact, - _Out_ XMFLOAT3 *normal - ) -{ - float dist; - - // Determine if a point is within radius distance of the face and - // return the point of contact (projection of the point onto the face). - - XMStoreFloat( - &dist, - XMVector3Dot( - XMLoadFloat3(&m_normal), - XMLoadFloat3(&point) - XMLoadFloat3(&m_position) - ) - ); - - // Determine the point of contact by projecting the point along the Normal - // vector the distance the point is from the plane. - XMStoreFloat3(contact, XMLoadFloat3(&point) - (XMLoadFloat3(&m_normal) * dist)); - normal->x = m_normal.x; - normal->y = m_normal.y; - normal->z = m_normal.z; - - if (dist < 0.0f) - { - dist *= -1.0f; - normal->x = -m_normal.x; - normal->y = -m_normal.y; - normal->z = -m_normal.z; - } - else - { - normal->x = m_normal.x; - normal->y = m_normal.y; - normal->z = m_normal.z; - } - - if (dist < radius) - { - // point is within radius of the plane - // - // Determine if the point of contact is inside the parallelogram of the target. - // This is true if distance from each of the parallel lines defining the half - // spaces is less than the distance between the parallel lines for both sets of - // parallel lines. - // To catch the cases where the contact point is just outside the parallelogram - // but less than the radius we extend the parallelogram to accept points that are - // the distance between the parallel lines plus the radius. - // - - float dist1, dist2, dist3, dist4; - - XMStoreFloat( - &dist1, - XMVector3LinePointDistance( - XMLoadFloat3(&m_point[0]), - XMLoadFloat3(&m_point[1]), - XMLoadFloat3(contact) - ) - ); - XMStoreFloat( - &dist2, - XMVector3LinePointDistance( - XMLoadFloat3(&m_point[3]), - XMLoadFloat3(&m_point[2]), - XMLoadFloat3(contact) - ) - ); - XMStoreFloat( - &dist3, - XMVector3LinePointDistance( - XMLoadFloat3(&m_point[0]), - XMLoadFloat3(&m_point[3]), - XMLoadFloat3(contact) - ) - ); - XMStoreFloat( - &dist4, - XMVector3LinePointDistance( - XMLoadFloat3(&m_point[1]), - XMLoadFloat3(&m_point[2]), - XMLoadFloat3(contact) - ) - ); - - if (dist1 < (m_height + radius) && - dist2 < (m_height + radius) && - dist3 < (m_width + radius) && - dist4 < (m_width + radius)) - { - return true; - } - else - { - return false; - } - } - return false; -} - -//-------------------------------------------------------------------------------- - -void Face::UpdateMatrix() -{ - // Determine the Model transform for the cannonical face to align with the position - // and orientation of the defined face. The cannonical face geometry is - // a rectangle at the origin extending 1 unit in the +X and 1 unit in the +Y direction. - - XMVECTOR w = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f); - XMVECTOR h = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f); - XMVECTOR epsilon = XMVectorReplicate(0.0001f); - XMVECTOR width = XMVectorScale(XMLoadFloat3(&m_widthVector), 1.0f / m_width); - XMVECTOR height = XMVectorScale(XMLoadFloat3(&m_heightVector), 1.0f / m_height); - XMMATRIX mat1 = XMMatrixIdentity(); - XMMATRIX mat2 = XMMatrixIdentity(); - - // Determine the necessary rotation to align the widthVector with the +X axis. - // Then apply the rotation to the cannonical H vector (+Y). - if (!XMVector3NearEqual(w, width, epsilon)) - { - float angle1 = XMVectorGetX( - XMVector3AngleBetweenVectors(w, width) - ); - - if (XMVector3NearEqual(w, XMVectorNegate(width), epsilon)) - { - // The angle between w and width is ~180 degrees, so - // pick a axis of rotation perpendicular to the W vector. - mat1 = XMMatrixRotationAxis(XMVector3Orthogonal(w), angle1); - h = XMVector3TransformCoord(h, mat1); - } - else if ((angle1 * angle1) > 0.025) - { - // Take the cross product between the w and width vectors to - // determine the axis to rotate that is perpendicular to both vectors. - XMVECTOR axis1 = XMVector3Cross(w, width); - mat1 = XMMatrixRotationAxis(axis1, angle1); - h = XMVector3TransformCoord(h, mat1); - } - } - - // Determine the necessary rotation to align the transformed heightVector - // with the transformed H vector. - if (!XMVector3NearEqual(h, height, epsilon)) - { - float angle2 = XMVectorGetX( - XMVector3AngleBetweenVectors(h, height) - ); - - if (XMVector3NearEqual(h, XMVectorNegate(height), epsilon)) - { - // The angle between the h' and height vectors is ~180 degrees, - // so rotate around the width vector to keep it aligned in the right - // place. - mat2 = XMMatrixRotationAxis(width, angle2); - } - else if ((angle2 * angle2) > 0.025) - { - // Take the cross product between the h' and height vectors - // to determine the axis to rotate that is perpendicular to both vectors. - XMVECTOR axis2 = XMVector3Cross(h, height); - mat2 = XMMatrixRotationAxis(axis2, angle2); - } - } - XMStoreFloat4x4(&m_rotationMatrix, mat1 * mat2); - - // Generate the composite matrix to scale, rotate and translate to cannonical - // face geometry to be positioned correctly in world space. - XMStoreFloat4x4( - &m_modelMatrix, - XMMatrixScaling(m_width, m_height, 1.0f) * - mat1 * - mat2 * - XMMatrixTranslation(m_position.x, m_position.y, m_position.z) - ); -} - -//-------------------------------------------------------------------------------- \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Face.h b/DirectXSceneStore/GameContent/Face.h deleted file mode 100644 index b17f78f..0000000 --- a/DirectXSceneStore/GameContent/Face.h +++ /dev/null @@ -1,53 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Face: -// This class is a specialization of GameObject that represents a parallelogram primitive. -// The face is defined by three points. It is positioned at 'origin'. The four corners -// of the face are defined at 'origin', 'p1', 'p2' and 'p1' + ('p2' - 'origin'). - -#include "GameObject.h" - -ref class Face: public GameObject -{ -internal: - Face(); - Face( - DirectX::XMFLOAT3 origin, - DirectX::XMFLOAT3 p1, - DirectX::XMFLOAT3 p2 - ); - - void SetPlane( - DirectX::XMFLOAT3 origin, - DirectX::XMFLOAT3 p1, - DirectX::XMFLOAT3 p2 - ); - - virtual bool IsTouching( - DirectX::XMFLOAT3 point, - float radius, - _Out_ DirectX::XMFLOAT3 *contact, - _Out_ DirectX::XMFLOAT3 *normal - ) override; - -protected: - virtual void UpdatePosition() override; - -private: - void UpdateMatrix(); - - DirectX::XMFLOAT3 m_widthVector; - DirectX::XMFLOAT3 m_heightVector; - DirectX::XMFLOAT3 m_normal; - DirectX::XMFLOAT3 m_point[4]; - float m_width; - float m_height; - DirectX::XMFLOAT4X4 m_rotationMatrix; -}; diff --git a/DirectXSceneStore/GameContent/FaceMesh.cpp b/DirectXSceneStore/GameContent/FaceMesh.cpp deleted file mode 100644 index 469fc10..0000000 --- a/DirectXSceneStore/GameContent/FaceMesh.cpp +++ /dev/null @@ -1,56 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "FaceMesh.h" -#include "Common\DirectXSample.h" -#include "ConstantBuffers.h" - -using namespace Microsoft::WRL; -using namespace DirectX; - -FaceMesh::FaceMesh(_In_ ID3D11Device *device) -{ - D3D11_BUFFER_DESC bd = {0}; - D3D11_SUBRESOURCE_DATA initData = {0}; - - PNTVertex target_vertices[] = - { - {XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 1.0f)}, - {XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.0f)}, - {XMFLOAT3(1.0f, 1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f)}, - {XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 0.0f)} - }; - WORD target_indices[] = - { - 0, 1, 2, - 0, 2, 3, - 0, 2, 1, - 0, 3, 2 - }; - - m_vertexCount = 4; - m_indexCount = 12; - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount; - bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = target_vertices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_vertexBuffer) - ); - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(WORD) * m_indexCount; - bd.BindFlags = D3D11_BIND_INDEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = target_indices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_indexBuffer) - ); -} diff --git a/DirectXSceneStore/GameContent/FaceMesh.h b/DirectXSceneStore/GameContent/FaceMesh.h deleted file mode 100644 index e28da3d..0000000 --- a/DirectXSceneStore/GameContent/FaceMesh.h +++ /dev/null @@ -1,24 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// FaceMesh: -// This class derives from MeshObject and creates a ID3D11Buffer of -// vertices and indices to represent a canonical face defined as a -// rectangle at the origin extending 1 unit in the +X and -// 1 unit in the +Y direction. -// The face is defined to be two sided, so it is visible from either -// side. - -#include "MeshObject.h" - -ref class FaceMesh: public MeshObject -{ -internal: - FaceMesh(_In_ ID3D11Device *device); -}; diff --git a/DirectXSceneStore/GameContent/GameConstants.h b/DirectXSceneStore/GameContent/GameConstants.h deleted file mode 100644 index d03267e..0000000 --- a/DirectXSceneStore/GameContent/GameConstants.h +++ /dev/null @@ -1,45 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -namespace GameConstants -{ - static const int MaxAmmo = 10; - static const int MaxCylinders = 5; - static const int MaxTargets = 10; - static const float AmmoSize = 0.2f; - static const float AmmoRadius = AmmoSize * 0.5f; - static const int MaxBackgroundTextures = 3; - - static const int InitialLoadingDelay = 2000; // Number of ms to wait before completion of initial load. - static const int LevelLoadingDelay = 500; // Number of ms to wait before completion of level load. - - static const int WorldFloorId = 80001; - static const int WorldCeilingId = 80002; - static const int WorldWallsId = 80003; - - namespace Physics - { - static const float GroundRestitution = 0.8f; // Percentage of the velocity transmitted by ground and walls when an ammo hit. - static const float Friction = 0.9f; // The amount of velocity retained after friction is applied. - static const float AutoFireDelay = 0.2f; // The period between two successive ammo firing. - static const float Gravity = 5.0f; // The magnitude of the downward force applied to ammos. - static const float BounceTransfer = 0.8f; // The proportion of velocity transferred during a collision between 2 ammos. - static const float BounceLost = 0.1f; // The proportion of velocity lost during a collision between 2 ammos. - static const float RestThreshold = 0.02f; // The energy below which the ball is flagged as laying on ground. - // It is defined as Gravity * Height_above_ground + 0.5 * Velocity * Velocity. - static const float FrameLength = 0.003f; // The duration of a frame for physics handling when the graphics frame length is too long. - } - - namespace Sound - { - static const float MaxVelocity = 10.0f; // The velocity at which the bouncing sound is played at maximum volume. - static const float MinVelocity = 0.05f; // The minimum contact velocity required to make a sound. - static const float MinAdjustment = 0.2f; // The minimum volume adjustment based on contact velocity. - } -}; diff --git a/DirectXSceneStore/GameContent/GameObject.cpp b/DirectXSceneStore/GameContent/GameObject.cpp deleted file mode 100644 index 01150d4..0000000 --- a/DirectXSceneStore/GameContent/GameObject.cpp +++ /dev/null @@ -1,102 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "GameObject.h" -#include "ConstantBuffers.h" -#include "GameConstants.h" - -using namespace DirectX; - -//-------------------------------------------------------------------------------- - -GameObject::GameObject() : - m_normalMaterial(nullptr), - m_hitMaterial(nullptr) -{ - m_active = false; - m_target = false; - m_targetId = 0; - m_hit = false; - m_ground = true; - - m_position = XMFLOAT3(0.0f, 0.0f, 0.0f); - m_velocity = XMFLOAT3(0.0f, 0.0f, 0.0f); - m_defaultXAxis = XMFLOAT3(1.0f, 0.0f, 0.0f); - m_defaultYAxis = XMFLOAT3(0.0f, 1.0f, 0.0f); - m_defaultZAxis = XMFLOAT3(0.0f, 0.0f, 1.0f); - XMStoreFloat4x4(&m_modelMatrix, XMMatrixIdentity()); - - m_hitTime = 0.0f; - - m_animatePosition = nullptr; -} - -//---------------------------------------------------------------------- - -void GameObject::Render( - _In_ ID3D11DeviceContext *context, - _In_ ID3D11Buffer *primitiveConstantBuffer - ) -{ - if (!m_active || (m_mesh == nullptr) || (m_normalMaterial == nullptr)) - { - return; - } - - ConstantBufferChangesEveryPrim constantBuffer; - - XMStoreFloat4x4( - &constantBuffer.worldMatrix, - XMMatrixTranspose(ModelMatrix()) - ); - - if (m_hit && m_hitMaterial != nullptr) - { - m_hitMaterial->RenderSetup(context, &constantBuffer); - } - else - { - m_normalMaterial->RenderSetup(context, &constantBuffer); - } - context->UpdateSubresource(primitiveConstantBuffer, 0, nullptr, &constantBuffer, 0, 0); - - m_mesh->Render(context); -} - -//---------------------------------------------------------------------- - -void GameObject::PlaySound(float impactSpeed, XMFLOAT3 eyePoint) -{ - if (m_hitSound != nullptr) - { - // Determine the sound volume adjustment based on velocity. - float adjustment; - if (impactSpeed < GameConstants::Sound::MinVelocity) - { - adjustment = 0.0f; // Too soft. Don't play sound. - } - else - { - adjustment = min(1.0f, impactSpeed / GameConstants::Sound::MaxVelocity); - adjustment = GameConstants::Sound::MinAdjustment + adjustment * (1.0f - GameConstants::Sound::MinAdjustment); - } - - // Compute Distance to eyePoint to adjust the volume based on that distance. - XMVECTOR cameraToPosition = XMLoadFloat3(&eyePoint) - VectorPosition(); - float distToPositionSquared = XMVectorGetX(XMVector3LengthSq(cameraToPosition)); - - float volume = min(distToPositionSquared, 1.0f); - // Scale - // Sound is proportional to how hard the ball is hitting. - volume = adjustment * volume; - - m_hitSound->PlaySound(volume); - } -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/GameObject.h b/DirectXSceneStore/GameContent/GameObject.h deleted file mode 100644 index 9a6ae8b..0000000 --- a/DirectXSceneStore/GameContent/GameObject.h +++ /dev/null @@ -1,269 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// GameObject: -// This is the class representing a generic object in the 3D world of the game. There are -// specific sub-classes that have specific geometric shapes. This class contains all the -// properties of objects that are common. -// -// During the game physics calculations the IsTouching method will be called to determine -// the object's proximity to a point. It is expected the sub-classes will replace this method. -// The Render method will be called during rendering to include the object in the generation of -// the scene. - -#include "MeshObject.h" -#include "SoundEffect.h" -#include "Animate.h" -#include "Material.h" - -ref class GameObject -{ -internal: - GameObject(); - - // Expect the IsTouching method to be overloaded by subclasses. - virtual bool IsTouching( - DirectX::XMFLOAT3 /* point */, - float /* radius */, - _Out_ DirectX::XMFLOAT3 *contact, - _Out_ DirectX::XMFLOAT3 *normal - ) - { - *contact = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f); - *normal = DirectX::XMFLOAT3(0.0f, 0.0f, 1.0f); - return false; - }; - - void Render( - _In_ ID3D11DeviceContext *context, - _In_ ID3D11Buffer *primitiveConstantBuffer - ); - - void Active(bool active); - bool Active(); - void Target(bool target); - bool Target(); - void Hit(bool hit); - bool Hit(); - void OnGround(bool ground); - bool OnGround(); - void TargetId(int targetId); - int TargetId(); - void HitTime(float t); - float HitTime(); - - void AnimatePosition(_In_opt_ Animate^ animate); - Animate^ AnimatePosition(); - - void HitSound(_In_ SoundEffect^ hitSound); - SoundEffect^ HitSound(); - - void PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint); - - void Mesh(_In_ MeshObject^ mesh); - - void NormalMaterial(_In_ Material^ material); - Material^ NormalMaterial(); - void HitMaterial(_In_ Material^ material); - Material^ HitMaterial(); - - void Position(DirectX::XMFLOAT3 position); - void Position(DirectX::XMVECTOR position); - void Velocity(DirectX::XMFLOAT3 velocity); - void Velocity(DirectX::XMVECTOR velocity); - DirectX::XMMATRIX ModelMatrix(); - DirectX::XMFLOAT3 Position(); - DirectX::XMVECTOR VectorPosition(); - DirectX::XMVECTOR VectorVelocity(); - DirectX::XMFLOAT3 Velocity(); - -protected private: - virtual void UpdatePosition() {}; - // Object Data - bool m_active; - bool m_target; - int m_targetId; - bool m_hit; - bool m_ground; - - DirectX::XMFLOAT3 m_position; - DirectX::XMFLOAT3 m_velocity; - DirectX::XMFLOAT4X4 m_modelMatrix; - - Material^ m_normalMaterial; - Material^ m_hitMaterial; - - DirectX::XMFLOAT3 m_defaultXAxis; - DirectX::XMFLOAT3 m_defaultYAxis; - DirectX::XMFLOAT3 m_defaultZAxis; - - float m_hitTime; - - Animate^ m_animatePosition; - MeshObject^ m_mesh; - - SoundEffect^ m_hitSound; -}; - - -__forceinline void GameObject::Active(bool active) -{ - m_active = active; -} - -__forceinline bool GameObject::Active() -{ - return m_active; -} - -__forceinline void GameObject::Target(bool target) -{ - m_target = target; -} - -__forceinline bool GameObject::Target() -{ - return m_target; -} - -__forceinline void GameObject::Hit(bool hit) -{ - m_hit = hit; -} - -__forceinline bool GameObject::Hit() -{ - return m_hit; -} - -__forceinline void GameObject::OnGround(bool ground) -{ - m_ground = ground; -} - -__forceinline bool GameObject::OnGround() -{ - return m_ground; -} - -__forceinline void GameObject::TargetId(int targetId) -{ - m_targetId = targetId; -} - -__forceinline int GameObject::TargetId() -{ - return m_targetId; -} - -__forceinline void GameObject::HitTime(float t) -{ - m_hitTime = t; -} - -__forceinline float GameObject::HitTime() -{ - return m_hitTime; -} - -__forceinline void GameObject::Position(DirectX::XMFLOAT3 position) -{ - m_position = position; - // Update any internal states that are dependent on the position. - // UpdatePosition is a virtual function that is specific to the derived class. - UpdatePosition(); -} - -__forceinline void GameObject::Position(DirectX::XMVECTOR position) -{ - XMStoreFloat3(&m_position, position); - // Update any internal states that are dependent on the position. - // UpdatePosition is a virtual function that is specific to the derived class. - UpdatePosition(); -} - -__forceinline DirectX::XMFLOAT3 GameObject::Position() -{ - return m_position; -} - -__forceinline DirectX::XMVECTOR GameObject::VectorPosition() -{ - return DirectX::XMLoadFloat3(&m_position); -} - -__forceinline void GameObject::Velocity(DirectX::XMFLOAT3 velocity) -{ - m_velocity = velocity; -} - -__forceinline void GameObject::Velocity(DirectX::XMVECTOR velocity) -{ - XMStoreFloat3(&m_velocity, velocity); -} - -__forceinline DirectX::XMFLOAT3 GameObject::Velocity() -{ - return m_velocity; -} - -__forceinline DirectX::XMVECTOR GameObject::VectorVelocity() -{ - return DirectX::XMLoadFloat3(&m_velocity); -} - -__forceinline void GameObject::AnimatePosition(_In_opt_ Animate^ animate) -{ - m_animatePosition = animate; -} - -__forceinline Animate^ GameObject::AnimatePosition() -{ - return m_animatePosition; -} - -__forceinline void GameObject::NormalMaterial(_In_ Material^ material) -{ - m_normalMaterial = material; -} - -__forceinline Material^ GameObject::NormalMaterial() -{ - return m_normalMaterial; -} - -__forceinline void GameObject::HitMaterial(_In_ Material^ material) -{ - m_hitMaterial = material; -} - -__forceinline Material^ GameObject::HitMaterial() -{ - return m_hitMaterial; -} - -__forceinline void GameObject::Mesh(_In_ MeshObject^ mesh) -{ - m_mesh = mesh; -} - -__forceinline void GameObject::HitSound(_In_ SoundEffect^ hitSound) -{ - m_hitSound = hitSound; -} - -__forceinline SoundEffect^ GameObject::HitSound() -{ - return m_hitSound; -} - -__forceinline DirectX::XMMATRIX GameObject::ModelMatrix() -{ - return DirectX::XMLoadFloat4x4(&m_modelMatrix); -} diff --git a/DirectXSceneStore/GameContent/GameTimer.cpp b/DirectXSceneStore/GameContent/GameTimer.cpp deleted file mode 100644 index a9dbea3..0000000 --- a/DirectXSceneStore/GameContent/GameTimer.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "GameTimer.h" - -GameTimer::GameTimer(): - m_active(false) -{ - LARGE_INTEGER frequency; - if (!QueryPerformanceFrequency(&frequency)) - { - throw ref new Platform::FailureException(); - } - m_secondsPerCount = 1.0f / static_cast(frequency.QuadPart); - - Reset(); -} - -// Returns the total time elapsed since Reset() was called, NOT counting any -// time when the clock is stopped. -float GameTimer::PlayingTime() -{ - if (m_active) - { - // The distance m_currentTime - m_baseTime includes paused time, - // which we do not want to count. To correct this, we can subtract - // the paused time from m_currentTime: - return static_cast(((m_currentTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount); - } - else - { - // The clock is currently not running so don't count the time since - // the clock was stopped - return static_cast(((m_stopTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount); - } -} - - -void GameTimer::PlayingTime(float time) -{ - // Reset the internal state to reflect a PlayingTime of 'time' - // Offset the baseTime by this 'time'. - m_active = false; - m_stopTime = m_currentTime; - m_pausedTime.QuadPart = 0; - - m_baseTime.QuadPart = m_stopTime.QuadPart - static_cast<__int64>(time / m_secondsPerCount); -} - - -float GameTimer::DeltaTime() -{ - return m_deltaTime; -} - -void GameTimer::Reset() -{ - LARGE_INTEGER currentTime; - if (!QueryPerformanceCounter(¤tTime)) - { - throw ref new Platform::FailureException(); - } - m_baseTime = currentTime; - m_previousTime = currentTime; - m_stopTime = currentTime; - m_currentTime = currentTime; - m_pausedTime.QuadPart = 0; - m_active = false; -} - -void GameTimer::Start() -{ - LARGE_INTEGER startTime; - if (!QueryPerformanceCounter(&startTime)) - { - throw ref new Platform::FailureException(); - } - if (!m_active) - { - // Accumulate the time elapsed between stop and start pairs. - m_pausedTime.QuadPart += (startTime.QuadPart - m_stopTime.QuadPart); - - m_previousTime = startTime; - m_stopTime.QuadPart = 0; - m_active = true; - } -} - -void GameTimer::Stop() -{ - if (m_active) - { - // Set the stop time to the time of the last update. - m_stopTime = m_currentTime; - m_active = false; - } -} - -void GameTimer::Update() -{ - if (!m_active) - { - m_deltaTime = 0.0; - return; - } - - LARGE_INTEGER currentTime; - if (!QueryPerformanceCounter(¤tTime)) - { - throw ref new Platform::FailureException(); - } - m_currentTime = currentTime; - - m_deltaTime = (m_currentTime.QuadPart - m_previousTime.QuadPart)*m_secondsPerCount; - m_previousTime = m_currentTime; - - if (m_deltaTime < 0.0) - { - m_deltaTime = 0.0; - } -} diff --git a/DirectXSceneStore/GameContent/GameTimer.h b/DirectXSceneStore/GameContent/GameTimer.h deleted file mode 100644 index 4ef7ba6..0000000 --- a/DirectXSceneStore/GameContent/GameTimer.h +++ /dev/null @@ -1,37 +0,0 @@ -/// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -ref class GameTimer -{ -internal: - GameTimer(); - - float PlayingTime(); // Return the Elapsed time the Game has been active in seconds since Reset - void PlayingTime(float time); // Set the Elapsed playing time -- used for restarting in the middle of a game - float DeltaTime(); // Return the Delta time between the last two updates - - void Reset(); - void Start(); - void Stop(); - void Update(); - bool Active() { return m_active; }; - -private: - float m_secondsPerCount; // 1.0 / Frequency - float m_deltaTime; - - LARGE_INTEGER m_baseTime; - LARGE_INTEGER m_pausedTime; - LARGE_INTEGER m_stopTime; - LARGE_INTEGER m_previousTime; - LARGE_INTEGER m_currentTime; - - bool m_active; -}; - diff --git a/DirectXSceneStore/GameContent/Level.cpp b/DirectXSceneStore/GameContent/Level.cpp deleted file mode 100644 index c74dfc4..0000000 --- a/DirectXSceneStore/GameContent/Level.cpp +++ /dev/null @@ -1,65 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Level.h" - -//---------------------------------------------------------------------- - -bool Level::Update( - float /* time */, - float /* elapsedTime */, - float /* timeRemaining*/, - std::vector objects - ) -{ - int left = 0; - - for (auto object = objects.begin(); object != objects.end(); object++) - { - if ((*object)->Active() && (*object)->Target()) - { - if ((*object)->Hit()) - { - (*object)->Active(false); - } - else - { - left++; - } - } - } - return (left == 0); -} - -//---------------------------------------------------------------------- - -void Level::SaveState(PersistentState^ /* state */) -{ -} - -//---------------------------------------------------------------------- - -void Level::LoadState(PersistentState^ /* state */) -{ -} - -//---------------------------------------------------------------------- - -Platform::String^ Level::Objective() -{ - return m_objective; -} - -//---------------------------------------------------------------------- - -float Level::TimeLimit() -{ - return m_timeLimit; -} - -//---------------------------------------------------------------------- \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Level.h b/DirectXSceneStore/GameContent/Level.h deleted file mode 100644 index 00d9d90..0000000 --- a/DirectXSceneStore/GameContent/Level.h +++ /dev/null @@ -1,52 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Level: -// This is an abstract class from which all of the levels of the game are derived. -// Each level potentially overrides up to four methods: -// Initialize - (required) takes a list of objects and enables the objects that -// are active for the level as well as setting their positions and -// any animations associated with the objects. -// Update - this method is called once per time step and is expected to -// determine if the level has been completed. The Level class provides -// a 'standard' Update method which checks each object that is a target -// and disables any active targets that have been hit. It returns true -// once there are no active targets remaining. -// SaveState - method to save any Level specific state. Default is defined as -// not saving any state. -// LoadState - method to restore any Level specific state. Default is defined -// as not restoring any state. - -#include "GameObject.h" -#include "Common\PersistentState.h" - -ref class Level abstract -{ -internal: - virtual void Initialize( - std::vector objects - ) = 0; - - virtual bool Update( - float time, - float elapsedTime, - float timeRemaining, - std::vector objects - ); - - virtual void SaveState(PersistentState^ state); - virtual void LoadState(PersistentState^ state); - - Platform::String^ Objective(); - float TimeLimit(); - -protected private: - Platform::String^ m_objective; - float m_timeLimit; -}; diff --git a/DirectXSceneStore/GameContent/Level1.cpp b/DirectXSceneStore/GameContent/Level1.cpp deleted file mode 100644 index 3de79dc..0000000 --- a/DirectXSceneStore/GameContent/Level1.cpp +++ /dev/null @@ -1,65 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Level1.h" -#include "Face.h" - -using namespace DirectX; - -//---------------------------------------------------------------------- - -Level1::Level1() -{ - m_timeLimit = 30.0f; - m_objective = "Hit each of the targets within the time limit.\nMove your face to aim. Open your mouth to fire. "; -} - -//---------------------------------------------------------------------- - -void Level1::Initialize(std::vector objects) -{ - XMFLOAT3 position[] = - { - XMFLOAT3(-2.5f, -1.0f, -1.5f), - XMFLOAT3(-1.0f, 0.0f, -3.0f), - XMFLOAT3( 1.5f, -1.0f, -3.0f), - XMFLOAT3(-2.5f, -1.0f, -5.5f), - XMFLOAT3( 0.5f, -2.1f, -5.0f), - XMFLOAT3( 1.5f, -1.8f, -5.5f), - XMFLOAT3( 1.5f, -0.5f, 0.0f), - XMFLOAT3( 0.0f, -2.5f, 0.0f), - XMFLOAT3(-2.0f, -2.0f, 0.0f) - }; - - int targetCount = 0; - for (auto object = objects.begin(); object != objects.end(); object++) - { - if (Face^ target = dynamic_cast(*object)) - { - if (targetCount < 9) - { - target->Active(true); - target->Target(true); - target->Hit(false); - target->AnimatePosition(nullptr); - target->Position(position[targetCount]); - targetCount++; - } - else - { - (*object)->Active(false); - } - } - else - { - (*object)->Active(false); - } - } -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/Level1.h b/DirectXSceneStore/GameContent/Level1.h deleted file mode 100644 index d305140..0000000 --- a/DirectXSceneStore/GameContent/Level1.h +++ /dev/null @@ -1,21 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Level1: -// This class defines the first level of the game. There are nine active targets. -// Each of the targets is stationary and can be hit in any order. - -#include "Level.h" - -ref class Level1: public Level -{ -internal: - Level1(); - virtual void Initialize(std::vector objects) override; -}; diff --git a/DirectXSceneStore/GameContent/Level2.cpp b/DirectXSceneStore/GameContent/Level2.cpp deleted file mode 100644 index 9383acb..0000000 --- a/DirectXSceneStore/GameContent/Level2.cpp +++ /dev/null @@ -1,87 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Level2.h" -#include "Face.h" - -//---------------------------------------------------------------------- - -Level2::Level2() -{ - m_timeLimit = 30.0f; - m_objective = "Hit each of the targets in ORDER before time runs out."; -} - -//---------------------------------------------------------------------- - -void Level2::Initialize(std::vector objects) -{ - Level1::Initialize(objects); - - int targetCount = 0; - for (auto object = objects.begin(); object != objects.end(); object++) - { - if (Face^ target = dynamic_cast(*object)) - { - if (targetCount < 9) - { - target->Target(targetCount == 0 ? true : false); - targetCount++; - } - } - } - m_nextId = 1; -} - -//---------------------------------------------------------------------- - -bool Level2::Update( - float /* time */, - float /* elapsedTime */, - float /* timeRemaining */, - std::vector objects - ) -{ - int left = 0; - for (auto object = objects.begin(); object != objects.end(); object++) - { - if ((*object)->Active() && ((*object)->TargetId() > 0)) - { - if ((*object)->Hit() && ((*object)->TargetId() == m_nextId)) - { - (*object)->Active(false); - m_nextId++; - } - else - { - left++; - } - } - if ((*object)->Active() && ((*object)->TargetId() == m_nextId)) - { - (*object)->Target(true); - } - } - return (left == 0); -} - -//---------------------------------------------------------------------- - -void Level2::SaveState(PersistentState^ state) -{ - state->SaveInt32(":NextTarget", m_nextId); -} - -//---------------------------------------------------------------------- - -void Level2::LoadState(PersistentState^ state) -{ - m_nextId = state->LoadInt32(":NextTarget", 1); -} - -//---------------------------------------------------------------------- \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Level2.h b/DirectXSceneStore/GameContent/Level2.h deleted file mode 100644 index a46cc23..0000000 --- a/DirectXSceneStore/GameContent/Level2.h +++ /dev/null @@ -1,34 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Level2: -// This class defines the second level of the game. It derives from the -// first level. In this level the targets must be hit in numeric order. - -#include "Level1.h" - -ref class Level2: public Level1 -{ -internal: - Level2(); - virtual void Initialize(std::vector objects) override; - - virtual bool Update( - float time, - float elapsedTime, - float timeRemaining, - std::vector objects - ) override; - - virtual void SaveState(PersistentState^ state) override; - virtual void LoadState(PersistentState^ state) override; - -private: - int m_nextId; -}; diff --git a/DirectXSceneStore/GameContent/Level3.cpp b/DirectXSceneStore/GameContent/Level3.cpp deleted file mode 100644 index 7bc3104..0000000 --- a/DirectXSceneStore/GameContent/Level3.cpp +++ /dev/null @@ -1,172 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Level3.h" -#include "Face.h" -#include "Animate.h" - -using namespace DirectX; - -//---------------------------------------------------------------------- - -Level3::Level3() -{ - m_timeLimit = 30.0f; - m_objective = "Hit each of the moving targets before time runs out."; -} - -//---------------------------------------------------------------------- - -void Level3::Initialize(std::vector objects) -{ - XMFLOAT3 position[] = - { - XMFLOAT3(-2.5f, -1.0f, -1.5f), - XMFLOAT3(-1.0f, 1.0f, -3.0f), - XMFLOAT3( 1.5f, 0.0f, -5.5f), - XMFLOAT3(-2.5f, -1.0f, -5.5f), - XMFLOAT3( 0.5f, -2.0f, -5.0f), - XMFLOAT3( 1.5f, -2.0f, -5.5f), - XMFLOAT3( 0.0f, -3.6f, 0.0f), - XMFLOAT3( 0.0f, -3.6f, 0.0f), - XMFLOAT3( 0.0f, -3.6f, 0.0f) - }; - XMFLOAT3 LineList1[] = - { - XMFLOAT3(-2.5f, -1.0f, -1.5f), - XMFLOAT3(-0.5f, 1.0f, 1.0f), - XMFLOAT3(-0.5f, -2.5f, 1.0f), - XMFLOAT3(-2.5f, -1.0f, -1.5f), - }; - XMFLOAT3 LineList2[] = - { - XMFLOAT3(-1.0f, 1.0f, -3.0f), - XMFLOAT3(-2.0f, 2.0f, -1.5f), - XMFLOAT3(-2.0f, -2.5f, -1.5f), - XMFLOAT3( 1.5f, -2.5f, -1.5f), - XMFLOAT3( 1.5f, -2.5f, -3.0f), - XMFLOAT3(-1.0f, 1.0f, -3.0f), - }; - XMFLOAT3 LineList3[] = - { - XMFLOAT3(1.5f, 0.0f, -5.5f), - XMFLOAT3(1.5f, 1.0f, -5.5f), - XMFLOAT3(1.5f, -2.5f, -5.5f), - XMFLOAT3(1.5f, 0.0f, -5.5f), - }; - XMFLOAT3 LineList4[] = - { - XMFLOAT3(-2.5f, -1.0f, -5.5f), - XMFLOAT3( 1.0f, -1.0f, -5.5f), - XMFLOAT3( 1.0f, 1.0f, -5.5f), - XMFLOAT3(-2.5f, 1.0f, -5.5f), - XMFLOAT3(-2.5f, -1.0f, -5.5f), - }; - XMFLOAT3 LineList5[] = - { - XMFLOAT3( 0.5f, -2.0f, -5.0f), - XMFLOAT3( 2.0f, -2.0f, -5.0f), - XMFLOAT3( 2.0f, 1.0f, -5.0f), - XMFLOAT3(-2.5f, 1.0f, -5.0f), - XMFLOAT3(-2.5f, -2.0f, -5.0f), - XMFLOAT3( 0.5f, -2.0f, -5.0f), - }; - XMFLOAT3 LineList6[] = - { - XMFLOAT3( 1.5f, -2.0f, -5.5f), - XMFLOAT3(-2.5f, -2.0f, -5.5f), - XMFLOAT3(-2.5f, 1.0f, -5.5f), - XMFLOAT3( 1.5f, 1.0f, -5.5f), - XMFLOAT3( 1.5f, -2.0f, -5.5f), - }; - - int targetCount = 0; - for (auto object = objects.begin(); object != objects.end(); object++) - { - if (Face^ target = dynamic_cast(*object)) - { - if (targetCount < 9) - { - target->Active(true); - target->Target(true); - target->Hit(false); - target->Position(position[targetCount]); - switch (targetCount) - { - case 0: - target->AnimatePosition(ref new AnimateLineListPosition(4, LineList1, 10.0f, true)); - break; - case 1: - target->AnimatePosition(ref new AnimateLineListPosition(6, LineList2, 15.0f, true)); - break; - case 2: - target->AnimatePosition(ref new AnimateLineListPosition(4, LineList3, 15.0f, true)); - break; - case 3: - target->AnimatePosition(ref new AnimateLineListPosition(5, LineList4, 15.0f, true)); - break; - case 4: - target->AnimatePosition(ref new AnimateLineListPosition(6, LineList5, 15.0f, true)); - break; - case 5: - target->AnimatePosition(ref new AnimateLineListPosition(5, LineList6, 15.0f, true)); - break; - case 6: - target->AnimatePosition( - ref new AnimateCirclePosition( - XMFLOAT3(0.0f, -2.5f, 0.0f), - XMFLOAT3(0.0f, -3.6f, 0.0f), - XMFLOAT3(0.0f, 0.0f, 1.0f), - 9.0f, - true, - true - ) - ); - break; - case 7: - target->AnimatePosition( - ref new AnimateCirclePosition( - XMFLOAT3(0.0f, -2.5f, 0.0f), - XMFLOAT3(0.0f, -3.6f, 0.0f), - XMFLOAT3(0.0f, 0.0f, 1.0f), - 9.0f, - true, - true - ) - ); - target->AnimatePosition()->Start(3.0f); - break; - case 8: - target->AnimatePosition( - ref new AnimateCirclePosition( - XMFLOAT3(0.0f, -2.5f, 0.0f), - XMFLOAT3(0.0f, -3.6f, 0.0f), - XMFLOAT3(0.0f, 0.0f, 1.0f), - 9.0f, - true, - true - ) - ); - target->AnimatePosition()->Start(6.0f); - break; - } - targetCount++; - } - else - { - target->Active(false); - } - } - else - { - (*object)->Active(false); - } - } -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/Level3.h b/DirectXSceneStore/GameContent/Level3.h deleted file mode 100644 index 0fbad3c..0000000 --- a/DirectXSceneStore/GameContent/Level3.h +++ /dev/null @@ -1,22 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Level3: -// This class defines the third level of the game. In this level each of the -// nine targets is moving along closed paths and can be hit -// in any order. - -#include "Level.h" - -ref class Level3: public Level -{ -internal: - Level3(); - virtual void Initialize(std::vector objects) override; -}; diff --git a/DirectXSceneStore/GameContent/Level4.cpp b/DirectXSceneStore/GameContent/Level4.cpp deleted file mode 100644 index 1c7e0ef..0000000 --- a/DirectXSceneStore/GameContent/Level4.cpp +++ /dev/null @@ -1,87 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Level4.h" -#include "Face.h" - -//---------------------------------------------------------------------- - -Level4::Level4() -{ - m_timeLimit = 30.0f; - m_objective = "Hit each of the moving targets in ORDER before time runs out."; -} - -//---------------------------------------------------------------------- - -void Level4::Initialize(std::vector objects) -{ - Level3::Initialize(objects); - - int targetCount = 0; - for (auto object = objects.begin(); object != objects.end(); object++) - { - if (Face^ target = dynamic_cast(*object)) - { - if (targetCount < 9) - { - target->Target(targetCount == 0 ? true : false); - targetCount++; - } - } - } - m_nextId = 1; -} - -//---------------------------------------------------------------------- - -bool Level4::Update( - float /* time */, - float /* elapsedTime */, - float /* timeRemaining */, - std::vector objects - ) -{ - int left = 0; - for (auto object = objects.begin(); object != objects.end(); object++) - { - if ((*object)->Active() && ((*object)->TargetId() > 0)) - { - if ((*object)->Hit() && ((*object)->TargetId() == m_nextId)) - { - (*object)->Active(false); - m_nextId++; - } - else - { - left++; - } - } - if ((*object)->Active() && ((*object)->TargetId() == m_nextId)) - { - (*object)->Target(true); - } - } - return (left == 0); -} - -//---------------------------------------------------------------------- - -void Level4::SaveState(PersistentState^ state) -{ - state->SaveInt32(":NextTarget", m_nextId); -} - -//---------------------------------------------------------------------- - -void Level4::LoadState(PersistentState^ state) -{ - m_nextId = state->LoadInt32(":NextTarget", 1); -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/Level4.h b/DirectXSceneStore/GameContent/Level4.h deleted file mode 100644 index 226264f..0000000 --- a/DirectXSceneStore/GameContent/Level4.h +++ /dev/null @@ -1,34 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Level4: -// This class defines the fourth level of the game. It derives from the -// third level. The targets must be hit in numeric order. - -#include "Level3.h" - -ref class Level4: public Level3 -{ -internal: - Level4(); - virtual void Initialize(std::vector objects) override; - - virtual bool Update( - float time, - float elapsedTime, - float timeRemaining, - std::vector objects - ) override; - - virtual void SaveState(PersistentState^ state) override; - virtual void LoadState(PersistentState^ state) override; - -private: - int m_nextId; -}; diff --git a/DirectXSceneStore/GameContent/Level5.cpp b/DirectXSceneStore/GameContent/Level5.cpp deleted file mode 100644 index bcfe5ec..0000000 --- a/DirectXSceneStore/GameContent/Level5.cpp +++ /dev/null @@ -1,78 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Level5.h" -#include "Cylinder.h" -#include "Animate.h" - -using namespace DirectX; - -//---------------------------------------------------------------------- - -Level5::Level5() -{ - m_timeLimit = 30.0f; - m_objective = "Hit each of the moving targets while avoiding the obstacles before time runs out."; -} - -//---------------------------------------------------------------------- - -void Level5::Initialize(std::vector objects) -{ - Level3::Initialize(objects); - - XMFLOAT3 obstacleStartPosition[] = - { - XMFLOAT3(-4.5f, -3.0f, 0.0f), - XMFLOAT3(4.5f, -3.0f, 0.0f), - XMFLOAT3(0.0f, 3.01f, -2.0f), - XMFLOAT3(-1.5f, -3.0f, -6.5f), - XMFLOAT3(1.5f, -3.0f, -6.5f) - }; - XMFLOAT3 obstacleEndPosition[] = - { - XMFLOAT3(-2.0f, -3.0f, 0.0f), - XMFLOAT3(2.0f, -3.0f, 0.0f), - XMFLOAT3(0.0f, -3.0f, -2.0f), - XMFLOAT3(-1.5f, -3.0f, -4.0f), - XMFLOAT3(1.5f, -3.0f, -4.0f) - }; - float obstacleStartTime[] = - { - 2.0f, - 5.0f, - 8.0f, - 11.0f, - 14.0f - }; - - int obstacleCount = 0; - for (auto object = objects.begin(); object != objects.end(); object++) - { - if (Cylinder^ obstacle = dynamic_cast(*object)) - { - if (obstacleCount < 5) - { - obstacle->Active(true); - obstacle->Position(obstacleStartPosition[obstacleCount]); - obstacle->AnimatePosition( - ref new AnimateLinePosition( - obstacleStartPosition[obstacleCount], - obstacleEndPosition[obstacleCount], - 10.0, - false - ) - ); - obstacle->AnimatePosition()->Start(obstacleStartTime[obstacleCount]); - obstacleCount ++; - } - } - } -} - -//---------------------------------------------------------------------- \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Level5.h b/DirectXSceneStore/GameContent/Level5.h deleted file mode 100644 index eea2478..0000000 --- a/DirectXSceneStore/GameContent/Level5.h +++ /dev/null @@ -1,22 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Level5: -// This class defines the fifth level of the game. It derives from the -// third level. This level introduces obstacles that move into place -// during game play. The targets may be hit in any order. - -#include "Level3.h" - -ref class Level5: public Level3 -{ -internal: - Level5(); - virtual void Initialize(std::vector objects) override; -}; diff --git a/DirectXSceneStore/GameContent/Level6.cpp b/DirectXSceneStore/GameContent/Level6.cpp deleted file mode 100644 index 7b619a3..0000000 --- a/DirectXSceneStore/GameContent/Level6.cpp +++ /dev/null @@ -1,41 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Level6.h" - -//---------------------------------------------------------------------- - -Level6::Level6() -{ - m_timeLimit = 20.0f; - m_objective = "Hit as many moving targets as possible while avoiding the obstacles before time runs out."; -} - -//---------------------------------------------------------------------- - -bool Level6::Update( - float time, - float elapsedTime, - float timeRemaining, - std::vector objects - ) -{ - for (auto object = objects.begin(); object != objects.end(); object++) - { - if ((*object)->Active() && (*object)->Target()) - { - if ((*object)->Hit() && ((*object)->HitTime() < (time - 2.0f))) - { - (*object)->Hit(false); - } - } - } - return ((timeRemaining - elapsedTime) <= 0.0f); -} - -//---------------------------------------------------------------------- \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Level6.h b/DirectXSceneStore/GameContent/Level6.h deleted file mode 100644 index c31adc8..0000000 --- a/DirectXSceneStore/GameContent/Level6.h +++ /dev/null @@ -1,28 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Level6: -// This class defines the sixth and final level of the game. It derives from the -// fifth level. In this level the targets do not disappear when they are hit. -// The target will stay highlighted for two seconds. As this is the last level -// the only criteria for completion is time expiring. - -#include "Level5.h" - -ref class Level6: public Level5 -{ -internal: - Level6(); - virtual bool Update( - float time, - float elapsedTime, - float timeRemaining, - std::vector objects - ) override; -}; diff --git a/DirectXSceneStore/GameContent/Material.cpp b/DirectXSceneStore/GameContent/Material.cpp deleted file mode 100644 index 4174394..0000000 --- a/DirectXSceneStore/GameContent/Material.cpp +++ /dev/null @@ -1,51 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Material.h" -#include "GameConstants.h" - -using namespace DirectX; - -//-------------------------------------------------------------------------------- - -Material::Material( - XMFLOAT4 meshColor, - XMFLOAT4 diffuseColor, - XMFLOAT4 specularColor, - float specularExponent, - _In_ ID3D11ShaderResourceView* textureResourceView, - _In_ ID3D11VertexShader* vertexShader, - _In_ ID3D11PixelShader* pixelShader - ) -{ - m_meshColor = meshColor; - m_diffuseColor = diffuseColor; - m_specularColor = specularColor; - m_specularExponent = specularExponent; - - m_vertexShader = vertexShader; - m_pixelShader = pixelShader; - m_textureRV = textureResourceView; -} - -//-------------------------------------------------------------------------------- - -void Material::RenderSetup( - _In_ ID3D11DeviceContext* context, - _Inout_ ConstantBufferChangesEveryPrim* constantBuffer - ) -{ - constantBuffer->meshColor = m_meshColor; - constantBuffer->specularColor = m_specularColor; - constantBuffer->specularPower = m_specularExponent; - constantBuffer->diffuseColor = m_diffuseColor; - - context->PSSetShaderResources(0, 1, m_textureRV.GetAddressOf()); - context->VSSetShader(m_vertexShader.Get(), nullptr, 0); - context->PSSetShader(m_pixelShader.Get(), nullptr, 0); -} \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/Material.h b/DirectXSceneStore/GameContent/Material.h deleted file mode 100644 index a1ad3f0..0000000 --- a/DirectXSceneStore/GameContent/Material.h +++ /dev/null @@ -1,54 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Material: -// This class maintains the properties that represent how an object will -// look when it is rendered. This includes the color of the object, the -// texture used to render the object, and the vertex and pixel shader that -// should be used for rendering. -// The RenderSetup method sets the appropriate values into the constantBuffer -// and calls the appropriate D3D11 context methods to set up the rendering pipeline -// in the graphics hardware. - -#include "ConstantBuffers.h" - -ref class Material -{ -internal: - Material( - DirectX::XMFLOAT4 meshColor, - DirectX::XMFLOAT4 diffuseColor, - DirectX::XMFLOAT4 specularColor, - float specularExponent, - _In_ ID3D11ShaderResourceView* textureResourceView, - _In_ ID3D11VertexShader* vertexShader, - _In_ ID3D11PixelShader* pixelShader - ); - - void RenderSetup( - _In_ ID3D11DeviceContext* context, - _Inout_ ConstantBufferChangesEveryPrim* constantBuffer - ); - - void SetTexture(_In_ ID3D11ShaderResourceView* textureResourceView) - { - m_textureRV = textureResourceView; - } - -protected private: - DirectX::XMFLOAT4 m_meshColor; - DirectX::XMFLOAT4 m_diffuseColor; - DirectX::XMFLOAT4 m_hitColor; - DirectX::XMFLOAT4 m_specularColor; - float m_specularExponent; - - Microsoft::WRL::ComPtr m_vertexShader; - Microsoft::WRL::ComPtr m_pixelShader; - Microsoft::WRL::ComPtr m_textureRV; -}; diff --git a/DirectXSceneStore/GameContent/MediaReader.cpp b/DirectXSceneStore/GameContent/MediaReader.cpp deleted file mode 100644 index ed84967..0000000 --- a/DirectXSceneStore/GameContent/MediaReader.cpp +++ /dev/null @@ -1,131 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "MediaReader.h" -#include "Common\DirectXSample.h" - -using namespace Microsoft::WRL; -using namespace Windows::Storage; -using namespace Windows::Storage::Streams; -using namespace Windows::Foundation; -using namespace Windows::ApplicationModel; - -MediaReader::MediaReader() -{ - ZeroMemory(&m_waveFormat, sizeof(m_waveFormat)); - m_installedLocation = Package::Current->InstalledLocation; - m_installedLocationPath = Platform::String::Concat(m_installedLocation->Path, "\\"); -} - -WAVEFORMATEX *MediaReader::GetOutputWaveFormatEx() -{ - return &m_waveFormat; -} - -Platform::Array^ MediaReader::LoadMedia(_In_ Platform::String^ filename) -{ - DX::ThrowIfFailed( - MFStartup(MF_VERSION) - ); - - ComPtr reader; - DX::ThrowIfFailed( - MFCreateSourceReaderFromURL( - Platform::String::Concat(m_installedLocationPath, filename)->Data(), - nullptr, - &reader - ) - ); - - // Set the decoded output format as PCM. - // XAudio2 on Windows can process PCM and ADPCM-encoded buffers. - // When using MediaFoundation, this sample always decodes into PCM. - Microsoft::WRL::ComPtr mediaType; - DX::ThrowIfFailed( - MFCreateMediaType(&mediaType) - ); - - DX::ThrowIfFailed( - mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio) - ); - - DX::ThrowIfFailed( - mediaType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM) - ); - - DX::ThrowIfFailed( - reader->SetCurrentMediaType(static_cast(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, mediaType.Get()) - ); - - // Get the complete WAVEFORMAT from the Media Type. - Microsoft::WRL::ComPtr outputMediaType; - DX::ThrowIfFailed( - reader->GetCurrentMediaType(static_cast(MF_SOURCE_READER_FIRST_AUDIO_STREAM), &outputMediaType) - ); - - UINT32 size = 0; - WAVEFORMATEX* waveFormat; - DX::ThrowIfFailed( - MFCreateWaveFormatExFromMFMediaType(outputMediaType.Get(), &waveFormat, &size) - ); - - CopyMemory(&m_waveFormat, waveFormat, sizeof(m_waveFormat)); - CoTaskMemFree(waveFormat); - - PROPVARIANT propVariant; - DX::ThrowIfFailed( - reader->GetPresentationAttribute(static_cast(MF_SOURCE_READER_MEDIASOURCE), MF_PD_DURATION, &propVariant) - ); - // 'duration' is in 100ns units; convert to seconds, and round up - // to the nearest whole byte. - LONGLONG duration = propVariant.uhVal.QuadPart; - unsigned int maxStreamLengthInBytes = - static_cast( - ((duration * static_cast(m_waveFormat.nAvgBytesPerSec)) + 10000000) / - 10000000 - ); - - Platform::Array^ fileData = ref new Platform::Array(maxStreamLengthInBytes); - - ComPtr sample; - ComPtr mediaBuffer; - DWORD flags = 0; - - int positionInData = 0; - bool done = false; - while (!done) - { - DX::ThrowIfFailed( - reader->ReadSample(static_cast(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, nullptr, &flags, nullptr, &sample) - ); - - if (sample != nullptr) - { - DX::ThrowIfFailed( - sample->ConvertToContiguousBuffer(&mediaBuffer) - ); - - BYTE *audioData = nullptr; - DWORD sampleBufferLength = 0; - DX::ThrowIfFailed( - mediaBuffer->Lock(&audioData, nullptr, &sampleBufferLength) - ); - - for (DWORD i = 0; i < sampleBufferLength; i++) - { - fileData[positionInData++] = audioData[i]; - } - } - if (flags & MF_SOURCE_READERF_ENDOFSTREAM) - { - done = true; - } - } - - return fileData; -} \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/MediaReader.h b/DirectXSceneStore/GameContent/MediaReader.h deleted file mode 100644 index 9e7c1fd..0000000 --- a/DirectXSceneStore/GameContent/MediaReader.h +++ /dev/null @@ -1,27 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// MediaReader: -// This is a helper class for the SoundEffect class. It reads small audio files -// synchronously from the package installed folder and returns sound data as a -// byte array. - -ref class MediaReader -{ -internal: - MediaReader(); - - Platform::Array^ LoadMedia(_In_ Platform::String^ filename); - WAVEFORMATEX* GetOutputWaveFormatEx(); - -protected private: - Windows::Storage::StorageFolder^ m_installedLocation; - Platform::String^ m_installedLocationPath; - WAVEFORMATEX m_waveFormat; -}; diff --git a/DirectXSceneStore/GameContent/MeshObject.cpp b/DirectXSceneStore/GameContent/MeshObject.cpp deleted file mode 100644 index ed5530b..0000000 --- a/DirectXSceneStore/GameContent/MeshObject.cpp +++ /dev/null @@ -1,35 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "MeshObject.h" -#include "Common\DirectXSample.h" -#include "ConstantBuffers.h" - -using namespace Microsoft::WRL; -using namespace DirectX; - -MeshObject::MeshObject(): - m_vertexCount(0), - m_indexCount(0) -{ -} - -//-------------------------------------------------------------------------------- - -void MeshObject::Render(_In_ ID3D11DeviceContext *context) -{ - uint32 stride = sizeof(PNTVertex); - uint32 offset = 0; - - context->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset); - context->IASetIndexBuffer(m_indexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0); - context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - context->DrawIndexed(m_indexCount, 0, 0); -} - -//-------------------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/MeshObject.h b/DirectXSceneStore/GameContent/MeshObject.h deleted file mode 100644 index 921942d..0000000 --- a/DirectXSceneStore/GameContent/MeshObject.h +++ /dev/null @@ -1,32 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// MeshObject: -// This class is the generic (abstract) representation of D3D11 Indexed triangle -// list. Each of the derived classes is just the constructor for the specific -// geometry primitive. This abstract class does not place any requirements on -// the format of the geometry directly. -// The primary method of the MeshObject is Render. The default implementation -// just sets the IndexBuffer, VertexBuffer and topology to a TriangleList and -// makes a DrawIndexed call on the context. It assumes all other state has -// already been set on the context. - -ref class MeshObject abstract -{ -internal: - MeshObject(); - - virtual void Render(_In_ ID3D11DeviceContext *context); - -protected private: - Microsoft::WRL::ComPtr m_vertexBuffer; - Microsoft::WRL::ComPtr m_indexBuffer; - int m_vertexCount; - int m_indexCount; -}; diff --git a/DirectXSceneStore/GameContent/MoveLookController.cpp b/DirectXSceneStore/GameContent/MoveLookController.cpp deleted file mode 100644 index 745e1bf..0000000 --- a/DirectXSceneStore/GameContent/MoveLookController.cpp +++ /dev/null @@ -1,833 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "MoveLookController.h" -#include "Common\DirectXSample.h" - -using namespace Windows::UI::Core; -using namespace Windows::UI::Input; -using namespace Windows::UI; -using namespace Windows::Foundation; -using namespace Microsoft::WRL; -using namespace DirectX; -using namespace Windows::Devices::Input; -using namespace Windows::System; - -//---------------------------------------------------------------------- - -MoveLookController::MoveLookController(): - m_autoFire(true), - m_pitch(0.0f), - m_yaw(0.0f), - m_state(MoveLookControllerState::None) -{ - ResetState(); -} - -//---------------------------------------------------------------------- - -bool MoveLookController::IsPauseRequested() -{ - switch (m_state) - { - case MoveLookControllerState::Active: - UpdatePollingDevices(); - if (m_pausePressed) - { -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"IsPauseRequested == true\n"); -#endif - m_pausePressed = false; - return true; - } - else - { - return false; - } - } - return false; -} - -//---------------------------------------------------------------------- - -bool MoveLookController::IsFiring() -{ - if (m_state == MoveLookControllerState::Active) - { - if (m_autoFire) - { - return (m_fireInUse || (m_mouseInUse && m_mouseLeftInUse) || PollingFireInUse()); - } - else - { - if (m_firePressed) - { - m_firePressed = false; - return true; - } - } - } - return false; -} - -//---------------------------------------------------------------------- - -bool MoveLookController::IsPressComplete() -{ - switch (m_state) - { - case MoveLookControllerState::WaitForInput: - UpdatePollingDevices(); - if (m_buttonPressed) - { -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"IsPressComplete == true\n"); -#endif - m_buttonPressed = false; - return true; - } - else - { - return false; - } - break; - } - - return false; -} - -//---------------------------------------------------------------------- - -void MoveLookController::OnPointerPressed( - _In_ CoreWindow^ /* sender */, - _In_ PointerEventArgs^ args - ) -{ - PointerPoint^ point = args->CurrentPoint; - uint32 pointerID = point->PointerId; - Point pointerPosition = point->Position; - PointerPointProperties^ pointProperties = point->Properties; - auto pointerDevice = point->PointerDevice; - auto pointerDeviceType = pointerDevice->PointerDeviceType; - - XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y); - -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Pressed", pointerID, position.x, position.y); -#endif - - switch (m_state) - { - case MoveLookControllerState::WaitForInput: - if (position.x > m_buttonUpperLeft.x && - position.x < m_buttonLowerRight.x && - position.y > m_buttonUpperLeft.y && - position.y < m_buttonLowerRight.y) - { - // Wait until button released before setting variable. - m_buttonPointerID = pointerID; - m_buttonInUse = true; -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"\tWaitForInput(%d) - BUTTON in USE", pointerID); -#endif - } - break; - - case MoveLookControllerState::Active: - switch (pointerDeviceType) - { - case Windows::Devices::Input::PointerDeviceType::Touch: - if (position.x > m_moveUpperLeft.x && - position.x < m_moveLowerRight.x && - position.y > m_moveUpperLeft.y && - position.y < m_moveLowerRight.y) - { - // This pointer is in the move control. - if (!m_moveInUse) - { - // There is not an active pointer in this control yet. - // Process a DPad touch down event. - m_moveFirstDown = position; // Save location of initial contact. - m_movePointerID = pointerID; // Store the pointer using this control. - m_moveInUse = true; - } - } - else if (position.x > m_fireUpperLeft.x && - position.x < m_fireLowerRight.x && - position.y > m_fireUpperLeft.y && - position.y < m_fireLowerRight.y) - { - // This pointer is in the fire control. - if (!m_fireInUse) - { - m_fireLastPoint = position; - m_firePointerID = pointerID; - m_fireInUse = true; - if (!m_autoFire) - { - m_firePressed = true; - } - } - } - else - { - if (!m_lookInUse) - { - // There is not an active pointer in this control yet. - m_lookLastPoint = position; // Save point for later move. - m_lookPointerID = pointerID; // Store the pointer using this control. - m_lookLastDelta.x = m_lookLastDelta.y = 0; // These are for smoothing. - m_lookInUse = true; - } - } - break; - - default: - bool rightButton = pointProperties->IsRightButtonPressed; - bool leftButton = pointProperties->IsLeftButtonPressed; - - if (!m_autoFire && (!m_mouseLeftInUse && leftButton)) - { - m_firePressed = true; - } - - if (!m_mouseInUse) - { - m_mouseInUse = true; - m_mouseLastPoint = position; - m_mousePointerID = pointerID; - m_mouseLeftInUse = leftButton; - m_mouseRightInUse = rightButton; - m_lookLastDelta.x = m_lookLastDelta.y = 0; // These are for smoothing. - } - else - { -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"\tWARNING: OnPointerPressed() Mouse aleady in use (%d-%s%s) and new event id: %d %s%s", - m_mousePointerID, - m_mouseLeftInUse ? "L" : "", - m_mouseRightInUse ? "R" : "", - pointerID, - leftButton ? "L" : "", - rightButton ? "R" : "" - ); -#endif - } - break; - } -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace( - L"\t%s%s%s %s%s%s", - m_moveInUse ? L"Move " : L"", - m_lookInUse ? L"Look " : L"", - m_fireInUse ? L"Fire " : L"", - m_mouseInUse ? L"Mouse:" : L"", - m_mouseLeftInUse ? L"L" : L"-", - m_mouseRightInUse ? L"R" : L"-" - ); -#endif - break; - } -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"\n"); -#endif - return; -} - -//---------------------------------------------------------------------- - -void MoveLookController::OnPointerMoved( - _In_ CoreWindow^ /* sender */, - _In_ PointerEventArgs^ args - ) -{ - PointerPoint^ point = args->CurrentPoint; - uint32 pointerID = point->PointerId; - Point pointerPosition = point->Position; - PointerPointProperties^ pointProperties = point->Properties; - auto pointerDevice = point->PointerDevice; - - XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y); // convert to allow math - -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Moved", pointerID, position.x, position.y); -#endif - - switch (m_state) - { - case MoveLookControllerState::Active: - // Decide which control this pointer is operating. - if (pointerID == m_movePointerID) - { - m_movePointerPosition = position; // Save the current position. - } - else if (pointerID == m_lookPointerID) - { - // Look control. - XMFLOAT2 pointerDelta; - pointerDelta.x = position.x - m_lookLastPoint.x; // How far did pointer move? - pointerDelta.y = position.y - m_lookLastPoint.y; - - XMFLOAT2 rotationDelta; - rotationDelta.x = pointerDelta.x * MoveLookConstants::RotationGain; // Scale for control sensitivity. - rotationDelta.y = pointerDelta.y * MoveLookConstants::RotationGain; - m_lookLastPoint = position; // Save for next time through. - -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"\tDelta (%4.0f, %4.0f)", pointerDelta.x, pointerDelta.y); -#endif - - // Update our orientation based on the command. - m_pitch -= rotationDelta.y; - m_yaw += rotationDelta.x; - - // Limit pitch to straight up or straight down. - float limit = XM_PI / 2.0f - 0.01f; - m_pitch = __max(-limit, m_pitch); - m_pitch = __min(+limit, m_pitch); - - // Keep longitude in sane range by wrapping. - if (m_yaw > XM_PI) - { - m_yaw -= XM_PI * 2.0f; - } - else if (m_yaw < -XM_PI) - { - m_yaw += XM_PI * 2.0f; - } - } - else if (pointerID == m_firePointerID) - { - m_fireLastPoint = position; - } - else if (pointerID == m_mousePointerID) - { - m_mouseLeftInUse = pointProperties->IsLeftButtonPressed; - m_mouseRightInUse = pointProperties->IsRightButtonPressed; - m_mouseLastPoint = position; // Save for next time through. - } - - // Mouse movement is handled via a separate relative mouse movement handler (OnMouseMoved). - - break; - } -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"\n"); -#endif -} - -//---------------------------------------------------------------------- - -void MoveLookController::OnMouseMoved( - _In_ MouseDevice^ /* mouseDevice */, - _In_ MouseEventArgs^ args - ) -{ - // Handle Mouse Input via dedicated relative movement handler. - - switch (m_state) - { - case MoveLookControllerState::Active: - XMFLOAT2 mouseDelta; - mouseDelta.x = static_cast(args->MouseDelta.X); - mouseDelta.y = static_cast(args->MouseDelta.Y); - - XMFLOAT2 rotationDelta; - rotationDelta.x = mouseDelta.x * MoveLookConstants::RotationGain; // Scale for control sensitivity. - rotationDelta.y = mouseDelta.y * MoveLookConstants::RotationGain; - - // Update our orientation based on the command. - m_pitch -= rotationDelta.y; - m_yaw += rotationDelta.x; - - // Limit pitch to straight up or straight down. - float limit = XM_PI / 2.0f - 0.01f; - m_pitch = __max(-limit, m_pitch); - m_pitch = __min(+limit, m_pitch); - - // Keep longitude in sane range by wrapping. - if (m_yaw > XM_PI) - { - m_yaw -= XM_PI * 2.0f; - } - else if (m_yaw < -XM_PI) - { - m_yaw += XM_PI * 2.0f; - } - break; - } -} - -//---------------------------------------------------------------------- - -void MoveLookController::OnPointerReleased( - _In_ CoreWindow^ /* sender */, - _In_ PointerEventArgs^ args - ) -{ - PointerPoint^ point = args->CurrentPoint; - uint32 pointerID = point->PointerId; - Point pointerPosition = point->Position; - PointerPointProperties^ pointProperties = point->Properties; - - XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y); - -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Release", pointerID, position.x, position.y); -#endif - - switch (m_state) - { - case MoveLookControllerState::WaitForInput: - if (m_buttonInUse && (pointerID == m_buttonPointerID)) - { - m_buttonInUse = false; - m_buttonPressed = true; -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"\tWaitForInput: ButtonPressed = true\n"); -#endif - } - break; - - case MoveLookControllerState::Active: - if (pointerID == m_movePointerID) - { - m_velocity = XMFLOAT3(0, 0, 0); // Stop on release. - m_moveInUse = false; - m_movePointerID = 0; - } - else if (pointerID == m_lookPointerID) - { - m_lookInUse = false; - m_lookPointerID = 0; - } - else if (pointerID == m_firePointerID) - { - m_fireInUse = false; - m_firePointerID = 0; - } - else if (pointerID == m_mousePointerID) - { - bool rightButton = pointProperties->IsRightButtonPressed; - bool leftButton = pointProperties->IsLeftButtonPressed; - - m_mouseInUse = false; - - // Don't clear the mouse Pointer ID so that Move events still result in Look changes. - m_mouseLeftInUse = leftButton; - m_mouseRightInUse = rightButton; - } - break; - } -} - -//---------------------------------------------------------------------- - -void MoveLookController::OnPointerExited( - _In_ CoreWindow^ /* sender */, - _In_ PointerEventArgs^ args - ) -{ - PointerPoint^ point = args->CurrentPoint; - uint32 pointerID = point->PointerId; - Point pointerPosition = point->Position; - PointerPointProperties^ pointProperties = point->Properties; - - XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y); - -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Exit", pointerID, position.x, position.y); -#endif - - switch (m_state) - { - case MoveLookControllerState::WaitForInput: - if (m_buttonInUse && (pointerID == m_buttonPointerID)) - { - m_buttonInUse = false; - m_buttonPressed = false; -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"\tWaitForPress: ButtonPressed = false -- Got Exit Event\n"); -#endif - } - break; - - case MoveLookControllerState::Active: - if (pointerID == m_movePointerID) - { - m_velocity = XMFLOAT3(0, 0, 0); // Stop on release. - m_moveInUse = false; - m_movePointerID = 0; - } - else if (pointerID == m_lookPointerID) - { - m_lookInUse = false; - m_lookPointerID = 0; - } - else if (pointerID == m_firePointerID) - { - m_fireInUse = false; - m_firePointerID = 0; - } - else if (pointerID == m_mousePointerID) - { - m_mouseInUse = false; - m_mousePointerID = 0; - m_mouseLeftInUse = false; - m_mouseRightInUse = false; - } - break; - } -} - -//---------------------------------------------------------------------- - -void MoveLookController::OnKeyDown( - _In_ CoreWindow^ /* sender */, - _In_ KeyEventArgs^ args - ) -{ - Windows::System::VirtualKey Key; - Key = args->VirtualKey; - - // Figure out the command from the keyboard. - if (Key == VirtualKey::W) - m_forward = true; - if (Key == VirtualKey::S) - m_back = true; - if (Key == VirtualKey::A) - m_left = true; - if (Key == VirtualKey::D) - m_right = true; - if (Key == VirtualKey::Space) - m_up = true; - if (Key == VirtualKey::X) - m_down = true; - if (Key == VirtualKey::P) - m_pause = true; -} - -//---------------------------------------------------------------------- - -void MoveLookController::OnKeyUp( - _In_ CoreWindow^ /* sender */, - _In_ KeyEventArgs^ args - ) -{ - Windows::System::VirtualKey Key; - Key = args->VirtualKey; - - // Figure out the command from the keyboard. - if (Key == VirtualKey::W) - m_forward = false; - if (Key == VirtualKey::S) - m_back = false; - if (Key == VirtualKey::A) - m_left = false; - if (Key == VirtualKey::D) - m_right = false; - if (Key == VirtualKey::Space) - m_up = false; - if (Key == VirtualKey::X) - m_down = false; - if (Key == VirtualKey::P) - { - if (m_pause) - { - // Trigger pause only once on button release. - m_pausePressed = true; - m_pause = false; - } - } -} - -//---------------------------------------------------------------------- - -void MoveLookController::ResetState() -{ - // Reset the state of the controller. - // Disable any active pointer IDs to stop all interaction. - m_buttonPressed = false; - m_pausePressed = false; - m_buttonInUse = false; - m_moveInUse = false; - m_lookInUse = false; - m_fireInUse = false; - m_mouseInUse = false; - m_mouseLeftInUse = false; - m_mouseRightInUse = false; - m_movePointerID = 0; - m_lookPointerID = 0; - m_firePointerID = 0; - m_mousePointerID = 0; - m_velocity = XMFLOAT3(0.0f, 0.0f, 0.0f); - m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f); - m_forward = false; - m_back = false; - m_left = false; - m_right = false; - m_up = false; - m_down = false; - m_pause = false; -} - -//---------------------------------------------------------------------- - -void MoveLookController::SetMoveRect ( - _In_ XMFLOAT2 upperLeft, - _In_ XMFLOAT2 lowerRight - ) -{ -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"MoveRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y); -#endif - m_moveUpperLeft = upperLeft; - m_moveLowerRight = lowerRight; -} - -//---------------------------------------------------------------------- - -void MoveLookController::SetFireRect ( - _In_ XMFLOAT2 upperLeft, - _In_ XMFLOAT2 lowerRight - ) -{ -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"FireRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y); -#endif - m_fireUpperLeft = upperLeft; - m_fireLowerRight = lowerRight; -} - -//---------------------------------------------------------------------- - -void MoveLookController::WaitForPress( - _In_ XMFLOAT2 upperLeft, - _In_ XMFLOAT2 lowerRight - ) -{ -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"WaitForPress (%.1f, %.1f) to (%.1f, %.1f)\n", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y); -#endif - - ResetState(); - m_state = MoveLookControllerState::WaitForInput; - m_buttonUpperLeft = upperLeft; - m_buttonLowerRight = lowerRight; - ShowCursor(); -} - -//---------------------------------------------------------------------- - -void MoveLookController::WaitForPress() -{ -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"WaitForPress (null rect)\n"); -#endif - - ResetState(); - m_state = MoveLookControllerState::WaitForInput; - m_buttonUpperLeft.x = 0.0f; - m_buttonUpperLeft.y = 0.0f; - m_buttonLowerRight.x = 0.0f; - m_buttonLowerRight.y = 0.0f; - ShowCursor(); -} - -//---------------------------------------------------------------------- - -XMFLOAT3 MoveLookController::Velocity() -{ - return m_velocity; -} - -//---------------------------------------------------------------------- - -XMFLOAT3 MoveLookController::LookDirection() -{ - XMFLOAT3 lookDirection; - - float r = cosf(m_pitch); // In the plane. - lookDirection.y = sinf(m_pitch); // Vertical. - lookDirection.z = r * cosf(m_yaw); // Fwd-back. - lookDirection.x = r * sinf(m_yaw); // Left-right. - - return lookDirection; -} - -//---------------------------------------------------------------------- - -float MoveLookController::Pitch() -{ - return m_pitch; -} - -//---------------------------------------------------------------------- - -void MoveLookController::Pitch(_In_ float pitch) -{ - m_pitch = pitch; -} - -//---------------------------------------------------------------------- - -float MoveLookController::Yaw() -{ - return m_yaw; -} - -//---------------------------------------------------------------------- - -void MoveLookController::Yaw(_In_ float yaw) -{ - m_yaw = yaw; -} - -//---------------------------------------------------------------------- - -void MoveLookController::Active(_In_ bool active) -{ - ResetState(); -#ifdef MOVELOOKCONTROLLER_TRACE - DebugTrace(L"Active = %s\n", active ? L"true" : L"false"); -#endif - - if (active) - { - m_state = MoveLookControllerState::Active; - //HideCursor(); - - } - else - { - m_state = MoveLookControllerState::None; - //ShowCursor(); - } -} - -//---------------------------------------------------------------------- - -bool MoveLookController::Active() -{ - if (m_state == MoveLookControllerState::Active) - { - return true; - } - else - { - return false; - } -} - -//---------------------------------------------------------------------- - -void MoveLookController::AutoFire(_In_ bool autoFire) -{ - m_autoFire = autoFire; -} - -//---------------------------------------------------------------------- - -bool MoveLookController::AutoFire() -{ - return m_autoFire; -} - -//---------------------------------------------------------------------- - -void MoveLookController::Update() -{ - UpdatePollingDevices(); - - if (m_moveInUse) - { - // Move control. - XMFLOAT2 pointerDelta; - - pointerDelta.x = m_movePointerPosition.x - m_moveFirstDown.x; - pointerDelta.y = m_movePointerPosition.y - m_moveFirstDown.y; - - // Figure out the command from the virtual joystick. - XMFLOAT3 commandDirection = XMFLOAT3(0.0f, 0.0f, 0.0f); - if (fabsf(pointerDelta.x) > 16.0f) // Leave 32 pixel-wide dead spot for being still. - m_moveCommand.x -= pointerDelta.x/fabsf(pointerDelta.x); - - if (fabsf(pointerDelta.y) > 16.0f) - m_moveCommand.y -= pointerDelta.y/fabsf(pointerDelta.y); - } - - // Poll our state bits set by the keyboard input events. - if (m_forward) - { - m_moveCommand.y += 1.0f; - } - if (m_back) - { - m_moveCommand.y -= 1.0f; - } - if (m_left) - { - m_moveCommand.x += 1.0f; - } - if (m_right) - { - m_moveCommand.x -= 1.0f; - } - if (m_up) - { - m_moveCommand.z += 1.0f; - } - if (m_down) - { - m_moveCommand.z -= 1.0f; - } - - // Make sure that 45deg cases are not faster. - if (fabsf(m_moveCommand.x) > 0.1f || - fabsf(m_moveCommand.y) > 0.1f || - fabsf(m_moveCommand.z) > 0.1f) - { - XMStoreFloat3(&m_moveCommand, XMVector3Normalize(XMLoadFloat3(&m_moveCommand))); - } - - // Rotate command to align with our direction (world coordinates). - XMFLOAT3 wCommand; - wCommand.x = m_moveCommand.x * cosf(m_yaw) - m_moveCommand.y * sinf(m_yaw); - wCommand.y = m_moveCommand.x * sinf(m_yaw) + m_moveCommand.y * cosf(m_yaw); - wCommand.z = m_moveCommand.z; - - // Scale for sensitivity adjustment. - // Our velocity is based on the command. Y is up. - m_velocity.x = -wCommand.x * MoveLookConstants::MovementGain; - m_velocity.z = wCommand.y * MoveLookConstants::MovementGain; - m_velocity.y = wCommand.z * MoveLookConstants::MovementGain; - - // Clear movement input accumulator for use during next frame. - m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f); -} - -//---------------------------------------------------------------------- - -#ifdef MOVELOOKCONTROLLER_TRACE -void MoveLookController::DebugTrace(const wchar_t *format, ...) -{ - // Generate the message string. - va_list args; - va_start(args, format); - wchar_t message[1024]; - vswprintf_s(message, 1024, format, args); - OutputDebugStringW(message); -} -#endif - -//---------------------------------------------------------------------- - -void MoveLookController::Fire() -{ - m_firePressed = true; -} \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/MoveLookController.h b/DirectXSceneStore/GameContent/MoveLookController.h deleted file mode 100644 index 44227e5..0000000 --- a/DirectXSceneStore/GameContent/MoveLookController.h +++ /dev/null @@ -1,231 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// MoveLookController: -// This is the class that handles input events and turns it into player -// intent. It aggregates, mouse, keyboard, touch and Polled device input -// (like the XBox controller) into a unified single controller. -// The controller has three modes of operation: -// None - the controller is not active and all input is ignored. -// WaitForInput - the controller is waiting for the player to acknowledge -// a message from the app. Only a left mouse click or touch event -// in the rectangle specified in the WaitForPress method or the -// 'Start' button has been pressed on the Xbox controller will -// result in IsPressComplete returning true. -// Active - the controller is in active game play mode. -// -// This class provides input handlers that can be associated directly with a CoreWindow -// object. As an abstract class the association is left to the derived class. -// Input handlers are available for the following events: -// PointerPressed -// PointerMoved -// PointerReleased -// PointerExited -// KeyDown -// KeyUp -// MouseMoved -// -// During 'Active' mode, the controller will put the mouse into relative mouse -// mode by turning off the pointer cursor. In this mode the controller separates -// mouse movement from pointer movement and uses the relative mouse movements to -// update the controller for the Look Control. -// -// The touch portion of the MoveLookController divides the window area of the app -// into three distinct regions: -// MoveRect - the rectangle of the screen where touch input is converted into -// a virtual joystick where the vertical motion will be translated into -// forward/backward position motion and horizontal motion will be translated -// into left/right position motion. -// FireRect - the rectangle of the screen where touch input will be converted -// into a fire button. A touch sequence of PointerPressed will result in -// IsFiring method to return true in AutoFire mode, otherwise a PointPressed -// followed by a PointerReleased event in the FireRect will result in the -// IsFiring method returning true once. -// Outside MoveRect & FireRect - this area of the screen controls the Look control -// and updates the LookDirection. -// -// The keyboard/mouse are used as a pair to provide a typical PC gaming input model in Active -// mode: -// Mouse - is mapped to the look control. Left mouse is mapped to IsFiring or 'Fire' button -// W key - is mapped to the 'forward' motion of the move control -// S key - is mapped to the 'back' motion of the move control -// A key - is mapped to the 'left' motion of the move control -// D key - is mapped to the 'right' motion of the move control -// key - is mapped to the 'up' motion of the move control -// X key - is mapped to the 'down' motion of the move control -// P key - is mapped to IsPauseRequested -// -// This abstract class enables Polling devices like the XBox controller -// with several methods that can be overridden: -// UpdatePollingDevices - will be called at the beginning of update -// and as a part of checking for pause requests -// PollingFireInUse - can use used to indicate a fire button is -// currently depressed. -// ResetState - can be augumented to reset an stored state associated -// with the polling devices -// -// Because the MoveLookController can be use in a variety of environments -// such as on a separate thread, or on devices that don't support setting a -// cursor, the implementation of the ShowCursor() and HideCursor() methods -// are left to the derived class implementation. -// -// The MoveLookController collects input from each of the input events. -// On the Update method it calls UpdatePollingDevices to update state. -// All the inputs are coalesced and merged to generate a velocity vector -// and update the Pitch and Yaw values. - -// Uncomment the next line to print debug tracing information. -// #define MOVELOOKCONTROLLER_TRACE 1 - -enum class MoveLookControllerState -{ - None, - WaitForInput, - Active, -}; - -namespace MoveLookConstants -{ - static const float RotationGain = 0.008f; // Sensitivity adjustment for look controller. - static const float MovementGain = 2.0f; // Sensitivity adjustment for move controller. -}; - -ref class MoveLookController abstract -{ -internal: - MoveLookController(); - - void SetMoveRect( - _In_ DirectX::XMFLOAT2 upperLeft, - _In_ DirectX::XMFLOAT2 lowerRight - ); - void SetFireRect( - _In_ DirectX::XMFLOAT2 upperLeft, - _In_ DirectX::XMFLOAT2 lowerRight - ); - void WaitForPress( - _In_ DirectX::XMFLOAT2 UpperLeft, - _In_ DirectX::XMFLOAT2 LowerRight - ); - void WaitForPress(); - - void Update(); - - bool IsFiring(); - bool IsPressComplete(); - bool IsPauseRequested(); - - DirectX::XMFLOAT3 Velocity(); - DirectX::XMFLOAT3 LookDirection(); - float Pitch(); - void Pitch(_In_ float pitch); - float Yaw(); - void Yaw(_In_ float yaw); - bool Active(); - void Active(_In_ bool active); - - bool AutoFire(); - void AutoFire(_In_ bool AutoFire); - - void Fire(); - -protected: - virtual void ResetState(); - virtual void UpdatePollingDevices() {}; - virtual bool PollingFireInUse() { return false; } - virtual void ShowCursor() {}; - virtual void HideCursor() {}; - - void OnPointerPressed( - _In_ Windows::UI::Core::CoreWindow^ sender, - _In_ Windows::UI::Core::PointerEventArgs^ args - ); - void OnPointerMoved( - _In_ Windows::UI::Core::CoreWindow^ sender, - _In_ Windows::UI::Core::PointerEventArgs^ args - ); - void OnPointerReleased( - _In_ Windows::UI::Core::CoreWindow^ sender, - _In_ Windows::UI::Core::PointerEventArgs^ args - ); - void OnPointerExited( - _In_ Windows::UI::Core::CoreWindow^ sender, - _In_ Windows::UI::Core::PointerEventArgs^ args - ); - void OnKeyDown( - _In_ Windows::UI::Core::CoreWindow^ sender, - _In_ Windows::UI::Core::KeyEventArgs^ args - ); - void OnKeyUp( - _In_ Windows::UI::Core::CoreWindow^ sender, - _In_ Windows::UI::Core::KeyEventArgs^ args - ); - void OnMouseMoved( - _In_ Windows::Devices::Input::MouseDevice^ mouseDevice, - _In_ Windows::Devices::Input::MouseEventArgs^ args - ); - -#ifdef MOVELOOKCONTROLLER_TRACE - void DebugTrace(const wchar_t *format, ...); -#endif - -protected private: - // Properties of the controller object. - MoveLookControllerState m_state; - DirectX::XMFLOAT3 m_velocity; // How far we move in this frame. - float m_pitch; - float m_yaw; // Orientation euler angles in radians. - - // Properties of the Move control. - DirectX::XMFLOAT2 m_moveUpperLeft; // Bounding box where this control will activate. - DirectX::XMFLOAT2 m_moveLowerRight; - bool m_moveInUse; // The move control is in use. - uint32 m_movePointerID; // Id of the pointer in this control. - DirectX::XMFLOAT2 m_moveFirstDown; // Point where initial contact occurred. - DirectX::XMFLOAT2 m_movePointerPosition; // Point where the move pointer is currently located. - DirectX::XMFLOAT3 m_moveCommand; // The net command from the move control. - - // Properties of the Look control. - bool m_lookInUse; // The look control is in use. - uint32 m_lookPointerID; // Id of the pointer in this control. - DirectX::XMFLOAT2 m_lookLastPoint; // Last point (from last frame). - DirectX::XMFLOAT2 m_lookLastDelta; // The delta used for smoothing between frames. - - // Properties of the Fire control. - bool m_autoFire; - bool m_firePressed; - DirectX::XMFLOAT2 m_fireUpperLeft; // Bounding box where this control will activate. - DirectX::XMFLOAT2 m_fireLowerRight; - bool m_fireInUse; // The fire control in in use. - UINT32 m_firePointerID; // Id of the pointer in this control. - DirectX::XMFLOAT2 m_fireLastPoint; // Last fire position. - - // Properties of the Mouse control. This is a combination of Look and Fire. - bool m_mouseInUse; - uint32 m_mousePointerID; - DirectX::XMFLOAT2 m_mouseLastPoint; - bool m_mouseLeftInUse; - bool m_mouseRightInUse; - - bool m_buttonInUse; - uint32 m_buttonPointerID; - DirectX::XMFLOAT2 m_buttonUpperLeft; - DirectX::XMFLOAT2 m_buttonLowerRight; - bool m_buttonPressed; - bool m_pausePressed; - - // Input states for Keyboard. - bool m_forward; - bool m_back; // States for movement. - bool m_left; - bool m_right; - bool m_up; - bool m_down; - bool m_pause; -}; diff --git a/DirectXSceneStore/GameContent/PixelShader.hlsl b/DirectXSceneStore/GameContent/PixelShader.hlsl deleted file mode 100644 index 9499f80..0000000 --- a/DirectXSceneStore/GameContent/PixelShader.hlsl +++ /dev/null @@ -1,27 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "ConstantBuffers.hlsli" - -float4 main(PixelShaderInput input) : SV_Target -{ - float diffuseLuminance = - max(0.0f, dot(input.normal, input.vertexToLight0)) + - max(0.0f, dot(input.normal, input.vertexToLight1)) + - max(0.0f, dot(input.normal, input.vertexToLight2)) + - max(0.0f, dot(input.normal, input.vertexToLight3)); - - // Normalize view space vertex-to-eye - input.vertexToEye = normalize(input.vertexToEye); - - float specularLuminance = 1.0f; - - float4 specular; - specular = specularColor * specularLuminance * 0.5f; - - return diffuseTexture.Sample(linearSampler, input.textureUV) * diffuseColor * diffuseLuminance * 0.5f + specular; -} diff --git a/DirectXSceneStore/GameContent/PixelShaderFlat.hlsl b/DirectXSceneStore/GameContent/PixelShaderFlat.hlsl deleted file mode 100644 index e07df07..0000000 --- a/DirectXSceneStore/GameContent/PixelShaderFlat.hlsl +++ /dev/null @@ -1,13 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "ConstantBuffers.hlsli" - -float4 main(PixelShaderFlatInput input) : SV_Target -{ - return diffuseTexture.Sample(linearSampler, input.textureUV) * input.diffuseColor; -} diff --git a/DirectXSceneStore/GameContent/SoundEffect.cpp b/DirectXSceneStore/GameContent/SoundEffect.cpp deleted file mode 100644 index e2f9c8c..0000000 --- a/DirectXSceneStore/GameContent/SoundEffect.cpp +++ /dev/null @@ -1,79 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "SoundEffect.h" -#include "Common\DirectXSample.h" - -SoundEffect::SoundEffect(): - m_audioAvailable(false) -{ -} - -//---------------------------------------------------------------------- - -void SoundEffect::Initialize( - _In_ IXAudio2 *masteringEngine, - _In_ WAVEFORMATEX *sourceFormat, - _In_ Platform::Array^ soundData) -{ - m_soundData = soundData; - - if (masteringEngine == nullptr) - { - // Audio is not available so just return. - m_audioAvailable = false; - return; - } - - // Create a source voice for this sound effect. - DX::ThrowIfFailed( - masteringEngine->CreateSourceVoice( - &m_sourceVoice, - sourceFormat - ) - ); - m_audioAvailable = true; -} - -//---------------------------------------------------------------------- - -void SoundEffect::PlaySound(_In_ float volume) -{ - XAUDIO2_BUFFER buffer = {0}; - - if (!m_audioAvailable) - { - // Audio is not available so just return. - return; - } - - // Interrupt sound effect if it is currently playing. - DX::ThrowIfFailed( - m_sourceVoice->Stop() - ); - DX::ThrowIfFailed( - m_sourceVoice->FlushSourceBuffers() - ); - - // Queue the memory buffer for playback and start the voice. - buffer.AudioBytes = m_soundData->Length; - buffer.pAudioData = m_soundData->Data; - buffer.Flags = XAUDIO2_END_OF_STREAM; - - DX::ThrowIfFailed( - m_sourceVoice->SetVolume(volume) - ); - DX::ThrowIfFailed( - m_sourceVoice->SubmitSourceBuffer(&buffer) - ); - DX::ThrowIfFailed( - m_sourceVoice->Start() - ); -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/SoundEffect.h b/DirectXSceneStore/GameContent/SoundEffect.h deleted file mode 100644 index e91b014..0000000 --- a/DirectXSceneStore/GameContent/SoundEffect.h +++ /dev/null @@ -1,32 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// SoundEffect: -// This class plays a sound using XAudio2. It uses a mastering voice provided -// from the Audio class. The sound data can be read from disk using the MediaReader -// class. - -ref class SoundEffect -{ -internal: - SoundEffect(); - - void Initialize( - _In_ IXAudio2* masteringEngine, - _In_ WAVEFORMATEX* sourceFormat, - _In_ Platform::Array^ soundData - ); - - void PlaySound(_In_ float volume); - -protected private: - bool m_audioAvailable; - IXAudio2SourceVoice* m_sourceVoice; - Platform::Array^ m_soundData; -}; diff --git a/DirectXSceneStore/GameContent/Sphere.cpp b/DirectXSceneStore/GameContent/Sphere.cpp deleted file mode 100644 index 18eb801..0000000 --- a/DirectXSceneStore/GameContent/Sphere.cpp +++ /dev/null @@ -1,79 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "Sphere.h" - -using namespace DirectX; - -//---------------------------------------------------------------------- - -Sphere::Sphere() -{ - m_position = XMFLOAT3(0.0f, 0.0f, 0.0f); - m_radius = 1.0f; - Update(); -} - -//---------------------------------------------------------------------- - -Sphere::Sphere( - DirectX::XMFLOAT3 position, - float radius - ) -{ - m_position = position; - m_radius = radius; - Update(); -} - -//---------------------------------------------------------------------- - -void Sphere::Update() -{ - XMStoreFloat4x4( - &m_modelMatrix, - XMMatrixScaling(m_radius, m_radius, m_radius) * - XMMatrixTranslation(m_position.x, m_position.y, m_position.z) - ); -} - -//---------------------------------------------------------------------- - -bool Sphere::IsTouching( - XMFLOAT3 point, - float radius, - _Out_ XMFLOAT3 *contact, - _Out_ XMFLOAT3 *normal - ) -{ - // Check collision between instances One and Two. - // oneToTwo is the collision normal vector. - XMVECTOR oneToTwo = XMLoadFloat3(&m_position) - XMLoadFloat3(&point); - - float distance = XMVectorGetX(XMVector3Length(oneToTwo)); - - oneToTwo = XMVector3Normalize(oneToTwo); - XMStoreFloat3(normal, oneToTwo); - XMStoreFloat3(contact, oneToTwo * m_radius); - - if (distance < 0.0f) - { - distance *= -1.0f; - } - - if (distance < (radius + m_radius)) - { - return true; - } - else - { - return false; - } -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/Sphere.h b/DirectXSceneStore/GameContent/Sphere.h deleted file mode 100644 index e12845b..0000000 --- a/DirectXSceneStore/GameContent/Sphere.h +++ /dev/null @@ -1,62 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Sphere: -// This class is a specialization of GameObject that represents a sphere primitive. -// The sphere is defined by a 'position' and radius. - -#include "GameObject.h" - -ref class Sphere: public GameObject -{ -internal: - Sphere(); - Sphere(DirectX::XMFLOAT3 pos, float radius); - - void Position(DirectX::XMFLOAT3 position); - void Position(DirectX::XMVECTOR position); - void Radius(float radius); - float Radius(); - - virtual bool IsTouching( - DirectX::XMFLOAT3 point, - float radius, - _Out_ DirectX::XMFLOAT3 *contact, - _Out_ DirectX::XMFLOAT3 *normal - ) override; - -private: - void Update(); - - float m_radius; -}; - - -__forceinline void Sphere::Position(DirectX::XMFLOAT3 position) -{ - m_position = position; - Update(); -} - -__forceinline void Sphere::Position(DirectX::XMVECTOR position) -{ - DirectX::XMStoreFloat3(&m_position, position); - Update(); -} - -__forceinline void Sphere::Radius(float radius) -{ - m_radius = radius; - Update(); -} - -__forceinline float Sphere::Radius() -{ - return m_radius; -} \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/SphereMesh.cpp b/DirectXSceneStore/GameContent/SphereMesh.cpp deleted file mode 100644 index eaf2a09..0000000 --- a/DirectXSceneStore/GameContent/SphereMesh.cpp +++ /dev/null @@ -1,100 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "SphereMesh.h" -#include "Common\DirectXSample.h" -#include "ConstantBuffers.h" - -using namespace Microsoft::WRL; -using namespace DirectX; - -SphereMesh::SphereMesh(_In_ ID3D11Device *device, uint32 segments) -{ - D3D11_BUFFER_DESC bd = {0}; - D3D11_SUBRESOURCE_DATA initData = {0}; - - uint32 slices = segments / 2; - uint32 numVertices = (slices + 1) * (segments + 1) + 1; - uint32 numIndices = slices * segments * 3 * 2; - - std::vector point(numVertices); - std::vector index(numIndices); - - // To make the texture look right on the top and bottom of the sphere - // each slice will have 'segments + 1' vertices. The top and bottom - // vertices will all be coincident, but have different U texture cooordinates. - uint32 p = 0; - for (uint32 a = 0; a <= slices; a++) - { - float angle1 = static_cast(a) / static_cast(slices) * XM_PI; - float z = cos(angle1); - float r = sin(angle1); - for (uint32 b = 0; b <= segments; b++) - { - float angle2 = static_cast(b) / static_cast(segments) * XM_2PI; - point[p].position = XMFLOAT3(r * cos(angle2), r * sin(angle2), z); - point[p].normal = point[p].position; - point[p].textureCoordinate = XMFLOAT2((1.0f-z) / 2.0f, static_cast(b) / static_cast(segments)); - p++; - } - } - m_vertexCount = p; - - p = 0; - for (uint16 a = 0; a < slices; a++) - { - uint16 p1 = a * (segments + 1); - uint16 p2 = (a + 1) * (segments + 1); - - // Generate two triangles for each segment around the slice. - for (uint16 b = 0; b < segments; b++) - { - if (a < (slices - 1)) - { - // For all but the bottom slice add the triangle with one - // vertex in the a slice and two vertices in the a + 1 slice. - // Skip it for the bottom slice since the triangle would be - // degenerate as all the vertices in the bottom slice are coincident. - index[p] = b + p1; - index[p+1] = b + p2; - index[p+2] = b + p2 + 1; - p = p + 3; - } - if (a > 0) - { - // For all but the top slice add the triangle with two - // vertices in the a slice and one vertex in the a + 1 slice. - // Skip it for the top slice since the triangle would be - // degenerate as all the vertices in the top slice are coincident. - index[p] = b + p1; - index[p+1] = b + p2 + 1; - index[p+2] = b + p1 + 1; - p = p + 3; - } - } - } - m_indexCount = p; - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount; - bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = point.data(); - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_vertexBuffer) - ); - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(uint16) * m_indexCount; - bd.BindFlags = D3D11_BIND_INDEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = index.data(); - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_indexBuffer) - ); -} diff --git a/DirectXSceneStore/GameContent/SphereMesh.h b/DirectXSceneStore/GameContent/SphereMesh.h deleted file mode 100644 index 1075e96..0000000 --- a/DirectXSceneStore/GameContent/SphereMesh.h +++ /dev/null @@ -1,21 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// SphereMesh: -// This class derives from MeshObject and creates a ID3D11Buffer of -// vertices and indices to represent a canonical sphere that is -// positioned at the origin with a radius of 1.0. - -#include "MeshObject.h" - -ref class SphereMesh: public MeshObject -{ -internal: - SphereMesh(_In_ ID3D11Device *device, uint32 segments); -}; diff --git a/DirectXSceneStore/GameContent/StereoProjection.cpp b/DirectXSceneStore/GameContent/StereoProjection.cpp deleted file mode 100644 index 1c2032f..0000000 --- a/DirectXSceneStore/GameContent/StereoProjection.cpp +++ /dev/null @@ -1,180 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "StereoProjection.h" - -#if !defined(XMASSERT) -#define XMASSERT(Expression) ((void)0) -#endif // !XMASSERT - -using namespace DirectX; - -void StereoCreateDefaultParameters(_Out_ STEREO_PARAMETERS* stereoParameters) -{ - XMASSERT(stereoParameters != nullptr); - - // Default assumption is 1920x1200 resolution, a 22" LCD monitor, and a 2' viewing distance - stereoParameters->viewerDistanceInches = 24.0f; - stereoParameters->pixelResolutionWidth = 1920.0f; - stereoParameters->pixelResolutionHeight = 1024.0f; // 480.0f; // 1200 - stereoParameters->displaySizeInches = 22.0f; - - stereoParameters->stereoSeparationFactor = 1.0f; - stereoParameters->stereoExaggerationFactor = 1.0f; -} - -__forceinline bool _XMMatrixStereoProjectionHelper ( - const STEREO_PARAMETERS* stereoParameters, - _Out_ float* virtualProjection, - _Out_ float* zNearWidth, - _Out_ float* zNearHeight, - float fovAngleY, - float aspectHByW, - float nearZ - ) -{ - // note that most people have difficulty fusing images into 3D - // if the separation equals even just the human average. by - // reducing the separation (interocular distance) by 1/2, we - // guarantee a larger subset of people will see full 3D - - // the conservative setting should always be used. the only problem - // with the conservative setting is that the 3D effect will be less - // impressive on smaller screens (which makes sense, since your eye - // cannot be tricked as easily based on the smaller fov). to simulate - // the effect of a larger screen, use the liberal settings (debug only) - - // Conservative Settings: * max acuity angle: 0.8f degrees * interoc distance: 1.25 inches - - // Liberal Settings: * max acuity angle: 1.6f degrees * interoc distance: 2.5f inches - - // maximum visual accuity angle allowed is 3.2 degrees for - // a physical scene, and 1.6 degrees for a virtual one. - // thus we cannot allow an object to appear any closer to - // the viewer than 1.6 degrees (divided by two for most - // half-angle calculations) - - static const float maxStereoDistance = 85; // 780 inches (should be between 10 and 20m) - static const float maxVisualAcuityAngle = 0.8f * (XM_PI / 180.0f); // radians - static const float interocularDistance = 1.25f; // inches - - bool comfortableResult = true; - - float displayHeight = stereoParameters->displaySizeInches / sqrtf(aspectHByW * aspectHByW + 1.0f); - float displayWidth = displayHeight * aspectHByW; - float halfInterocular = 0.5f * interocularDistance * stereoParameters->stereoExaggerationFactor; - float halfPixelWidth = displayWidth / stereoParameters->pixelResolutionWidth * 0.5f; - float halfMaximumAcuityAngle = maxVisualAcuityAngle * 0.5f * stereoParameters->stereoExaggerationFactor; - - float maxSeparationAcuityAngle = atanf(halfInterocular / maxStereoDistance); - float maxSeparationDistance = halfPixelWidth / tanf(maxSeparationAcuityAngle); - float refinedMaxStereoDistance = maxStereoDistance - maxSeparationDistance; - float fovHalfAngle = fovAngleY / 2.0f; - - if (refinedMaxStereoDistance < 0.0f || maxSeparationDistance > 0.1f * maxStereoDistance) - { - // Pixel resolution is too low to offer a comfortable stereo experience - comfortableResult = false; - } - - float refinedMaxSeparationAcuityAngle = atanf(halfInterocular / refinedMaxStereoDistance); - float physicalZNearDistance = halfInterocular / tanf(halfMaximumAcuityAngle); - - float nearZSeparation = tanf(refinedMaxSeparationAcuityAngle) * (refinedMaxStereoDistance - physicalZNearDistance); - - *zNearHeight = cosf(fovHalfAngle) / sinf(fovHalfAngle); - *zNearWidth = *zNearHeight / aspectHByW; - *virtualProjection = (nearZSeparation * nearZ * (*zNearWidth * 4.0f)) / (2.0f * nearZ); - - return comfortableResult; -} - - -XMMATRIX MatrixStereoProjectionFovLH ( - _In_opt_ const STEREO_PARAMETERS* stereoParameters, - STEREO_CHANNEL channel, - float fovAngleY, - float aspectHByW, - float nearZ, - float farZ, - STEREO_MODE stereoMode - ) -{ - float virtualProjection = 0.0f; - float zNearWidth = 0.0f; - float zNearHeight = 0.0f; - float invertedAngle; - XMMATRIX patchedProjection; - XMMATRIX proj; - STEREO_PARAMETERS defaultParameters; - - XMASSERT(channel == STEREO_CHANNEL::LEFT || channel == STEREO_CHANNEL::RIGHT); - XMASSERT(stereoMode == STEREO_MODE::NORMAL || stereoMode == STEREO_MODE::INVERTED); - XMASSERT(!XMScalarNearEqual(fovAngleY, 0.0f, 0.00001f * 2.0f)); - XMASSERT(!XMScalarNearEqual(aspectHByW, 0.0f, 0.00001f)); - XMASSERT(!XMScalarNearEqual(farZ, nearZ, 0.00001f)); - - proj = XMMatrixIdentity(); - - if (stereoParameters == nullptr) - { - StereoCreateDefaultParameters(&defaultParameters); - stereoParameters = &defaultParameters; - } - - XMASSERT(pStereoParameters->stereoSeparationFactor >= 0.0f && stereoParameters->stereoSeparationFactor <= 1.0f); - XMASSERT(pStereoParameters->stereoExaggerationFactor >= 1.0f && stereoParameters->stereoExaggerationFactor <= 2.0f); - - _XMMatrixStereoProjectionHelper(stereoParameters, &virtualProjection, &zNearWidth, &zNearHeight, fovAngleY, aspectHByW, nearZ); - - virtualProjection *= stereoParameters->stereoSeparationFactor; // incorporate developer defined bias - - // - // By applying a translation, we are forcing our cameras to be parallel - // - - invertedAngle = atanf(virtualProjection / (2.0f * nearZ)); - - proj = XMMatrixPerspectiveFovLH(fovAngleY, aspectHByW, nearZ, farZ); - - if (channel == STEREO_CHANNEL::LEFT) - { - if (stereoMode > STEREO_MODE::NORMAL) - { - XMMATRIX rots, trans; - rots = XMMatrixRotationY(invertedAngle); - trans = XMMatrixTranslation(-virtualProjection, 0, 0); - patchedProjection = XMMatrixMultiply(XMMatrixMultiply(rots, trans), proj); - } - else - { - XMMATRIX trans; - trans = XMMatrixTranslation(-virtualProjection, 0, 0); - patchedProjection = XMMatrixMultiply(trans, proj); - } - } - else - { - if (stereoMode > STEREO_MODE::NORMAL) - { - XMMATRIX rots, trans; - rots = XMMatrixRotationY(-invertedAngle); - trans = XMMatrixTranslation(virtualProjection, 0, 0); - patchedProjection = XMMatrixMultiply(XMMatrixMultiply(rots, trans), proj); - } - else - { - XMMATRIX trans; - trans = XMMatrixTranslation(virtualProjection, 0, 0); - patchedProjection = XMMatrixMultiply(trans, proj); - } - } - - return patchedProjection; -} - diff --git a/DirectXSceneStore/GameContent/StereoProjection.h b/DirectXSceneStore/GameContent/StereoProjection.h deleted file mode 100644 index 62ce618..0000000 --- a/DirectXSceneStore/GameContent/StereoProjection.h +++ /dev/null @@ -1,45 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -typedef struct STEREO_PARAMETERS -{ - float viewerDistanceInches; - float displaySizeInches; - float pixelResolutionWidth; - float pixelResolutionHeight; - float stereoSeparationFactor; - float stereoExaggerationFactor; -} STEREO_PARAMETERS; - -// Enumeration for stereo channels (left and right). -typedef enum class STEREO_CHANNEL -{ - LEFT = 0, - RIGHT -} STEREO_CHANNEL; - -// Enumeration for stereo mode (normal or inverted). -typedef enum class STEREO_MODE -{ - NORMAL = 0, - INVERTED, -} STEREO_MODE; - -void StereoCreateDefaultParameters(_Out_ STEREO_PARAMETERS* pStereoParameters); - -DirectX::XMMATRIX MatrixStereoProjectionFovLH( - _In_opt_ const STEREO_PARAMETERS* stereoParameters, - STEREO_CHANNEL channel, - float fovAngleY, - float aspectHByW, - float nearZ, - float farZ, - STEREO_MODE stereoMode - ); - diff --git a/DirectXSceneStore/GameContent/TargetTexture.cpp b/DirectXSceneStore/GameContent/TargetTexture.cpp deleted file mode 100644 index 7d8aa57..0000000 --- a/DirectXSceneStore/GameContent/TargetTexture.cpp +++ /dev/null @@ -1,359 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "TargetTexture.h" -#include "Common\DirectXSample.h" - -using namespace Microsoft::WRL; -using namespace Windows::Graphics::Display; - -TargetTexture::TargetTexture( - _In_ ID3D11Device1* d3dDevice, - _In_ ID2D1Factory1* d2dFactory, - _In_ IDWriteFactory1* dwriteFactory, - _In_ ID2D1DeviceContext* d2dContext - ) -{ - m_d3dDevice = d3dDevice; - m_d2dFactory = d2dFactory; - m_dwriteFactory = dwriteFactory; - m_d2dContext = d2dContext; - - DX::ThrowIfFailed( - m_d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::Red, 1.f), - &m_redBrush - ) - ); - - DX::ThrowIfFailed( - m_d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::CornflowerBlue, 1.0f), - &m_blueBrush - ) - ); - - DX::ThrowIfFailed( - m_d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::Green, 1.f), - &m_greenBrush - ) - ); - - DX::ThrowIfFailed( - m_d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::White, 1.f), - &m_whiteBrush - ) - ); - - DX::ThrowIfFailed( - m_d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::Black, 1.f), - &m_blackBrush - ) - ); - - DX::ThrowIfFailed( - m_d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::Yellow, 1.f), - &m_yellowBrush - ) - ); - - DX::ThrowIfFailed( - m_d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::White, 0.0f), - &m_clearBrush - ) - ); - - DX::ThrowIfFailed( - m_d2dFactory->CreateEllipseGeometry( - D2D1::Ellipse( - D2D1::Point2F(256.0f, 256.0f), - 50.0f, - 50.0f - ), - &m_circleGeometry1) - ); - - DX::ThrowIfFailed( - m_d2dFactory->CreateEllipseGeometry( - D2D1::Ellipse( - D2D1::Point2F(256.0f, 256.0f), - 100.0f, - 100.0f - ), - &m_circleGeometry2) - ); - - DX::ThrowIfFailed( - m_d2dFactory->CreateEllipseGeometry( - D2D1::Ellipse( - D2D1::Point2F(256.0f, 256.0f), - 150.0f, - 150.0f - ), - &m_circleGeometry3) - ); - - DX::ThrowIfFailed( - m_d2dFactory->CreateEllipseGeometry( - D2D1::Ellipse( - D2D1::Point2F(256.0f, 256.0f), - 200.0f, - 200.0f - ), - &m_circleGeometry4) - ); - - DX::ThrowIfFailed( - m_d2dFactory->CreateEllipseGeometry( - D2D1::Ellipse( - D2D1::Point2F(256.0f, 256.0f), - 250.0f, - 250.0f - ), - &m_circleGeometry5) - ); - - DX::ThrowIfFailed( - m_dwriteFactory->CreateTextFormat( - L"Segoe UI", - nullptr, - DWRITE_FONT_WEIGHT_LIGHT, - DWRITE_FONT_STYLE_NORMAL, - DWRITE_FONT_STRETCH_NORMAL, - 425, // fontsize - L"en-US", // locale - &m_textFormat - ) - ); - - // Center the text horizontally. - DX::ThrowIfFailed( - m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER) - ); - - // Center the text vertically. - DX::ThrowIfFailed( - m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER) - ); -} -//---------------------------------------------------------------------- -void TargetTexture::CreateTextureResourceView( - _In_ Platform::String^ name, - _Out_ ID3D11ShaderResourceView** textureResourceView - ) -{ - // Allocate a offscreen D3D surface for D2D to render our 2D content into - D3D11_TEXTURE2D_DESC texDesc; - texDesc.ArraySize = 1; - texDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; - texDesc.CPUAccessFlags = 0; - texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; - texDesc.Height = 512; - texDesc.Width = 512; - texDesc.MipLevels = 1; - texDesc.MiscFlags = 0; - texDesc.SampleDesc.Count = 1; - texDesc.SampleDesc.Quality = 0; - texDesc.Usage = D3D11_USAGE_DEFAULT; - - ComPtr offscreenTexture; - DX::ThrowIfFailed( - m_d3dDevice->CreateTexture2D(&texDesc, nullptr, &offscreenTexture) - ); - - // Convert the Direct2D texture into a Shader Resource View - ComPtr texture; - DX::ThrowIfFailed( - m_d3dDevice->CreateShaderResourceView(offscreenTexture.Get(), nullptr, &texture) - ); -#if defined(_DEBUG) - { - char debugName[100]; - int l = sprintf_s(debugName, sizeof(debugName) / sizeof(debugName[0]), "Simple3DGame Target %ls", name->Data()); - DX::ThrowIfFailed( - texture->SetPrivateData(WKPDID_D3DDebugObjectName, l, debugName) - ); - } -#endif - - ComPtr dxgiSurface; - DX::ThrowIfFailed( - offscreenTexture.As(&dxgiSurface) - ); - - // Create a D2D render target which can draw into our offscreen D3D - // surface. Given that we use a constant size for the texture, we - // fix the DPI at 96. - - D2D1_BITMAP_PROPERTIES1 properties; - properties.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM; - properties.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED; - properties.dpiX = 96; - properties.dpiY = 96; - properties.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW; - properties.colorContext = nullptr; - - ComPtr renderTarget; - DX::ThrowIfFailed( - m_d2dContext->CreateBitmapFromDxgiSurface( - dxgiSurface.Get(), - &properties, - &renderTarget - ) - ); - - m_d2dContext->SetTarget(renderTarget.Get()); - float saveDpiX; - float saveDpiY; - - m_d2dContext->GetDpi(&saveDpiX, &saveDpiY); - m_d2dContext->SetDpi(96.0f, 96.0f); - - m_d2dContext->BeginDraw(); - m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity()); - - D2D1_SIZE_F renderTargetSize = renderTarget->GetSize(); - - m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::White)); - m_d2dContext->FillGeometry(m_circleGeometry5.Get(), m_redBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry4.Get(), m_blueBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry3.Get(), m_greenBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry2.Get(), m_yellowBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry1.Get(), m_blackBrush.Get()); - m_d2dContext->DrawText( - name->Data(), - name->Length(), - m_textFormat.Get(), - D2D1::RectF(0, 0, renderTargetSize.width, renderTargetSize.height), - m_whiteBrush.Get() - ); - - // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device - // is lost. It will be handled during the next call to Present. - HRESULT hr = m_d2dContext->EndDraw(); - if (hr != D2DERR_RECREATE_TARGET) - { - DX::ThrowIfFailed(hr); - } - - m_d2dContext->SetTarget(nullptr); - m_d2dContext->SetDpi(saveDpiX, saveDpiY); - - *textureResourceView = texture.Detach(); -} -//---------------------------------------------------------------------- -void TargetTexture::CreateHitTextureResourceView( - _In_ Platform::String^ name, - _Out_ ID3D11ShaderResourceView** textureResourceView - ) -{ - // Allocate a offscreen D3D surface for D2D to render our 2D content into - D3D11_TEXTURE2D_DESC texDesc; - texDesc.ArraySize = 1; - texDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; - texDesc.CPUAccessFlags = 0; - texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; - texDesc.Height = 512; - texDesc.Width = 512; - texDesc.MipLevels = 1; - texDesc.MiscFlags = 0; - texDesc.SampleDesc.Count = 1; - texDesc.SampleDesc.Quality = 0; - texDesc.Usage = D3D11_USAGE_DEFAULT; - - ComPtr offscreenTexture; - DX::ThrowIfFailed( - m_d3dDevice->CreateTexture2D(&texDesc, nullptr, &offscreenTexture) - ); - - // Convert the Direct2D texture into a Shader Resource View - ComPtr texture; - DX::ThrowIfFailed( - m_d3dDevice->CreateShaderResourceView(offscreenTexture.Get(), nullptr, &texture) - ); -#if defined(_DEBUG) - { - char debugName[100]; - int l = sprintf_s(debugName, sizeof(debugName) / sizeof(debugName[0]), "Simple3DGame HitTarget %ls", name->Data()); - DX::ThrowIfFailed( - texture->SetPrivateData(WKPDID_D3DDebugObjectName, l, debugName) - ); - } -#endif - - ComPtr dxgiSurface; - DX::ThrowIfFailed( - offscreenTexture.As(&dxgiSurface) - ); - - // Create a D2D render target which can draw into our offscreen D3D - // surface. Given that we use a constant size for the texture, we - // fix the DPI at 96. - - D2D1_BITMAP_PROPERTIES1 properties; - properties.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM; - properties.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED; - properties.dpiX = 96; - properties.dpiY = 96; - properties.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW; - properties.colorContext = nullptr; - - ComPtr renderTarget; - DX::ThrowIfFailed( - m_d2dContext->CreateBitmapFromDxgiSurface( - dxgiSurface.Get(), - &properties, - &renderTarget - ) - ); - - m_d2dContext->SetTarget(renderTarget.Get()); - float saveDpiX; - float saveDpiY; - - m_d2dContext->GetDpi(&saveDpiX, &saveDpiY); - m_d2dContext->SetDpi(96.0f, 96.0f); - - m_d2dContext->BeginDraw(); - m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity()); - - D2D1_SIZE_F renderTargetSize = renderTarget->GetSize(); - - m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::Black)); - m_d2dContext->FillGeometry(m_circleGeometry5.Get(), m_yellowBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry4.Get(), m_greenBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry3.Get(), m_blueBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry2.Get(), m_redBrush.Get()); - m_d2dContext->FillGeometry(m_circleGeometry1.Get(), m_whiteBrush.Get()); - m_d2dContext->DrawText( - name->Data(), - name->Length(), - m_textFormat.Get(), - D2D1::RectF(0, 0, renderTargetSize.width, renderTargetSize.height), - m_blackBrush.Get() - ); - - // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device - // is lost. It will be handled during the next call to Present. - HRESULT hr = m_d2dContext->EndDraw(); - if (hr != D2DERR_RECREATE_TARGET) - { - DX::ThrowIfFailed(hr); - } - - m_d2dContext->SetTarget(nullptr); - m_d2dContext->SetDpi(saveDpiX, saveDpiY); - - *textureResourceView = texture.Detach(); -} -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameContent/TargetTexture.h b/DirectXSceneStore/GameContent/TargetTexture.h deleted file mode 100644 index ddca429..0000000 --- a/DirectXSceneStore/GameContent/TargetTexture.h +++ /dev/null @@ -1,57 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// TargetTexture: -// This is a helper class to procedurally generate textures for game -// targets. There are two versions of the textures, one when it is -// hit and the other is when it is not. -// The class creates the necessary resources to draw the texture into -// an off screen resource at initialization time. - -ref class TargetTexture -{ -internal: - TargetTexture( - _In_ ID3D11Device1* d3dDevice, - _In_ ID2D1Factory1* d2dFactory, - _In_ IDWriteFactory1* dwriteFactory, - _In_ ID2D1DeviceContext* d2dContext - ); - - void CreateTextureResourceView( - _In_ Platform::String^ name, - _Out_ ID3D11ShaderResourceView** textureResourceView - ); - void CreateHitTextureResourceView( - _In_ Platform::String^ name, - _Out_ ID3D11ShaderResourceView** textureResourceView - ); - -protected private: - Microsoft::WRL::ComPtr m_d3dDevice; - Microsoft::WRL::ComPtr m_d2dFactory; - Microsoft::WRL::ComPtr m_d2dContext; - Microsoft::WRL::ComPtr m_dwriteFactory; - - Microsoft::WRL::ComPtr m_redBrush; - Microsoft::WRL::ComPtr m_blueBrush; - Microsoft::WRL::ComPtr m_greenBrush; - Microsoft::WRL::ComPtr m_whiteBrush; - Microsoft::WRL::ComPtr m_blackBrush; - Microsoft::WRL::ComPtr m_yellowBrush; - Microsoft::WRL::ComPtr m_clearBrush; - - Microsoft::WRL::ComPtr m_circleGeometry1; - Microsoft::WRL::ComPtr m_circleGeometry2; - Microsoft::WRL::ComPtr m_circleGeometry3; - Microsoft::WRL::ComPtr m_circleGeometry4; - Microsoft::WRL::ComPtr m_circleGeometry5; - - Microsoft::WRL::ComPtr m_textFormat; -}; \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/VertexShader.hlsl b/DirectXSceneStore/GameContent/VertexShader.hlsl deleted file mode 100644 index a2c782e..0000000 --- a/DirectXSceneStore/GameContent/VertexShader.hlsl +++ /dev/null @@ -1,30 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "ConstantBuffers.hlsli" - -PixelShaderInput main(VertextShaderInput input) -{ - PixelShaderInput output = (PixelShaderInput)0; - - output.position = mul(mul(mul(input.position, world), view), projection); - output.textureUV = input.textureUV; - - // compute view space normal - output.normal = normalize (mul(mul(input.normal.xyz, (float3x3)world), (float3x3)view)); - - // Vertex pos in view space (normalize in pixel shader) - output.vertexToEye = -mul(mul(input.position, world), view).xyz; - - // Compute view space vertex to light vectors (normalized) - output.vertexToLight0 = normalize(mul(lightPosition[0], view ).xyz + output.vertexToEye); - output.vertexToLight1 = normalize(mul(lightPosition[1], view ).xyz + output.vertexToEye); - output.vertexToLight2 = normalize(mul(lightPosition[2], view ).xyz + output.vertexToEye); - output.vertexToLight3 = normalize(mul(lightPosition[3], view ).xyz + output.vertexToEye); - - return output; -} \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/VertexShaderFlat.hlsl b/DirectXSceneStore/GameContent/VertexShaderFlat.hlsl deleted file mode 100644 index ceeb67f..0000000 --- a/DirectXSceneStore/GameContent/VertexShaderFlat.hlsl +++ /dev/null @@ -1,36 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "ConstantBuffers.hlsli" - -PixelShaderFlatInput main(VertextShaderInput input) -{ - PixelShaderFlatInput output = (PixelShaderFlatInput)0; - - output.position = mul(mul(mul(input.position, world), view), projection); - output.textureUV = input.textureUV; - - // compute view space normal - float3 normal = normalize (mul(mul(input.normal.xyz, (float3x3)world), (float3x3)view)); - - // Vertex pos in view space (normalize in pixel shader) - float3 vertexToEye = -mul(mul(input.position, world), view).xyz; - - // Compute view space vertex to light vectors (normalized) - float3 vertexToLight0 = normalize(mul(lightPosition[0], view ).xyz + vertexToEye); - float3 vertexToLight1 = normalize(mul(lightPosition[1], view ).xyz + vertexToEye); - float3 vertexToLight2 = normalize(mul(lightPosition[2], view ).xyz + vertexToEye); - float3 vertexToLight3 = normalize(mul(lightPosition[3], view ).xyz + vertexToEye); - - output.diffuseColor = diffuseColor * - (max(0.0f, dot(normal, vertexToLight0)) + - max(0.0f, dot(normal, vertexToLight1)) + - max(0.0f, dot(normal, vertexToLight2)) + - max(0.0f, dot(normal, vertexToLight3))) * 0.5f; - - return output; -} \ No newline at end of file diff --git a/DirectXSceneStore/GameContent/WorldMesh.cpp b/DirectXSceneStore/GameContent/WorldMesh.cpp deleted file mode 100644 index c369658..0000000 --- a/DirectXSceneStore/GameContent/WorldMesh.cpp +++ /dev/null @@ -1,159 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "WorldMesh.h" -#include "Common\DirectXSample.h" -#include "ConstantBuffers.h" - -using namespace Microsoft::WRL; -using namespace DirectX; - -WorldCeilingMesh::WorldCeilingMesh(_In_ ID3D11Device *device) -{ - PNTVertex cellVertices[] = - { - // CEILING - {XMFLOAT3(-4.0f, 3.0f, -6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2(-0.15f, 0.0f)}, - {XMFLOAT3( 4.0f, 3.0f, -6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2( 1.25f, 0.0f)}, - {XMFLOAT3(-4.0f, 3.0f, 6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2(-0.15f, 2.1f)}, - {XMFLOAT3( 4.0f, 3.0f, 6.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT2( 1.25f, 2.1f)}, - }; - - WORD cellIndices[] = { - 0, 1, 2, - 1, 3, 2, - }; - - m_vertexCount = 4; - m_indexCount = 6; - - D3D11_BUFFER_DESC bd = {0}; - D3D11_SUBRESOURCE_DATA initData = {0}; - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount; - bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = cellVertices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_vertexBuffer) - ); - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(WORD) * m_indexCount; - bd.BindFlags = D3D11_BIND_INDEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = cellIndices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_indexBuffer) - ); -} - -WorldFloorMesh::WorldFloorMesh(_In_ ID3D11Device *device) -{ - PNTVertex cellVertices[] = - { - // FLOOR - {XMFLOAT3(-4.0f, -3.0f, 6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)}, - {XMFLOAT3( 4.0f, -3.0f, 6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(1.0f, 0.0f)}, - {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)}, - {XMFLOAT3( 4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(1.0f, 1.5f)}, - }; - - WORD cellIndices[] = { - 0, 1, 2, - 1, 3, 2, - }; - - m_vertexCount = 4; - m_indexCount = 6; - - D3D11_BUFFER_DESC bd = {0}; - D3D11_SUBRESOURCE_DATA initData = {0}; - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount; - bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = cellVertices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_vertexBuffer) - ); - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(WORD) * m_indexCount; - bd.BindFlags = D3D11_BIND_INDEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = cellIndices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_indexBuffer) - ); -} - -WorldWallsMesh::WorldWallsMesh(_In_ ID3D11Device *device) -{ - PNTVertex cellVertices[] = - { - // WALL - {XMFLOAT3(-4.0f, 3.0f, 6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(0.0f, 0.0f)}, - {XMFLOAT3( 4.0f, 3.0f, 6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(2.0f, 0.0f)}, - {XMFLOAT3(-4.0f, -3.0f, 6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(0.0f, 1.5f)}, - {XMFLOAT3( 4.0f, -3.0f, 6.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), XMFLOAT2(2.0f, 1.5f)}, - // WALL - {XMFLOAT3(4.0f, 3.0f, 6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)}, - {XMFLOAT3(4.0f, 3.0f, -6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 0.0f)}, - {XMFLOAT3(4.0f, -3.0f, 6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)}, - {XMFLOAT3(4.0f, -3.0f, -6.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 1.5f)}, - // WALL - {XMFLOAT3( 4.0f, 3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f)}, - {XMFLOAT3(-4.0f, 3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(2.0f, 0.0f)}, - {XMFLOAT3( 4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.5f)}, - {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(2.0f, 1.5f)}, - // WALL - {XMFLOAT3(-4.0f, 3.0f, -6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 0.0f)}, - {XMFLOAT3(-4.0f, 3.0f, 6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 0.0f)}, - {XMFLOAT3(-4.0f, -3.0f, -6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(0.0f, 1.5f)}, - {XMFLOAT3(-4.0f, -3.0f, 6.0f), XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT2(3.0f, 1.5f)}, - }; - - WORD cellIndices[] = { - 0, 1, 2, - 1, 3, 2, - 4, 5, 6, - 5, 7, 6, - 8, 9, 10, - 9, 11, 10, - 12, 13, 14, - 13, 15, 14, - }; - - m_vertexCount = 16; - m_indexCount = 24; - - D3D11_BUFFER_DESC bd = {0}; - D3D11_SUBRESOURCE_DATA initData = {0}; - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount; - bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = cellVertices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_vertexBuffer) - ); - - bd.Usage = D3D11_USAGE_DEFAULT; - bd.ByteWidth = sizeof(WORD) * m_indexCount; - bd.BindFlags = D3D11_BIND_INDEX_BUFFER; - bd.CPUAccessFlags = 0; - initData.pSysMem = cellIndices; - DX::ThrowIfFailed( - device->CreateBuffer(&bd, &initData, &m_indexBuffer) - ); -} - diff --git a/DirectXSceneStore/GameContent/WorldMesh.h b/DirectXSceneStore/GameContent/WorldMesh.h deleted file mode 100644 index ae52051..0000000 --- a/DirectXSceneStore/GameContent/WorldMesh.h +++ /dev/null @@ -1,45 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -#include "MeshObject.h" - -// WorldCeilingMesh: -// This class derives from MeshObject and creates a ID3D11Buffer of -// vertices and indices to represent the ceiling of the bounding cube -// of the world. -// The vertices are defined by a position, a normal and a single -// 2D texture coordinate. - -ref class WorldCeilingMesh: public MeshObject -{ -internal: - WorldCeilingMesh(_In_ ID3D11Device *device); -}; - -// WorldFloorMesh: -// This class derives from MeshObject and creates a ID3D11Buffer of -// vertices and indices to represent the floor of the bounding cube -// of the world. - -ref class WorldFloorMesh: public MeshObject -{ -internal: - WorldFloorMesh(_In_ ID3D11Device *device); -}; - -// WorldWallsMesh: -// This class derives from MeshObject and creates a ID3D11Buffer of -// vertices and indices to represent the walls of the bounding cube -// of the world. - -ref class WorldWallsMesh: public MeshObject -{ -internal: - WorldWallsMesh(_In_ ID3D11Device *device); -}; diff --git a/DirectXSceneStore/GameContent/pch.cpp b/DirectXSceneStore/GameContent/pch.cpp deleted file mode 100644 index 73fdc21..0000000 --- a/DirectXSceneStore/GameContent/pch.cpp +++ /dev/null @@ -1,8 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" diff --git a/DirectXSceneStore/GameContent/pch.h b/DirectXSceneStore/GameContent/pch.h deleted file mode 100644 index d95e855..0000000 --- a/DirectXSceneStore/GameContent/pch.h +++ /dev/null @@ -1,34 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include - diff --git a/DirectXSceneStore/GameHud.cpp b/DirectXSceneStore/GameHud.cpp deleted file mode 100644 index f1f4b9d..0000000 --- a/DirectXSceneStore/GameHud.cpp +++ /dev/null @@ -1,482 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "GameHud.h" -#include "GameContent\GameConstants.h" -#include "GameUIConstants.h" - -using namespace Microsoft::WRL; -using namespace Windows::UI::Core; -using namespace Windows::ApplicationModel; -using namespace Windows::Foundation; -using namespace Windows::Storage; -using namespace Windows::UI::ViewManagement; -using namespace Windows::Graphics::Display; -using namespace D2D1; - -//---------------------------------------------------------------------- - -GameHud::GameHud( - _In_ const std::shared_ptr& deviceResources, - _In_ Platform::String^ titleHeader, - _In_ Platform::String^ titleBody, - _In_ Platform::String^ titleLicenseInfo - ) : - m_deviceResources(deviceResources), - m_titleHeader(titleHeader), - m_titleBody(titleBody), - m_titleLicenseInfo(titleLicenseInfo), - m_licenseInfoChanged(true) -{ - m_showTitle = true; - m_titleBodyVerticalOffset = GameConstants::Margin; - m_logoSize = D2D1::SizeF(0.0f, 0.0f); - - auto dwriteFactory = m_deviceResources->GetDWriteFactory(); - - DX::ThrowIfFailed( - dwriteFactory->CreateTextFormat( - L"Segoe UI", - nullptr, - DWRITE_FONT_WEIGHT_LIGHT, - DWRITE_FONT_STYLE_NORMAL, - DWRITE_FONT_STRETCH_NORMAL, - GameConstants::HudBodyPointSize, - L"en-us", - &m_textFormatBody - ) - ); - DX::ThrowIfFailed( - dwriteFactory->CreateTextFormat( - L"Segoe UI Symbol", - nullptr, - DWRITE_FONT_WEIGHT_LIGHT, - DWRITE_FONT_STYLE_NORMAL, - DWRITE_FONT_STRETCH_NORMAL, - GameConstants::HudBodyPointSize, - L"en-us", - &m_textFormatBodySymbol - ) - ); - DX::ThrowIfFailed( - dwriteFactory->CreateTextFormat( - L"Segoe UI Light", - nullptr, - DWRITE_FONT_WEIGHT_LIGHT, - DWRITE_FONT_STYLE_NORMAL, - DWRITE_FONT_STRETCH_NORMAL, - GameConstants::HudTitleHeaderPointSize, - L"en-us", - &m_textFormatTitleHeader - ) - ); - DX::ThrowIfFailed( - dwriteFactory->CreateTextFormat( - L"Segoe UI Light", - nullptr, - DWRITE_FONT_WEIGHT_LIGHT, - DWRITE_FONT_STYLE_NORMAL, - DWRITE_FONT_STRETCH_NORMAL, - GameConstants::HudTitleBodyPointSize, - L"en-us", - &m_textFormatTitleBody - ) - ); - DX::ThrowIfFailed( - dwriteFactory->CreateTextFormat( - L"Segoe UI Bold", - nullptr, - DWRITE_FONT_WEIGHT_BOLD, - DWRITE_FONT_STYLE_NORMAL, - DWRITE_FONT_STRETCH_NORMAL, - GameConstants::HudLicensePointSize, - L"en-us", - &m_textFormatTitleLicense - ) - ); - - DX::ThrowIfFailed(m_textFormatBody->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)); - DX::ThrowIfFailed(m_textFormatBody->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); - DX::ThrowIfFailed(m_textFormatBodySymbol->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)); - DX::ThrowIfFailed(m_textFormatBodySymbol->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); - DX::ThrowIfFailed(m_textFormatTitleHeader->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)); - DX::ThrowIfFailed(m_textFormatTitleHeader->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); - DX::ThrowIfFailed(m_textFormatTitleBody->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)); - DX::ThrowIfFailed(m_textFormatTitleBody->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); - DX::ThrowIfFailed(m_textFormatTitleLicense->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)); - DX::ThrowIfFailed(m_textFormatTitleLicense->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); -} - -//---------------------------------------------------------------------- - -void GameHud::CreateDeviceDependentResources() -{ - auto location = Package::Current->InstalledLocation; - Platform::String^ path = Platform::String::Concat(location->Path, "\\"); - path = Platform::String::Concat(path, "DirectXSceneStore\\Assets\\windows-sdk.png"); - - auto wicFactory = m_deviceResources->GetWicImagingFactory(); - - ComPtr wicBitmapDecoder; - DX::ThrowIfFailed( - wicFactory->CreateDecoderFromFilename( - path->Data(), - nullptr, - GENERIC_READ, - WICDecodeMetadataCacheOnDemand, - &wicBitmapDecoder - ) - ); - - ComPtr wicBitmapFrame; - DX::ThrowIfFailed( - wicBitmapDecoder->GetFrame(0, &wicBitmapFrame) - ); - - ComPtr wicFormatConverter; - DX::ThrowIfFailed( - wicFactory->CreateFormatConverter(&wicFormatConverter) - ); - - DX::ThrowIfFailed( - wicFormatConverter->Initialize( - wicBitmapFrame.Get(), - GUID_WICPixelFormat32bppPBGRA, - WICBitmapDitherTypeNone, - nullptr, - 0.0, - WICBitmapPaletteTypeCustom // The BGRA format has no palette so this value is ignored. - ) - ); - - double dpiX = 96.0f; - double dpiY = 96.0f; - DX::ThrowIfFailed( - wicFormatConverter->GetResolution(&dpiX, &dpiY) - ); - - auto d2dContext = m_deviceResources->GetD2DDeviceContext(); - - // Create D2D Resources - DX::ThrowIfFailed( - d2dContext->CreateBitmapFromWicBitmap( - wicFormatConverter.Get(), - BitmapProperties( - PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), - static_cast(dpiX), - static_cast(dpiY) - ), - &m_logoBitmap - ) - ); - - m_logoSize = m_logoBitmap->GetSize(); - - DX::ThrowIfFailed( - d2dContext->CreateSolidColorBrush( - D2D1::ColorF(D2D1::ColorF::White), - &m_textBrush - ) - ); - DX::ThrowIfFailed( - d2dContext->CreateSolidColorBrush( - D2D1::ColorF(0xaaaaaa, 1.0f), - &m_textBrushGrey - ) - ); -} - -//---------------------------------------------------------------------- - -void GameHud::CreateWindowSizeDependentResources() -{ - auto windowBounds = m_deviceResources->GetLogicalSize(); - - m_maxTitleSize.width = windowBounds.Width - GameConstants::HudSafeWidth; - m_maxTitleSize.height = windowBounds.Height; - - float headerWidth = m_maxTitleSize.width - (m_logoSize.width + 2 * GameConstants::Margin); - - if (headerWidth > 0) - { - auto dwriteFactory = m_deviceResources->GetDWriteFactory(); - - // Only resize the text layout for the Title area when there is enough space. - m_showTitle = true; - - DX::ThrowIfFailed( - dwriteFactory->CreateTextLayout( - m_titleHeader->Data(), - m_titleHeader->Length(), - m_textFormatTitleHeader.Get(), - headerWidth, - m_maxTitleSize.height, - &m_titleHeaderLayout - ) - ); - - DWRITE_TEXT_METRICS metrics = {0}; - DX::ThrowIfFailed( - m_titleHeaderLayout->GetMetrics(&metrics) - ); - - // Compute the vertical size of the laid out Header and logo. This could change - // based on the window size and the layout of the text. In some cases the text - // may wrap. - m_titleBodyVerticalOffset = max(m_logoSize.height + GameConstants::Margin * 2, metrics.height + 2 * GameConstants::Margin); - - DX::ThrowIfFailed( - dwriteFactory->CreateTextLayout( - m_titleBody->Data(), - m_titleBody->Length(), - m_textFormatTitleBody.Get(), - m_maxTitleSize.width, - m_maxTitleSize.height - m_titleBodyVerticalOffset, - &m_titleBodyLayout - ) - ); - - DX::ThrowIfFailed( - m_titleBodyLayout->GetMetrics(&metrics) - ); - - m_titleLicenseVerticalOffset = m_titleBodyVerticalOffset + metrics.height + GameConstants::Margin; - - m_licenseInfoChanged = false; - DX::ThrowIfFailed( - dwriteFactory->CreateTextLayout( - m_titleLicenseInfo->Data(), - m_titleLicenseInfo->Length(), - m_textFormatTitleLicense.Get(), - m_maxTitleSize.width, - m_maxTitleSize.height - m_titleLicenseVerticalOffset, - &m_titleLicenseInfoLayout - ) - ); - } - else - { - // Not enough horizontal space for the titles so just turn it off. - m_showTitle = false; - } -} - -//---------------------------------------------------------------------- - -void GameHud::SetLicenseInfo(_In_ Platform::String^ licenseInfo) -{ - m_titleLicenseInfo = licenseInfo; - m_licenseInfoChanged = true; -} - -//---------------------------------------------------------------------- - -void GameHud::Render(_In_ Simple3DGame^ game) -{ - auto d2dContext = m_deviceResources->GetD2DDeviceContext(); - auto windowBounds = m_deviceResources->GetLogicalSize(); - - if (m_showTitle) - { - if (m_licenseInfoChanged) - { - DX::ThrowIfFailed( - m_deviceResources->GetDWriteFactory()->CreateTextLayout( - m_titleLicenseInfo->Data(), - m_titleLicenseInfo->Length(), - m_textFormatTitleLicense.Get(), - m_maxTitleSize.width, - m_maxTitleSize.height - m_titleLicenseVerticalOffset, - &m_titleLicenseInfoLayout - ) - ); - m_licenseInfoChanged = false; - } - - d2dContext->DrawBitmap( - m_logoBitmap.Get(), - D2D1::RectF( - GameConstants::Margin, - GameConstants::Margin, - m_logoSize.width + GameConstants::Margin, - m_logoSize.height + GameConstants::Margin - ) - ); - d2dContext->DrawTextLayout( - Point2F(m_logoSize.width + 2.0f * GameConstants::Margin, GameConstants::Margin), - m_titleHeaderLayout.Get(), - m_textBrush.Get() - ); - d2dContext->DrawTextLayout( - Point2F(GameConstants::Margin, m_titleBodyVerticalOffset), - m_titleBodyLayout.Get(), - m_textBrush.Get() - ); - d2dContext->DrawTextLayout( - Point2F(GameConstants::Margin, m_titleLicenseVerticalOffset), - m_titleLicenseInfoLayout.Get(), - m_textBrush.Get() - ); - } - - if (game != nullptr) - { - // This section is only used after the game state has been initialized. - static const int bufferLength = 256; - static char16 wsbuffer[bufferLength]; - int length = swprintf_s( - wsbuffer, - bufferLength, - L"Hits:\t%10d\nShots:\t%10d\nTime:\t%8.1f", - game->TotalHits(), - game->TotalShots(), - game->TimeRemaining() - ); - - d2dContext->DrawText( - wsbuffer, - length, - m_textFormatBody.Get(), - D2D1::RectF( - windowBounds.Width - GameConstants::HudRightOffset, - GameConstants::HudTopOffset, - windowBounds.Width, - GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3 - ), - m_textBrush.Get() - ); - - //// Using the unicode characters starting at 0x2780 ( ➀ ) for the consecutive levels of the game. - //// For completed levels start with 0x278A ( ➊ ) (This is 0x2780 + 10). - //uint32 levelCharacter[6]; - //for (uint32 i = 0; i < 6; i++) - //{ - // levelCharacter[i] = 0x2780 + i + ((static_cast(game->LevelCompleted()) == i) ? 10 : 0); - //} - - //if (game->IsTrial()) - //{ - // length = swprintf_s( - // wsbuffer, - // bufferLength, - // L"%lc %lc", - // levelCharacter[0], - // levelCharacter[1] - // ); - // d2dContext->DrawText( - // wsbuffer, - // length, - // m_textFormatBodySymbol.Get(), - // D2D1::RectF( - // windowBounds.Width - GameConstants::HudRightOffset, - // GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3 + GameConstants::Margin, - // windowBounds.Width, - // GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 4 - // ), - // m_textBrush.Get() - // ); - - // length = swprintf_s( - // wsbuffer, - // bufferLength, - // L"%lc %lc %lc %lc", - // levelCharacter[2], - // levelCharacter[3], - // levelCharacter[4], - // levelCharacter[5] - // ); - - // d2dContext->DrawText( - // wsbuffer, - // length, - // m_textFormatBodySymbol.Get(), - // D2D1::RectF( - // windowBounds.Width - GameConstants::HudRightOffset + 52.0f, - // GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3 + GameConstants::Margin, - // windowBounds.Width, - // GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize+ GameConstants::Margin) * 4 - // ), - // m_textBrushGrey.Get() - // ); - //} - //else - //{ - // length = swprintf_s( - // wsbuffer, - // bufferLength, - // L"%lc %lc %lc %lc %lc %lc", - // levelCharacter[0], - // levelCharacter[1], - // levelCharacter[2], - // levelCharacter[3], - // levelCharacter[4], - // levelCharacter[5] - // ); - // d2dContext->DrawText( - // wsbuffer, - // length, - // m_textFormatBodySymbol.Get(), - // D2D1::RectF( - // windowBounds.Width - GameConstants::HudRightOffset, - // GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 3 + GameConstants::Margin, - // windowBounds.Width, - // GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize+ GameConstants::Margin) * 4 - // ), - // m_textBrush.Get() - // ); - //} - - if (game->IsActivePlay()) - { - // Draw a rectangle for the touch input for the move control. - //d2dContext->DrawRectangle( - // D2D1::RectF( - // 0.0f, - // windowBounds.Height - GameConstants::TouchRectangleSize, - // GameConstants::TouchRectangleSize, - // windowBounds.Height - // ), - // m_textBrush.Get() - // ); - // Draw a rectangle for the touch input for the fire control. - //d2dContext->DrawRectangle( - // D2D1::RectF( - // windowBounds.Width - GameConstants::TouchRectangleSize, - // windowBounds.Height - GameConstants::TouchRectangleSize, - // windowBounds.Width, - // windowBounds.Height - // ), - // m_textBrush.Get() - // ); - - // Draw the cross hairs - d2dContext->DrawLine( - D2D1::Point2F(windowBounds.Width / 2.0f - GameConstants::CrossHairHalfSize, windowBounds.Height / 2.0f), - D2D1::Point2F(windowBounds.Width / 2.0f + GameConstants::CrossHairHalfSize, windowBounds.Height / 2.0f), - m_textBrush.Get(), - 3.0f - ); - d2dContext->DrawLine( - D2D1::Point2F(windowBounds.Width / 2.0f, windowBounds.Height / 2.0f - GameConstants::CrossHairHalfSize), - D2D1::Point2F(windowBounds.Width / 2.0f, windowBounds.Height / 2.0f + GameConstants::CrossHairHalfSize), - m_textBrush.Get(), - 3.0f - ); - } - } -} - -//---------------------------------------------------------------------- - -void GameHud::ReleaseDeviceDependentResources() -{ - m_textBrush.Reset(); - m_textBrushGrey.Reset(); - m_logoBitmap.Reset(); -} -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/GameHud.h b/DirectXSceneStore/GameHud.h deleted file mode 100644 index c767980..0000000 --- a/DirectXSceneStore/GameHud.h +++ /dev/null @@ -1,65 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// GameHud: -// This class maintains the resources necessary to draw the Heads Up Display, which is a -// 2D overlay on top of the main 3D graphics generated for the game. -// The GameHud Render method expects to be called within the context of a D2D BeginDraw -// and makes D2D drawing calls to draw the text elements on the window. - -#include "Simple3DGame.h" -#include "Common\DirectXSample.h" - -ref class Simple3DGame; - -ref class GameHud -{ -internal: - GameHud( - _In_ const std::shared_ptr& deviceResources, - _In_ Platform::String^ titleHeader, - _In_ Platform::String^ titleBody, - _In_ Platform::String^ titleLicenseInfo - ); - - void CreateDeviceDependentResources(); - void CreateWindowSizeDependentResources(); - void ReleaseDeviceDependentResources(); - void Render(_In_ Simple3DGame^ game); - - void SetLicenseInfo(_In_ Platform::String^ licenseInfo); - -private: - // Cached pointer to device resources. - std::shared_ptr m_deviceResources; - - Microsoft::WRL::ComPtr m_textBrush; - Microsoft::WRL::ComPtr m_textBrushGrey; - Microsoft::WRL::ComPtr m_textFormatBody; - Microsoft::WRL::ComPtr m_textFormatBodySymbol; - - Microsoft::WRL::ComPtr m_textFormatTitleHeader; - Microsoft::WRL::ComPtr m_textFormatTitleBody; - Microsoft::WRL::ComPtr m_textFormatTitleLicense; - Microsoft::WRL::ComPtr m_logoBitmap; - Microsoft::WRL::ComPtr m_titleHeaderLayout; - Microsoft::WRL::ComPtr m_titleBodyLayout; - Microsoft::WRL::ComPtr m_titleLicenseInfoLayout; - - bool m_showTitle; - Platform::String^ m_titleHeader; - Platform::String^ m_titleBody; - Platform::String^ m_titleLicenseInfo; - bool m_licenseInfoChanged; - - float m_titleBodyVerticalOffset; - float m_titleLicenseVerticalOffset; - D2D1_SIZE_F m_logoSize; - D2D1_SIZE_F m_maxTitleSize; -}; diff --git a/DirectXSceneStore/GameMain.cpp b/DirectXSceneStore/GameMain.cpp deleted file mode 100644 index b57fda5..0000000 --- a/DirectXSceneStore/GameMain.cpp +++ /dev/null @@ -1,817 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "MoveLookControllerXaml.h" -#include "MoveLookControllerKinect.h" -#include "GameMain.h" - -using namespace DirectXSceneStore; -using namespace GameControl; -using namespace concurrency; -using namespace DirectX; -using namespace Windows::ApplicationModel; -using namespace Windows::ApplicationModel::Activation; -using namespace Windows::ApplicationModel::Core; -using namespace Windows::ApplicationModel::Store; -using namespace Windows::Foundation; -using namespace Windows::Graphics::Display; -using namespace Windows::Storage; -using namespace Windows::UI::Core; -using namespace Windows::UI::Input; -using namespace Windows::UI::ViewManagement; -using namespace Windows::UI::Xaml; -using namespace Windows::UI::Xaml::Media; -using namespace Windows::System::Threading; -using namespace Concurrency; - - -GameMain::GameMain(const std::shared_ptr& deviceResources, IGameUIControl^ UIControl) : -m_deviceResources(deviceResources), -m_uiControl(UIControl) -{ - m_deviceResources->RegisterDeviceNotify(this); - - m_renderer = ref new GameRenderer(m_deviceResources); - m_game = ref new Simple3DGame(); - - // Can't really do this because the MoveLookController is what is updated from here, not the Kinect specific one. - //m_controller = MoveLookControllerKinect::Create(); - - m_controller = MoveLookControllerXaml::Create(Window::Current->CoreWindow, m_deviceResources->GetSwapChainPanel()->Dispatcher); - m_controller->AutoFire(false); - - auto bounds = m_deviceResources->GetLogicalSize(); - - //m_controller->SetMoveRect( - // XMFLOAT2(0.0f, bounds.Height - GameConstants::TouchRectangleSize), - // XMFLOAT2(GameConstants::TouchRectangleSize, bounds.Height) - // ); - //m_controller->SetFireRect( - // XMFLOAT2(bounds.Width - GameConstants::TouchRectangleSize, bounds.Height - GameConstants::TouchRectangleSize), - // XMFLOAT2(bounds.Width, bounds.Height) - // ); - - SetGameInfoOverlay(GameInfoOverlayState::Loading); - m_uiControl->SetAction(GameInfoOverlayCommand::None); - m_uiControl->ShowGameInfoOverlay(); - - create_task([this]() - { - // Asynchronously initialize the game class and load the renderer device resources. - // By doing all this asynchronously, the game gets to its main loop more quickly - // and in parallel all the necessary resources are loaded on other threads. - m_game->Initialize(m_controller, m_renderer); - - return m_renderer->CreateGameDeviceResourcesAsync(m_game); - - }).then([this]() - { - // The finalize code needs to run in the same thread context - // as the m_renderer object was created because the D3D device context - // can ONLY be accessed on a single thread. - { - critical_section::scoped_lock lock(m_criticalSection); - m_renderer->FinalizeCreateGameDeviceResources(); - } - - InitializeGameState(); - - if (m_updateState == UpdateEngineState::WaitingForResources) - { - return m_game->LoadLevelAsync().then([this]() - { - // The m_game object may need to deal with D3D device context work so - // again the finalize code needs to run in the same thread - // context as the m_renderer object was created because the D3D - // device context can ONLY be accessed on a single thread. - critical_section::scoped_lock lock(m_criticalSection); - m_game->FinalizeLoadLevel(); - m_game->SetCurrentLevelToSavedState(); - m_updateState = UpdateEngineState::ResourcesLoaded; - - }, task_continuation_context::use_current()); - } - else - { - // The game is not in the middle of a level so there aren't any level - // resources to load. Creating a no-op task so that in both cases - // the same continuation logic is used. - return create_task([]() - { - }); - } - }, task_continuation_context::use_current()).then([this]() - { - // Since Game loading is an async task, the app visual state - // may be too small or not have focus. Put the state machine - // into the correct state to reflect these cases. - m_haveFocus = true; - if (m_deviceResources->GetLogicalSize().Width < GameConstants::MinPlayableWidth) - { - m_updateStateNext = m_updateState; - m_updateState = UpdateEngineState::TooSmall; - m_controller->Active(false); - m_uiControl->HideGameInfoOverlay(); - m_uiControl->ShowTooSmall(); - } - else if (!m_haveFocus) - { - m_updateStateNext = m_updateState; - m_updateState = UpdateEngineState::Deactivated; - m_controller->Active(false); - m_uiControl->SetAction(GameInfoOverlayCommand::None); - } - - if (m_renderLoopWorker == nullptr || m_renderLoopWorker->Status != AsyncStatus::Started) - { - StartRenderLoop(); - } - }, task_continuation_context::use_current()); -} - -//-------------------------------------------------------------------------------------- - -GameMain::~GameMain() -{ - // Deregister device notification - m_deviceResources->RegisterDeviceNotify(nullptr); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::StartRenderLoop() -{ - // If the animation render loop is already running then do not start another thread. - if (m_renderLoopWorker != nullptr && m_renderLoopWorker->Status == AsyncStatus::Started) - { - return; - } - - // Create a task that will be run on a background thread. - auto workItemHandler = ref new WorkItemHandler([this](IAsyncAction ^ action) - { - // Calculate the updated frame and render once per vertical blanking interval. - while (action->Status == AsyncStatus::Started) - { - critical_section::scoped_lock lock(m_criticalSection); - Update(); - m_renderer->Render(); - m_deviceResources->Present(); - - if (!m_haveFocus || (m_updateState == UpdateEngineState::TooSmall)) - { - // The app is in an inactive state so stop rendering - // This optimizes for power and allows the framework to become more queiecent - break; - } - } - }); - - // Run task on a dedicated high priority background thread. - m_renderLoopWorker = ThreadPool::RunAsync(workItemHandler, WorkItemPriority::High, WorkItemOptions::TimeSliced); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::StopRenderLoop() -{ - m_renderLoopWorker->Cancel(); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::InitializeGameState() -{ - // Set up the initial state machine for handling Game playing state. - if (m_game->GameActive() && m_game->LevelActive()) - { - // The last time the game terminated it was in the middle - // of a level. - // We are waiting for the user to continue the game. - m_updateState = UpdateEngineState::WaitingForResources; - m_pressResult = PressResultState::ContinueLevel; - SetGameInfoOverlay(GameInfoOverlayState::Pause); - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - } - else - { - // This is either the first time the game has run or - // the last time the game terminated the level was completed. - // We are waiting for the user to begin the next level. - m_updateState = UpdateEngineState::WaitingForResources; - m_pressResult = PressResultState::PlayLevel; - SetGameInfoOverlay(GameInfoOverlayState::LevelStart); - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - } - m_uiControl->ShowGameInfoOverlay(); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::Update() -{ - m_controller->Update(); - - switch (m_updateState) - { - case UpdateEngineState::ResourcesLoaded: - switch (m_pressResult) - { - case PressResultState::LoadGame: - SetGameInfoOverlay(GameInfoOverlayState::GameStats); - break; - - case PressResultState::PlayLevel: - SetGameInfoOverlay(GameInfoOverlayState::LevelStart); - break; - - case PressResultState::ContinueLevel: - SetGameInfoOverlay(GameInfoOverlayState::Pause); - break; - } - m_updateState = UpdateEngineState::WaitingForPress; - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - m_controller->WaitForPress(); - m_uiControl->ShowGameInfoOverlay(); - break; - - case UpdateEngineState::WaitingForPress: - if (m_controller->IsPressComplete() || m_pressComplete) - { - m_pressComplete = false; - - switch (m_pressResult) - { - case PressResultState::LoadGame: - m_updateState = UpdateEngineState::WaitingForResources; - m_pressResult = PressResultState::PlayLevel; - m_controller->Active(false); - m_game->LoadGame(); - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - SetGameInfoOverlay(GameInfoOverlayState::LevelStart); - m_uiControl->ShowGameInfoOverlay(); - - m_game->LoadLevelAsync().then([this]() - { - critical_section::scoped_lock lock(m_criticalSection); - m_game->FinalizeLoadLevel(); - m_updateState = UpdateEngineState::ResourcesLoaded; - }, task_continuation_context::use_current()); - break; - - case PressResultState::PlayLevel: - m_updateState = UpdateEngineState::Dynamics; - m_uiControl->HideGameInfoOverlay(); - m_controller->Active(true); - m_game->StartLevel(); - break; - - case PressResultState::ContinueLevel: - m_updateState = UpdateEngineState::Dynamics; - m_uiControl->HideGameInfoOverlay(); - m_controller->Active(true); - m_game->ContinueGame(); - break; - } - } - break; - - case UpdateEngineState::Dynamics: - if (m_controller->IsPauseRequested() || m_pauseRequested) - { - m_pauseRequested = false; - - m_game->PauseGame(); - SetGameInfoOverlay(GameInfoOverlayState::Pause); - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - m_updateState = UpdateEngineState::WaitingForPress; - m_pressResult = PressResultState::ContinueLevel; - m_uiControl->ShowGameInfoOverlay(); - } - else - { - GameState runState = m_game->RunGame(); - switch (runState) - { - case GameState::TimeExpired: - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - SetGameInfoOverlay(GameInfoOverlayState::GameOverExpired); - m_uiControl->ShowGameInfoOverlay(); - m_updateState = UpdateEngineState::WaitingForPress; - m_pressResult = PressResultState::LoadGame; - break; - - case GameState::LevelComplete: - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - SetGameInfoOverlay(GameInfoOverlayState::LevelStart); - m_uiControl->ShowGameInfoOverlay(); - m_updateState = UpdateEngineState::WaitingForResources; - m_pressResult = PressResultState::PlayLevel; - - m_game->LoadLevelAsync().then([this]() - { - critical_section::scoped_lock lock(m_criticalSection); - m_game->FinalizeLoadLevel(); - m_updateState = UpdateEngineState::ResourcesLoaded; - - }, task_continuation_context::use_current()); - break; - - case GameState::GameComplete: - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - SetGameInfoOverlay(GameInfoOverlayState::GameOverCompleted); - m_uiControl->ShowGameInfoOverlay(); - m_updateState = UpdateEngineState::WaitingForPress; - m_pressResult = PressResultState::LoadGame; - break; - } - } - - if (m_updateState == UpdateEngineState::WaitingForPress) - { - // Transitioning state, so enable waiting for the press event - m_controller->WaitForPress(); - } - if (m_updateState == UpdateEngineState::WaitingForResources) - { - // Transitioning state, so shut down the input controller until resources are loaded - m_controller->Active(false); - } - break; - } -} - -//-------------------------------------------------------------------------------------- - -void GameMain::CreateWindowSizeDependentResources() -{ - UpdateLayoutState(); - m_renderer->CreateWindowSizeDependentResources(); - - // The location of the Control regions may have changed with the size change so update the controller. - auto bounds = m_deviceResources->GetLogicalSize(); - - m_controller->SetMoveRect( - XMFLOAT2(0.0f, bounds.Height - GameConstants::TouchRectangleSize), - XMFLOAT2(GameConstants::TouchRectangleSize, bounds.Height) - ); - m_controller->SetFireRect( - XMFLOAT2(bounds.Width - GameConstants::TouchRectangleSize, bounds.Height - GameConstants::TouchRectangleSize), - XMFLOAT2(bounds.Width, bounds.Height) - ); - - if (m_renderLoopWorker == nullptr || m_renderLoopWorker->Status != AsyncStatus::Started) - { - StartRenderLoop(); - } -} - -//-------------------------------------------------------------------------------------- - -void GameMain::OnDeviceLost() -{ - if (m_updateState == UpdateEngineState::Dynamics) - { - // Game is in the active game play state, Stop Game Timer and Pause play and save state - m_game->PauseGame(); - } - StopRenderLoop(); - m_renderer->ReleaseDeviceDependentResources(); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::OnDeviceRestored() -{ - m_renderer->CreateDeviceDependentResources(); - m_renderer->CreateWindowSizeDependentResources(); - - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - SetGameInfoOverlay(GameInfoOverlayState::Loading); - m_updateState = UpdateEngineState::WaitingForResources; - - if (m_renderLoopWorker == nullptr || m_renderLoopWorker->Status != AsyncStatus::Started) - { - StartRenderLoop(); - } - - create_task([this]() - { - return m_renderer->CreateGameDeviceResourcesAsync(m_game); - - }).then([this]() - { - // The finalize code needs to run in the same thread context - // as the m_renderer object was created because the D3D device context - // can ONLY be accessed on a single thread. - { - critical_section::scoped_lock lock(m_criticalSection); - m_renderer->FinalizeCreateGameDeviceResources(); - } - - // Reset the main state machine based on the current game state now - // that the device resources have been restored. - InitializeGameState(); - - if (m_updateState == UpdateEngineState::WaitingForResources) - { - // In the middle of a game so spin up the async task to load the level. - return m_game->LoadLevelAsync().then([this]() - { - // The m_game object may need to deal with D3D device context work so - // again the finalize code needs to run in the same thread - // context as the m_renderer object was created because the D3D - // device context can ONLY be accessed on a single thread. - critical_section::scoped_lock lock(m_criticalSection); - m_game->FinalizeLoadLevel(); - m_game->SetCurrentLevelToSavedState(); - m_updateState = UpdateEngineState::ResourcesLoaded; - - }, task_continuation_context::use_current()); - } - else - { - // The game is not in the middle of a level so there aren't any level - // resources to load. Creating a no-op task so that in both cases - // the same continuation logic is used. - return create_task([]() - { - }); - } - - }, task_continuation_context::use_current()).then([this]() - { - // Since Device lost is an unexpected event, the app visual state - // may be TooSmall or not have focus. Put the state machine - // into the correct state to reflect these cases. - auto bounds = m_deviceResources->GetLogicalSize(); - if (bounds.Width < GameConstants::MinPlayableWidth) - { - m_updateStateNext = m_updateState; - m_updateState = UpdateEngineState::TooSmall; - m_controller->Active(false); - m_uiControl->HideGameInfoOverlay(); - m_uiControl->ShowTooSmall(); - } - else if (!m_haveFocus) - { - m_updateStateNext = m_updateState; - m_updateState = UpdateEngineState::Deactivated; - m_controller->Active(false); - m_uiControl->SetAction(GameInfoOverlayCommand::None); - } - - if (m_renderLoopWorker == nullptr || m_renderLoopWorker->Status != AsyncStatus::Started) - { - StartRenderLoop(); - } - }, task_continuation_context::use_current()); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::UpdateLayoutState() -{ - if (m_deviceResources->GetLogicalSize().Width < GameConstants::MinPlayableWidth) - { - switch (m_updateState) - { - case UpdateEngineState::Dynamics: - // From Dynamic mode, when coming out of TooSmall layout rather than going directly back into game play - // go to the paused state waiting for user input to continue - m_updateStateNext = UpdateEngineState::WaitingForPress; - m_pressResult = PressResultState::ContinueLevel; - SetGameInfoOverlay(GameInfoOverlayState::Pause); - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - m_game->PauseGame(); - break; - - case UpdateEngineState::WaitingForResources: - // There is outstanding async loading in progress. This state change will be picked up after the - // async task is completed. - return; - - case UpdateEngineState::WaitingForPress: - // Avoid corrupting the m_updateStateNext on a transition from TooSmall -> TooSmall. - // Otherwise just cache the current state and return to it when leaving TooSmall layout - - m_updateStateNext = m_updateState; - break; - - default: - break; - } - - m_updateState = UpdateEngineState::TooSmall; - m_controller->Active(false); - m_uiControl->HideGameInfoOverlay(); - m_uiControl->ShowTooSmall(); - } - else - { - if (m_updateState == UpdateEngineState::TooSmall) - { - m_uiControl->HideTooSmall(); - m_uiControl->ShowGameInfoOverlay(); - - if (m_haveFocus) - { - if (m_updateStateNext == UpdateEngineState::WaitingForPress) - { - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - m_controller->WaitForPress(); - } - else if (m_updateStateNext == UpdateEngineState::WaitingForResources) - { - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - } - - m_updateState = m_updateStateNext; - } - else - { - m_updateState = UpdateEngineState::Deactivated; - m_uiControl->SetAction(GameInfoOverlayCommand::None); - } - } - else if (m_updateState == UpdateEngineState::Dynamics) - { - // In Dynamic mode, when a resize event happens, go to the paused state waiting for user input to continue. - m_pressResult = PressResultState::ContinueLevel; - SetGameInfoOverlay(GameInfoOverlayState::Pause); - m_game->PauseGame(); - if (m_haveFocus) - { - m_updateState = UpdateEngineState::WaitingForPress; - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - m_controller->WaitForPress(); - } - else - { - m_updateState = UpdateEngineState::Deactivated; - m_uiControl->SetAction(GameInfoOverlayCommand::None); - } - m_uiControl->ShowGameInfoOverlay(); - } - - if (m_renderLoopWorker == nullptr || m_renderLoopWorker->Status != AsyncStatus::Started) - { - StartRenderLoop(); - } - } -} - -//-------------------------------------------------------------------------------------- - -void GameMain::ResetGame() -{ - m_updateState = UpdateEngineState::WaitingForResources; - m_pressResult = PressResultState::PlayLevel; - m_controller->Active(false); - m_game->LoadGame(); - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - SetGameInfoOverlay(GameInfoOverlayState::LevelStart); - m_uiControl->ShowGameInfoOverlay(); - - m_game->LoadLevelAsync().then([this]() - { - critical_section::scoped_lock lock(m_criticalSection); - m_game->FinalizeLoadLevel(); - m_updateState = UpdateEngineState::ResourcesLoaded; - - }, task_continuation_context::use_current()); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::SetGameInfoOverlay(GameInfoOverlayState state) -{ - m_gameInfoOverlayState = state; - switch (state) - { - case GameInfoOverlayState::Loading: - m_uiControl->SetGameLoading(); - break; - - case GameInfoOverlayState::GameStats: - m_uiControl->SetGameStats( - m_game->HighScore().levelCompleted + 1, - m_game->HighScore().totalHits, - m_game->HighScore().totalShots - ); - break; - - case GameInfoOverlayState::LevelStart: - m_uiControl->SetLevelStart( - m_game->LevelCompleted() + 1, - m_game->CurrentLevel()->Objective(), - m_game->CurrentLevel()->TimeLimit(), - m_game->BonusTime() - ); - break; - - case GameInfoOverlayState::GameOverCompleted: - m_uiControl->SetGameOver( - true, - m_game->LevelCompleted() + 1, - m_game->TotalHits(), - m_game->TotalShots(), - m_game->HighScore().totalHits - ); - break; - - case GameInfoOverlayState::GameOverExpired: - m_uiControl->SetGameOver( - false, - m_game->LevelCompleted(), - m_game->TotalHits(), - m_game->TotalShots(), - m_game->HighScore().totalHits - ); - break; - - case GameInfoOverlayState::Pause: - m_uiControl->SetPause( - m_game->LevelCompleted() + 1, - m_game->TotalHits(), - m_game->TotalShots(), - m_game->TimeRemaining() - ); - break; - } -} - -//-------------------------------------------------------------------------------------- - -void GameMain::WindowActivationChanged(CoreWindowActivationState activationState) -{ - if (activationState == CoreWindowActivationState::Deactivated) - { - m_haveFocus = false; - - switch (m_updateState) - { - case UpdateEngineState::Dynamics: - // From Dynamic mode, when coming out of Deactivated rather than going directly back into game play - // go to the paused state waiting for user input to continue - m_updateStateNext = UpdateEngineState::WaitingForPress; - m_pressResult = PressResultState::ContinueLevel; - SetGameInfoOverlay(GameInfoOverlayState::Pause); - m_uiControl->ShowGameInfoOverlay(); - m_game->PauseGame(); - m_updateState = UpdateEngineState::Deactivated; - m_uiControl->SetAction(GameInfoOverlayCommand::None); - break; - - case UpdateEngineState::WaitingForResources: - case UpdateEngineState::WaitingForPress: - m_updateStateNext = m_updateState; - m_updateState = UpdateEngineState::Deactivated; - m_uiControl->SetAction(GameInfoOverlayCommand::None); - m_uiControl->ShowGameInfoOverlay(); - break; - } - // Don't have focus so shutdown input processing - m_controller->Active(false); - } - else if (activationState == CoreWindowActivationState::CodeActivated - || activationState == CoreWindowActivationState::PointerActivated) - { - m_haveFocus = true; - - if (m_updateState == UpdateEngineState::Deactivated) - { - m_updateState = m_updateStateNext; - - if (m_updateState == UpdateEngineState::WaitingForPress) - { - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - m_controller->WaitForPress(); - } - else if (m_updateStateNext == UpdateEngineState::WaitingForResources) - { - m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait); - } - - if (m_renderLoopWorker == nullptr || m_renderLoopWorker->Status != AsyncStatus::Started) - { - StartRenderLoop(); - } - } - } -} - -//-------------------------------------------------------------------------------------- - -void GameMain::Suspend() -{ - // Save application state. - switch (m_updateState) - { - case UpdateEngineState::Dynamics: - // Game is in the active game play state, Stop Game Timer and Pause play and save state - m_uiControl->SetAction(GameInfoOverlayCommand::None); - SetGameInfoOverlay(GameInfoOverlayState::Pause); - m_updateStateNext = UpdateEngineState::WaitingForPress; - m_pressResult = PressResultState::ContinueLevel; - m_game->PauseGame(); - break; - - case UpdateEngineState::WaitingForResources: - case UpdateEngineState::WaitingForPress: - m_updateStateNext = m_updateState; - break; - - default: - // any other state don't save as next state as they are trancient states and have already set m_updateStateNext - break; - } - m_updateState = UpdateEngineState::Suspended; - - m_controller->Active(false); - m_game->OnSuspending(); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::Resume() -{ - if (m_haveFocus) - { - m_updateState = m_updateStateNext; - } - else - { - m_updateState = UpdateEngineState::Deactivated; - } - - if (m_updateState == UpdateEngineState::WaitingForPress) - { - m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue); - m_controller->WaitForPress(); - } - m_game->OnResuming(); - m_uiControl->ShowGameInfoOverlay(); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::SetBackground(unsigned int background) -{ - m_game->SetBackground(background); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::CycleBackground() -{ - m_game->CycleBackground(); -} - -//-------------------------------------------------------------------------------------- - -void GameMain::LicenseChanged( - ListingInformation^ listing, - LicenseInformation^ license - ) -{ - m_listingInformation = listing; - m_licenseInformation = license; - - m_game->UpdateGameConfig(m_licenseInformation); - - if (m_licenseInformation->IsActive) - { - if (m_licenseInformation->IsTrial) - { - m_renderer->Hud()->SetLicenseInfo("Trial Version"); - } - else - { - m_renderer->Hud()->SetLicenseInfo("Full Version"); - } - } - else - { - m_renderer->Hud()->SetLicenseInfo("License Inactive - defaulting to Trial Version"); - } -} - -//-------------------------------------------------------------------------------------- - -void GameMain::SetYawPitch(float yaw, float pitch) -{ - //Pointing forward - m_controller->Yaw(yaw + XM_PI); - m_controller->Pitch(pitch); -} - -void GameMain::Fire() -{ - m_controller->Fire(); -} \ No newline at end of file diff --git a/DirectXSceneStore/GameMain.h b/DirectXSceneStore/GameMain.h deleted file mode 100644 index 963a1fd..0000000 --- a/DirectXSceneStore/GameMain.h +++ /dev/null @@ -1,151 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -// GameMain: -// This class is the main class required for Windows Store apps. -// It it called on Launch activation and maintains the overall state of the game. -// The GameMain class drives and maintains a state machine for the game. It can be in -// one of seven major stated defined by the UpdateEngineState enum class. -// These are: -// WaitingForResources - the game has requested the game object or the renderer object -// to load resources asynchronously. -// ResourcesLoaded - the asynchronous loading of resources has been completed. This -// is a transient state. -// WaitingForPress - the game is waiting for the player to indicate they are ready to proceed. -// There are three possible actions from this state. This is controlled by m_pressResult. -// The possible outcomes are: -// LoadGame - The player is ready to start a new game and has acknowledged the status -// information provided about the previous state. -// PlayLevel - The player is ready to play the next level. The level has already been -// loaded so active game play will start. -// ContinueLevel - The player is ready to continue playing the current level. Part of the -// current level has already been played. -// Dynamics - the game is active play mode. -// TooSmall - the window is currently too small to play the game. -// Suspended - the game was suspended by PLM. -// Deactivated - the game has lost focus. -// -// GameMain creates and maintains references to three major objects used for the game: -// MoveLookController (m_controller) - this object handles all the game specific user input and -// aggregates touch, mouse/keyboard and Xbox controller input into a unified input control. -// Simple3DGame (m_game) - this object handles all the game specific logic and game dynamics. -// GameRenderer (m_renderer) - This object handles all the graphics rendering for the game. -// - -#pragma once - -#include "Common\DeviceResources.h" -#include "GameContent\MoveLookController.h" -#include "GameRenderer.h" -#include "Simple3DGame.h" -#include "GameUIControl.h" - - -namespace GameControl -{ - private enum class UpdateEngineState - { - WaitingForResources, - ResourcesLoaded, - WaitingForPress, - Dynamics, - TooSmall, - Suspended, - Deactivated, - }; - - private enum class PressResultState - { - LoadGame, - PlayLevel, - ContinueLevel, - }; - - private enum class GameInfoOverlayState - { - Loading, - GameStats, - GameOverExpired, - GameOverCompleted, - LevelStart, - Pause, - }; -}; - -namespace DirectXSceneStore -{ - class GameMain : public DX::IDeviceNotify - { - public: - GameMain(const std::shared_ptr& deviceResources, DirectXSceneStore::IGameUIControl^ UIControl); - ~GameMain(); - void CreateWindowSizeDependentResources(); - void StartRenderLoop(); - void StopRenderLoop(); - void Suspend(); - void Resume(); - Concurrency::critical_section& GetCriticalSection() { return m_criticalSection; } - - // IDeviceNotify - virtual void OnDeviceLost(); - virtual void OnDeviceRestored(); - - void PauseRequested() { if (m_updateState == GameControl::UpdateEngineState::Dynamics) m_pauseRequested = true; }; - void PressComplete() { - if (m_updateState == GameControl::UpdateEngineState::WaitingForPress) m_pressComplete = true; - }; - void ResetGame(); - void SetBackground(unsigned int background); - void CycleBackground(); - void LicenseChanged( - Windows::ApplicationModel::Store::ListingInformation^ listing, - Windows::ApplicationModel::Store::LicenseInformation^ license - ); - - void WindowActivationChanged(Windows::UI::Core::CoreWindowActivationState activationState); - - // To allow some control outside the library, the Yaw, Pitch and Fire elements are exposed through the GameMain here: - void SetYawPitch(float yaw, float pitch); - void Fire(); - - private: - void SetGameInfoOverlay(GameControl::GameInfoOverlayState state); - void InitializeGameState(); - void UpdateLayoutState(); - void Update(); - - void InitializeLicense(); - void InitializeLicenseCore(); - void OnLicenseChanged(); - - private: - bool m_pauseRequested; - bool m_pressComplete; - bool m_haveFocus; - - std::shared_ptr m_deviceResources; - IGameUIControl^ m_uiControl; - - MoveLookController^ m_controller; - GameRenderer^ m_renderer; - Simple3DGame^ m_game; - - GameControl::UpdateEngineState m_updateState; - GameControl::UpdateEngineState m_updateStateNext; - GameControl::PressResultState m_pressResult; - GameControl::GameInfoOverlayState m_gameInfoOverlayState; - Windows::ApplicationModel::Store::LicenseInformation^ m_licenseInformation; - Windows::ApplicationModel::Store::ListingInformation^ m_listingInformation; -#ifdef USE_STORE_SIMULATOR - PersistentState^ m_licenseState; - bool m_isTrial; -#endif - Concurrency::critical_section m_criticalSection; - Windows::Foundation::IAsyncAction^ m_renderLoopWorker; - }; - -}; \ No newline at end of file diff --git a/DirectXSceneStore/GameRenderer.cpp b/DirectXSceneStore/GameRenderer.cpp deleted file mode 100644 index 4d4634e..0000000 --- a/DirectXSceneStore/GameRenderer.cpp +++ /dev/null @@ -1,641 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "GameRenderer.h" -#include "GameContent\ConstantBuffers.h" -#include "GameContent\TargetTexture.h" -#include "Common\BasicLoader.h" -#include "GameContent\CylinderMesh.h" -#include "GameContent\FaceMesh.h" -#include "GameContent\SphereMesh.h" -#include "GameContent\WorldMesh.h" -#include "GameContent\Face.h" -#include "GameContent\Sphere.h" -#include "GameContent\Cylinder.h" -#include "windows.ui.xaml.media.dxinterop.h" - -using namespace concurrency; -using namespace DirectX; -using namespace Microsoft::WRL; -using namespace Windows::UI::Core; -using namespace Windows::UI::Xaml::Controls; - -//---------------------------------------------------------------------- - -GameRenderer::GameRenderer(const std::shared_ptr& deviceResources) : - m_deviceResources(deviceResources), - m_initialized(false), - m_gameResourcesLoaded(false), - m_levelResourcesLoaded(false) -{ - m_gameHud = ref new GameHud( - deviceResources, - "Windows platform samples", - "", - "" - ); - - CreateDeviceDependentResources(); - CreateWindowSizeDependentResources(); -} - -//---------------------------------------------------------------------- - -void GameRenderer::ReleaseDeviceDependentResources() -{ - // On device lost all the device resources are invalid. - // Set the state of the renderer to not have a pointer to the - // Simple3DGame object. It will be reset as a part of the - // game devices resources being recreated. - m_game = nullptr; - m_gameHud->ReleaseDeviceDependentResources(); -} - -//---------------------------------------------------------------------- - -void GameRenderer::CreateDeviceDependentResources() -{ - m_gameResourcesLoaded = false; - m_levelResourcesLoaded = false; - - m_gameHud->CreateDeviceDependentResources(); -} - -//---------------------------------------------------------------------- - -void GameRenderer::CreateWindowSizeDependentResources() -{ - m_gameHud->CreateWindowSizeDependentResources(); - - auto d3dContext = m_deviceResources->GetD3DDeviceContext(); - auto renderTargetSize = m_deviceResources->GetRenderTargetSize(); - - if (m_game != nullptr) - { - // Update the Projection Matrix and the associated Constant Buffer. - m_game->GameCamera()->SetProjParams( - XM_PI / 2, renderTargetSize.Width / renderTargetSize.Height, - 0.01f, - 100.0f - ); - - XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D(); - - ConstantBufferChangeOnResize changesOnResize; - XMStoreFloat4x4( - &changesOnResize.projection, - XMMatrixMultiply( - XMMatrixTranspose(m_game->GameCamera()->Projection()), - XMMatrixTranspose(XMLoadFloat4x4(&orientation)) - ) - ); - - d3dContext->UpdateSubresource( - m_constantBufferChangeOnResize.Get(), - 0, - nullptr, - &changesOnResize, - 0, - 0 - ); - } -} - -//---------------------------------------------------------------------- - -task GameRenderer::CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game) -{ - // Create the device dependent game resources. - // Only the d3dDevice is used in this method. It is expected - // to not run on the same thread as the GameRenderer was created. - // Create methods on the d3dDevice are free-threaded and are safe while any methods - // in the d3dContext should only be used on a single thread and handled - // in the FinalizeCreateGameDeviceResources method. - m_game = game; - - auto d3dDevice = m_deviceResources->GetD3DDevice(); - - D3D11_BUFFER_DESC bd; - ZeroMemory(&bd, sizeof(bd)); - - // Create the constant buffers. - bd.Usage = D3D11_USAGE_DEFAULT; - bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; - bd.CPUAccessFlags = 0; - bd.ByteWidth = (sizeof(ConstantBufferNeverChanges) + 15) / 16 * 16; - DX::ThrowIfFailed( - d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferNeverChanges) - ); - - bd.ByteWidth = (sizeof(ConstantBufferChangeOnResize) + 15) / 16 * 16; - DX::ThrowIfFailed( - d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangeOnResize) - ); - - bd.ByteWidth = (sizeof(ConstantBufferChangesEveryFrame) + 15) / 16 * 16; - DX::ThrowIfFailed( - d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryFrame) - ); - - bd.ByteWidth = (sizeof(ConstantBufferChangesEveryPrim) + 15) / 16 * 16; - DX::ThrowIfFailed( - d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryPrim) - ); - - D3D11_SAMPLER_DESC sampDesc; - ZeroMemory(&sampDesc, sizeof(sampDesc)); - - sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; - sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; - sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; - sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; - sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; - sampDesc.MinLOD = 0; - sampDesc.MaxLOD = FLT_MAX; - DX::ThrowIfFailed( - d3dDevice->CreateSamplerState(&sampDesc, &m_samplerLinear) - ); - - // Start the async tasks to load the shaders and textures. - BasicLoader^ loader = ref new BasicLoader(d3dDevice); - - std::vector> tasks; - OutputDebugString(L"Hello monkey!\r\n"); - uint32 numElements = ARRAYSIZE(PNTVertexLayout); - tasks.push_back(loader->LoadShaderAsync("DirectXSceneStore\\VertexShader.cso", PNTVertexLayout, numElements, &m_vertexShader, &m_vertexLayout)); - tasks.push_back(loader->LoadShaderAsync("DirectXSceneStore\\VertexShaderFlat.cso", nullptr, numElements, &m_vertexShaderFlat, nullptr)); - tasks.push_back(loader->LoadShaderAsync("DirectXSceneStore\\PixelShader.cso", &m_pixelShader)); - tasks.push_back(loader->LoadShaderAsync("DirectXSceneStore\\PixelShaderFlat.cso", &m_pixelShaderFlat)); - - // Make sure the previous versions if any of the textures are released. - m_sphereTexture = nullptr; - m_cylinderTexture = nullptr; - for (uint32 i = 0; i < GameConstants::MaxBackgroundTextures; i++) - { - m_ceilingTexture[i] = nullptr; - m_floorTexture[i] = nullptr; - m_wallsTexture[i] = nullptr; - } - - // Load Game specific textures. - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\seafloor.dds", nullptr, &m_sphereTexture)); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\metal_texture.dds", nullptr, &m_cylinderTexture)); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\cellceiling.dds", nullptr, &m_ceilingTexture[0])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\cellfloor.dds", nullptr, &m_floorTexture[0])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\cellwall.dds", nullptr, &m_wallsTexture[0])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\nightceiling.dds", nullptr, &m_ceilingTexture[1])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\nightfloor.dds", nullptr, &m_floorTexture[1])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\nightwall.dds", nullptr, &m_wallsTexture[1])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\dayceiling.dds", nullptr, &m_ceilingTexture[2])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\dayfloor.dds", nullptr, &m_floorTexture[2])); - tasks.push_back(loader->LoadTextureAsync("DirectXSceneStore\\Assets\\daywall.dds", nullptr, &m_wallsTexture[2])); - tasks.push_back(create_task([]() - { - // Simulate loading additional resources by introducing a delay. - wait(GameConstants::InitialLoadingDelay); - })); - - // Return the task group of all the async tasks for loading the shader and texture assets. - return when_all(tasks.begin(), tasks.end()); -} - -//---------------------------------------------------------------------- - -void GameRenderer::FinalizeCreateGameDeviceResources() -{ - // All asynchronously loaded resources have completed loading. - // Now associate all the resources with the appropriate game objects. - // This method is expected to run in the same thread as the GameRenderer - // was created. All work will happen behind the "Loading ..." screen after the - // main loop has been entered. - - // Initialize the Constant buffer with the light positions - // These are handled here to ensure that the d3dContext is only - // used in one thread. - - auto d3dDevice = m_deviceResources->GetD3DDevice(); - - ConstantBufferNeverChanges constantBufferNeverChanges; - constantBufferNeverChanges.lightPosition[0] = XMFLOAT4( 3.5f, 2.5f, 5.5f, 1.0f); - constantBufferNeverChanges.lightPosition[1] = XMFLOAT4( 3.5f, 2.5f, -5.5f, 1.0f); - constantBufferNeverChanges.lightPosition[2] = XMFLOAT4(-3.5f, 2.5f, -5.5f, 1.0f); - constantBufferNeverChanges.lightPosition[3] = XMFLOAT4( 3.5f, 2.5f, 5.5f, 1.0f); - constantBufferNeverChanges.lightColor = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f); - m_deviceResources->GetD3DDeviceContext()->UpdateSubresource( - m_constantBufferNeverChanges.Get(), - 0, - nullptr, - &constantBufferNeverChanges, - 0, - 0 - ); - - // For the targets, there are two unique generated textures. - // Each texture image includes the number of the texture. - // Make sure the 2D rendering is occurring on the same thread - // as the main rendering. - - TargetTexture^ textureGenerator = ref new TargetTexture( - d3dDevice, - m_deviceResources->GetD2DFactory(), - m_deviceResources->GetDWriteFactory(), - m_deviceResources->GetD2DDeviceContext() - ); - - MeshObject^ cylinderMesh = ref new CylinderMesh(d3dDevice, 26); - MeshObject^ targetMesh = ref new FaceMesh(d3dDevice); - MeshObject^ sphereMesh = ref new SphereMesh(d3dDevice, 26); - - Material^ cylinderMaterial = ref new Material( - XMFLOAT4(0.8f, 0.8f, 0.8f, .5f), - XMFLOAT4(0.8f, 0.8f, 0.8f, .5f), - XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), - 15.0f, - m_cylinderTexture.Get(), - m_vertexShader.Get(), - m_pixelShader.Get() - ); - - Material^ sphereMaterial = ref new Material( - XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f), - XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f), - XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), - 50.0f, - m_sphereTexture.Get(), - m_vertexShader.Get(), - m_pixelShader.Get() - ); - - auto objects = m_game->RenderObjects(); - - // Attach the textures to the appropriate game objects. - for (auto object = objects.begin(); object != objects.end(); object++) - { - if ((*object)->TargetId() == GameConstants::WorldFloorId) - { - (*object)->NormalMaterial( - ref new Material( - XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f), - XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f), - XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f), - 150.0f, - m_floorTexture[0].Get(), - m_vertexShaderFlat.Get(), - m_pixelShaderFlat.Get() - ) - ); - (*object)->Mesh(ref new WorldFloorMesh(d3dDevice)); - } - else if ((*object)->TargetId() == GameConstants::WorldCeilingId) - { - (*object)->NormalMaterial( - ref new Material( - XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f), - XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f), - XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f), - 150.0f, - m_ceilingTexture[0].Get(), - m_vertexShaderFlat.Get(), - m_pixelShaderFlat.Get() - ) - ); - (*object)->Mesh(ref new WorldCeilingMesh(d3dDevice)); - } - else if ((*object)->TargetId() == GameConstants::WorldWallsId) - { - (*object)->NormalMaterial( - ref new Material( - XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f), - XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f), - XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f), - 150.0f, - m_wallsTexture[0].Get(), - m_vertexShaderFlat.Get(), - m_pixelShaderFlat.Get() - ) - ); - (*object)->Mesh(ref new WorldWallsMesh(d3dDevice)); - } - else if (Cylinder^ cylinder = dynamic_cast(*object)) - { - cylinder->Mesh(cylinderMesh); - cylinder->NormalMaterial(cylinderMaterial); - } - else if (Face^ target = dynamic_cast(*object)) - { - const int bufferLength = 16; - char16 str[bufferLength]; - int len = swprintf_s(str, bufferLength, L"%d", target->TargetId()); - Platform::String^ string = ref new Platform::String(str, len); - - ComPtr texture; - textureGenerator->CreateTextureResourceView(string, &texture); - target->NormalMaterial( - ref new Material( - XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f), - XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f), - XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f), - 5.0f, - texture.Get(), - m_vertexShader.Get(), - m_pixelShader.Get() - ) - ); - - textureGenerator->CreateHitTextureResourceView(string, &texture); - target->HitMaterial( - ref new Material( - XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f), - XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f), - XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f), - 5.0f, - texture.Get(), - m_vertexShader.Get(), - m_pixelShader.Get() - ) - ); - - target->Mesh(targetMesh); - } - else if (Sphere^ sphere = dynamic_cast(*object)) - { - sphere->Mesh(sphereMesh); - sphere->NormalMaterial(sphereMaterial); - } - } - - // Ensure that the camera has been initialized with the right Projection - // matrix. The camera is not created at the time the first window resize event - // occurs. - auto renderTargetSize = m_deviceResources->GetRenderTargetSize(); - m_game->GameCamera()->SetProjParams( - XM_PI / 2, - renderTargetSize.Width / renderTargetSize.Height, - 0.01f, - 100.0f - ); - - // Make sure that Projection matrix has been set in the constant buffer - // now that all the resources are loaded. - // We are handling screen rotations directly to eliminate an unaligned - // fullscreen copy. As a result, it is necessary to post multiply the rotationTransform3D - // matrix to the camera projection matrix. - // The matrices are transposed due to the shader code expecting the matrices in the opposite - // row/column order from the DirectX math library. - - auto orientation = m_deviceResources->GetOrientationTransform3D(); - - ConstantBufferChangeOnResize changesOnResize; - XMStoreFloat4x4( - &changesOnResize.projection, - XMMatrixMultiply( - XMMatrixTranspose(m_game->GameCamera()->Projection()), - XMMatrixTranspose(XMLoadFloat4x4(&orientation)) - ) - ); - - m_deviceResources->GetD3DDeviceContext()->UpdateSubresource( - m_constantBufferChangeOnResize.Get(), - 0, - nullptr, - &changesOnResize, - 0, - 0 - ); - - m_gameResourcesLoaded = true; -} - -//---------------------------------------------------------------------- - -task GameRenderer::LoadLevelResourcesAsync() -{ - m_levelResourcesLoaded = false; - - return create_task([this]() - { - // This is where additional async loading of level specific resources - // would be done. Since there aren't any to load, just simulate - // by delaying for some time. - wait(GameConstants::LevelLoadingDelay); - }); -} - -//---------------------------------------------------------------------- - -void GameRenderer::FinalizeLoadLevelResources() -{ - // Once the level specific resources had been loaded, this method is - // where D3D context specific actions would be handled. This method - // runs in the same thread context as the GameRenderer was created. - - m_levelResourcesLoaded = true; -} - -//---------------------------------------------------------------------- - -void GameRenderer::Render() -{ - bool stereoEnabled = m_deviceResources->GetStereoState(); - - auto d3dContext = m_deviceResources->GetD3DDeviceContext(); - auto d2dContext = m_deviceResources->GetD2DDeviceContext(); - - int renderingPasses = 1; - if (stereoEnabled) - { - renderingPasses = 2; - } - - for (int i = 0; i < renderingPasses; i++) - { - // Iterate through the number of rendering passes to be completed. - if (i > 0) - { - // Doing the Right Eye View. - ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetViewRight() }; - - d3dContext->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView()); - d3dContext->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0); - d2dContext->SetTarget(m_deviceResources->GetD2DTargetBitmapRight()); - } - else - { - // Doing the Mono or Left Eye View. - ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() }; - - d3dContext->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView()); - d3dContext->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0); - d2dContext->SetTarget(m_deviceResources->GetD2DTargetBitmap()); - } - - if (m_game != nullptr && m_gameResourcesLoaded && m_levelResourcesLoaded) - { - // This section is only used after the game state has been initialized and all device - // resources needed for the game have been created and associated with the game objects. - if (stereoEnabled) - { - // When doing stereo, it is necessary to update the projection matrix once per rendering pass. - - auto orientation = m_deviceResources->GetOrientationTransform3D(); - - ConstantBufferChangeOnResize changesOnResize; - XMStoreFloat4x4( - &changesOnResize.projection, - XMMatrixMultiply( - XMMatrixTranspose( - i == 0 ? - m_game->GameCamera()->LeftEyeProjection() : - m_game->GameCamera()->RightEyeProjection() - ), - XMMatrixTranspose(XMLoadFloat4x4(&orientation)) - ) - ); - - d3dContext->UpdateSubresource( - m_constantBufferChangeOnResize.Get(), - 0, - nullptr, - &changesOnResize, - 0, - 0 - ); - } - // Update variables that change once per frame. - - ConstantBufferChangesEveryFrame constantBufferChangesEveryFrame; - XMStoreFloat4x4( - &constantBufferChangesEveryFrame.view, - XMMatrixTranspose(m_game->GameCamera()->View()) - ); - d3dContext->UpdateSubresource( - m_constantBufferChangesEveryFrame.Get(), - 0, - nullptr, - &constantBufferChangesEveryFrame, - 0, - 0 - ); - - // Setup the graphics pipeline. This sample uses the same InputLayout and set of - // constant buffers for all shaders, so they only need to be set once per frame. - - d3dContext->IASetInputLayout(m_vertexLayout.Get()); - d3dContext->VSSetConstantBuffers(0, 1, m_constantBufferNeverChanges.GetAddressOf()); - d3dContext->VSSetConstantBuffers(1, 1, m_constantBufferChangeOnResize.GetAddressOf()); - d3dContext->VSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf()); - d3dContext->VSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf()); - - d3dContext->PSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf()); - d3dContext->PSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf()); - d3dContext->PSSetSamplers(0, 1, m_samplerLinear.GetAddressOf()); - - auto objects = m_game->RenderObjects(); - for (auto object = objects.begin(); object != objects.end(); object++) - { - (*object)->Render(d3dContext, m_constantBufferChangesEveryPrim.Get()); - } - } - else - { - const float ClearColor[4] = { 0.5f, 0.5f, 0.8f, 1.0f }; - - // Only need to clear the background when not rendering the full 3D scene since - // the 3D world is a fully enclosed box and the dynamics prevents the camera from - // moving outside this space. - if (i > 0) - { - // Doing the Right Eye View. - d3dContext->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetViewRight(), ClearColor); - } - else - { - // Doing the Mono or Left Eye View. - d3dContext->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), ClearColor); - } - } - - d2dContext->BeginDraw(); - - // To handle the swapchain being pre-rotated, set the D2D transformation to include it. - d2dContext->SetTransform(m_deviceResources->GetOrientationTransform2D()); - - if (m_game != nullptr && m_gameResourcesLoaded) - { - // This is only used after the game state has been initialized. - m_gameHud->Render(m_game); - } - - // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device - // is lost. It will be handled during the next call to Present. - HRESULT hr = d2dContext->EndDraw(); - if (hr != D2DERR_RECREATE_TARGET) - { - DX::ThrowIfFailed(hr); - } - } -} - -//---------------------------------------------------------------------- - -#if defined(_DEBUG) -void GameRenderer::ReportLiveDeviceObjects() -{ - // If the debug layer isn't present on the system then this QI will fail. In that case - // the routine just exits. This is a debugging aid to see the active D3D objects and - // is not critical to functional operation of the sample. - - ComPtr debugLayer; - ComPtrd3dDevice = m_deviceResources->GetD3DDevice(); - HRESULT hr = d3dDevice.As(&debugLayer); - if (FAILED(hr)) - { - return; - } - DX::ThrowIfFailed( - debugLayer->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL) - ); -} - -//---------------------------------------------------------------------- - -#endif - -void GameRenderer::SetBackground(uint32 background) -{ - if (background < GameConstants::MaxBackgroundTextures) - { - if (m_ceilingTexture[background] != nullptr && - m_floorTexture[background] != nullptr && - m_wallsTexture[background] != nullptr) - { - auto objects = m_game->RenderObjects(); - - // Attach the textures to the appropriate game objects. - for (auto object = objects.begin(); object != objects.end(); object++) - { - if ((*object)->TargetId() == GameConstants::WorldFloorId) - { - (*object)->NormalMaterial()->SetTexture(m_floorTexture[background].Get()); - } - else if ((*object)->TargetId() == GameConstants::WorldCeilingId) - { - (*object)->NormalMaterial()->SetTexture(m_ceilingTexture[background].Get()); - } - else if ((*object)->TargetId() == GameConstants::WorldWallsId) - { - (*object)->NormalMaterial()->SetTexture(m_wallsTexture[background].Get()); - } - } - } - } -} - -//-------------------------------------------------------------------------------------- - - diff --git a/DirectXSceneStore/GameRenderer.h b/DirectXSceneStore/GameRenderer.h deleted file mode 100644 index b14bba2..0000000 --- a/DirectXSceneStore/GameRenderer.h +++ /dev/null @@ -1,106 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// GameRenderer: -// This is the renderer for the game. -// It is responsble for creating and maintaining all the D3D11 and D2D objects -// used to generate the game visuals. It maintains a reference to the Simple3DGame -// object to retrieve the list of objects to render as well as status of the -// game for the Heads Up Display (HUD). -// -// The renderer is designed to use a standard vertex layout across all objects. This -// simplifies the shader design and allows for easy changes between shaders independent -// of the objects' geometry. Each vertex is defined by a position, a normal and one set of -// 2D texture coordinates. The shaders all expect one 2D texture and 4 constant buffers: -// m_constantBufferNeverChanges - general parameters that are set only once. This includes -// all the lights used in scene generation. -// m_constantBufferChangeOnResize - the projection matrix. It is typically only changed when -// the window is resized, however it will be changed 2x per frame when rendering -// in 3D stereo. -// m_constantBufferChangesEveryFrame - the view transformation matrix. This is set once per frame. -// m_constantBufferChangesEveryPrim - the parameters for each object. It includes the object to world -// transformation matrix as well as material properties like color and specular exponent for lighting -// calculations. -// -// The renderer also maintains a set of texture resources that will be associated with particular game objects. -// It knows which textures are to be associated with which objects and will do that association once the -// textures have been loaded. -// -// The renderer provides a set of methods to allow for a "standard" sequence to be executed for loading general -// game resources and for level specific resources. Because D3D11 allows free threaded creation of objects, -// textures will be loaded asynchronously and in parallel, however D3D11 does not allow for multiple threads to -// be using the DeviceContext at the same time. -// -// The pattern is: -// create_task([this]() -// { -// // create/load device resources -// }).then([this]() -// { -// // create/load device context resources -// }, task_continuation_context::use_current()); - -#include "Common\DeviceResources.h" -#include "GameHud.h" -#include "Simple3DGame.h" - -ref class Simple3DGame; -ref class GameHud; - -ref class GameRenderer -{ -internal: - GameRenderer(const std::shared_ptr& deviceResources); - - void CreateDeviceDependentResources(); - void CreateWindowSizeDependentResources(); - void ReleaseDeviceDependentResources(); - void Render(); - - concurrency::task CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game); - void FinalizeCreateGameDeviceResources(); - concurrency::task LoadLevelResourcesAsync(); - void FinalizeLoadLevelResources(); - - void SetBackground(uint32 background); - - GameHud^ Hud() { return m_gameHud; } - -#if defined(_DEBUG) - void ReportLiveDeviceObjects(); -#endif - -protected private: - // Cached pointer to device resources. - std::shared_ptr m_deviceResources; - - bool m_initialized; - bool m_gameResourcesLoaded; - bool m_levelResourcesLoaded; - GameHud^ m_gameHud; - Simple3DGame^ m_game; - - Microsoft::WRL::ComPtr m_sphereTexture; - Microsoft::WRL::ComPtr m_cylinderTexture; - Microsoft::WRL::ComPtr m_ceilingTexture[GameConstants::MaxBackgroundTextures]; - Microsoft::WRL::ComPtr m_floorTexture[GameConstants::MaxBackgroundTextures]; - Microsoft::WRL::ComPtr m_wallsTexture[GameConstants::MaxBackgroundTextures]; - - // Constant Buffers - Microsoft::WRL::ComPtr m_constantBufferNeverChanges; - Microsoft::WRL::ComPtr m_constantBufferChangeOnResize; - Microsoft::WRL::ComPtr m_constantBufferChangesEveryFrame; - Microsoft::WRL::ComPtr m_constantBufferChangesEveryPrim; - Microsoft::WRL::ComPtr m_samplerLinear; - Microsoft::WRL::ComPtr m_vertexShader; - Microsoft::WRL::ComPtr m_vertexShaderFlat; - Microsoft::WRL::ComPtr m_pixelShader; - Microsoft::WRL::ComPtr m_pixelShaderFlat; - Microsoft::WRL::ComPtr m_vertexLayout; -}; diff --git a/DirectXSceneStore/GameUIConstants.h b/DirectXSceneStore/GameUIConstants.h deleted file mode 100644 index c85c8d2..0000000 --- a/DirectXSceneStore/GameUIConstants.h +++ /dev/null @@ -1,39 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// ** Store Version *** -namespace GameInfoOverlayConstant -{ - static const float Width = 750.0f; - static const float Height = 380.0f; - static const float TitlePointSize = 32.0f; - static const float TitleHeight = 50.0f; - static const float Separator = 10.0f; - static const float BodyPointSize = 24.0f; - static const float ActionHeight = 40.0f; - static const float TopMargin = 50.0f; - static const float SideMargin = 50.0f; - static const float BottomMargin = 5.0f; -}; - -namespace GameConstants -{ - static const float CrossHairHalfSize = 20.0f; - static const float HudSafeWidth = 300.0f; - static const float HudRightOffset = 250.0f; - static const float HudTopOffset = 50.0f; - static const float Margin = 5.0f; - static const float HudBodyPointSize = 24.0f; - static const float HudTitleHeaderPointSize = 16.0f; - static const float HudTitleBodyPointSize = 36.0f; - static const float HudLicensePointSize = 20.0f; - - static const float TouchRectangleSize = 300.0f; - static const float MinPlayableWidth = 512.0f; -}; diff --git a/DirectXSceneStore/GameUIControl.h b/DirectXSceneStore/GameUIControl.h deleted file mode 100644 index 4e8627f..0000000 --- a/DirectXSceneStore/GameUIControl.h +++ /dev/null @@ -1,53 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved -#pragma once - -// The IGameUIControl interface provides an abstraction to the GameMain class -// for controlling UI elements on the screen in response to game state. It helps to -// provide separation between the game control and how the UI is displayed to the user. -// SetGameLoading - is called to have the UI indicate the game is currently loading -// resources for the game or a particular level. -// SetGameStats - is called to have the UI indicate the status of the last completed game. -// SetGameOver - is called to have the UI indicate this iteration of the game as finished. -// SetLevelStart - is called to have the UI indicate the level is ready to begin. This includes -// providing the objectives for the level and other current data. -// SetPause - is called to have the UI indicate the game is currently in the Paused state. -// ShowTooSmall - this method indicates the UI should display to the user that the current -// display configuration is too small for the game to be played. -// HideTooSmall - this method inticates the UI should stop displaying to the user that the -// current display configuration is too small for game play. -// SetAction - is called to have the UI indicate the next action the user should take. -// ShowGameInfoOverlay - is called to have the UI display to the user the current state -// as defined by the other interface calls above. -// HideGameInfoOverlay - is called to have the UI remove the display of the current state -// when the game transitions into active game play. - -namespace DirectXSceneStore -{ - public enum class GameInfoOverlayCommand - { - None, - TapToContinue, - PleaseWait, - PlayAgain, - }; - - public interface class IGameUIControl - { - void SetGameLoading(); - void SetGameStats(int maxLevel, int hitCount, int shotCount); - void SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore); - void SetLevelStart(int level, Platform::String^ objective, float timeLimit, float bonusTime); - void SetPause(int level, int hitCount, int shotCount, float timeRemaining); - void ShowTooSmall(); - void HideTooSmall(); - void SetAction(GameInfoOverlayCommand action); - void HideGameInfoOverlay(); - void ShowGameInfoOverlay(); - }; -}; - diff --git a/DirectXSceneStore/GameUIStyles.xaml b/DirectXSceneStore/GameUIStyles.xaml deleted file mode 100644 index 80d6305..0000000 --- a/DirectXSceneStore/GameUIStyles.xaml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - diff --git a/DirectXSceneStore/MoveLookControllerKinect.cpp b/DirectXSceneStore/MoveLookControllerKinect.cpp deleted file mode 100644 index 5f956e0..0000000 --- a/DirectXSceneStore/MoveLookControllerKinect.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "pch.h" -#include "MoveLookControllerKinect.h" - - -MoveLookController^ MoveLookControllerKinect::Create() -{ - auto p = ref new MoveLookControllerKinect(); - return static_cast(p); -} - -MoveLookControllerKinect::MoveLookControllerKinect() -{ - -} - - diff --git a/DirectXSceneStore/MoveLookControllerKinect.h b/DirectXSceneStore/MoveLookControllerKinect.h deleted file mode 100644 index f7cf91b..0000000 --- a/DirectXSceneStore/MoveLookControllerKinect.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -#include "GameContent\MoveLookController.h" -ref class MoveLookControllerKinect : public MoveLookController -{ -public: - -internal: - static MoveLookController^ Create(); - -private: - MoveLookControllerKinect(); - -}; - diff --git a/DirectXSceneStore/MoveLookControllerXaml.cpp b/DirectXSceneStore/MoveLookControllerXaml.cpp deleted file mode 100644 index d78992b..0000000 --- a/DirectXSceneStore/MoveLookControllerXaml.cpp +++ /dev/null @@ -1,249 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -//// *** Windows Version *** - -#include "pch.h" -#include "MoveLookControllerXaml.h" - -using namespace Windows::UI::Core; -using namespace Windows::UI::Input; -using namespace Windows::UI; -using namespace Windows::Foundation; -using namespace Microsoft::WRL; -using namespace DirectX; -using namespace Windows::Devices::Input; -using namespace Windows::System; - -//---------------------------------------------------------------------- - -MoveLookController^ MoveLookControllerXaml::Create(_In_ CoreWindow^ window, - _In_ CoreDispatcher^ dispatcher - ) -{ - auto p = ref new MoveLookControllerXaml(window, dispatcher); - return static_cast(p); -} - -//---------------------------------------------------------------------- - -MoveLookControllerXaml::MoveLookControllerXaml( - _In_ CoreWindow^ window, - _In_ CoreDispatcher ^dispatcher - ) : - m_isControllerConnected(false) -{ - // Even though all current realizations of MoveLookController install the - // PointerPressed, PointerMoved, PointerReleased and PointerExited event - // handlers, it was decided to put all event handler registrations together - // in the constructor. - - // The windows version of the MoveLookController installs event handlers - // for keyboard input and for relative mouse movement. There are two - // parts required to enable relative mouse movement, the event handler - // and disabling the cursor pointer. The game is running on a separate thread - // from the Xaml UI thread, and this separate thread does NOT have access to - // the CoreWindow. The dispatcher can be used to marshal execution back to - // the Xaml UI thread which does have a CoreWindow. The Dispatcher is cached - // to enable execution of code on the UI thread to turn on and off the cursor glyph. - - m_dispatcher = dispatcher; - - //window->PointerPressed += - // ref new TypedEventHandler(this, &MoveLookControllerXaml::OnPointerPressed); - - //window->PointerMoved += - // ref new TypedEventHandler(this, &MoveLookControllerXaml::OnPointerMoved); - - //window->PointerReleased += - // ref new TypedEventHandler(this, &MoveLookControllerXaml::OnPointerReleased); - - //window->PointerExited += - // ref new TypedEventHandler(this, &MoveLookControllerXaml::OnPointerExited); - - //window->KeyDown += - // ref new TypedEventHandler(this, &MoveLookControllerXaml::OnKeyDown); - - //window->KeyUp += - // ref new TypedEventHandler(this, &MoveLookControllerXaml::OnKeyUp); - - //// There is a separate handler for mouse only relative mouse movement events. - //MouseDevice::GetForCurrentView()->MouseMoved += - // ref new TypedEventHandler(this, &MoveLookControllerXaml::OnMouseMoved); -} - -//---------------------------------------------------------------------- - -void MoveLookControllerXaml::ResetState() -{ - MoveLookController::ResetState(); - m_xinputStartButtonInUse = false; - m_xinputTriggerInUse = false; -} - -//---------------------------------------------------------------------- - -void MoveLookControllerXaml::ShowCursor() -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - // NOTE: PointerCursor is not implemented on WindowsPhone. - m_dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this]() - { - // Turn on mouse cursor. - // This disables relative mouse movement events. - CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0); - }) - ); -} - -//---------------------------------------------------------------------- - -void MoveLookControllerXaml::HideCursor() -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - // NOTE: PointerCursor is not implemented on WindowsPhone. - m_dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this]() - { - // Turn off the cursor to enable relative mouse. - CoreWindow::GetForCurrentThread()->PointerCursor = nullptr; - }) - ); -} - -//---------------------------------------------------------------------- - -void MoveLookControllerXaml::UpdatePollingDevices() -{ - if (!m_isControllerConnected) - { - // Check for controller connection by trying to get the capabilties. - DWORD capsResult = XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &m_xinputCaps); - if (capsResult != ERROR_SUCCESS) - { - return; - } - // Device is connected. - m_isControllerConnected = true; - m_xinputStartButtonInUse = false; - m_xinputTriggerInUse = false; - } - - DWORD stateResult = XInputGetState(0, &m_xinputState); - if (stateResult != ERROR_SUCCESS) - { - // Device is no longer connected. - m_isControllerConnected = false; - } - - switch (m_state) - { - case MoveLookControllerState::WaitForInput: - if (m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_START) - { - m_xinputStartButtonInUse = true; - } - else if (m_xinputStartButtonInUse) - { - // Trigger once only on button release. - m_xinputStartButtonInUse = false; - m_buttonPressed = true; - } - break; - - case MoveLookControllerState::Active: - if (m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_START) - { - m_xinputStartButtonInUse = true; - } - else if (m_xinputStartButtonInUse) - { - // Trigger once only on button release. - m_xinputStartButtonInUse = false; - m_pausePressed = true; - } - // Use the Left Thumb joystick on the Xbox controller to control - // the eye point position control. - // The controller input goes from -32767 to 32767. We will normalize - // this from -1 to 1 and keep a dead spot in the middle to avoid drift. - - if (m_xinputState.Gamepad.sThumbLX > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE || - m_xinputState.Gamepad.sThumbLX < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) - { - float x = (float) m_xinputState.Gamepad.sThumbLX / 32767.0f; - m_moveCommand.x -= x / fabsf(x); - } - - if (m_xinputState.Gamepad.sThumbLY > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE || - m_xinputState.Gamepad.sThumbLY < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) - { - float y = (float) m_xinputState.Gamepad.sThumbLY / 32767.0f; - m_moveCommand.y += y / fabsf(y); - } - - // Use the Right Thumb Joystick on the Xbox controller to control - // the look at control. - // The controller input goes from -32767 to 32767. We will normalize - // this from -1 to 1 and keep a dead spot in the middle to avoid drift. - XMFLOAT2 pointerDelta; - if (m_xinputState.Gamepad.sThumbRX > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE || - m_xinputState.Gamepad.sThumbRX < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) - { - pointerDelta.x = (float) m_xinputState.Gamepad.sThumbRX / 32767.0f; - pointerDelta.x = pointerDelta.x * pointerDelta.x * pointerDelta.x; - } - else - { - pointerDelta.x = 0.0f; - } - if (m_xinputState.Gamepad.sThumbRY > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE || - m_xinputState.Gamepad.sThumbRY < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) - { - pointerDelta.y = (float) m_xinputState.Gamepad.sThumbRY / 32767.0f; - pointerDelta.y = pointerDelta.y * pointerDelta.y * pointerDelta.y; - } - else - { - pointerDelta.y = 0.0f; - } - - XMFLOAT2 rotationDelta; - rotationDelta.x = pointerDelta.x * 0.08f; // Scale for control sensitivity. - rotationDelta.y = pointerDelta.y * 0.08f; - - // Update our orientation based on the command. - m_pitch += rotationDelta.y; - m_yaw += rotationDelta.x; - - // Limit pitch to straight up or straight down. - m_pitch = __max(-XM_PI / 2.0f, m_pitch); - m_pitch = __min(+XM_PI / 2.0f, m_pitch); - - // Check the state of the Right Trigger button. This is used to indicate fire control. - - if (m_xinputState.Gamepad.bRightTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD) - { - if (!m_autoFire && !m_xinputTriggerInUse) - { - m_firePressed = true; - } - m_xinputTriggerInUse = true; - } - else - { - m_xinputTriggerInUse = false; - } - break; - } -} - -//---------------------------------------------------------------------- diff --git a/DirectXSceneStore/MoveLookControllerXaml.h b/DirectXSceneStore/MoveLookControllerXaml.h deleted file mode 100644 index 34bf767..0000000 --- a/DirectXSceneStore/MoveLookControllerXaml.h +++ /dev/null @@ -1,65 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -//// *** Windows Version *** - -#pragma once - -// MoveLookControllerXaml: -// This class derives from the MoveLookController abstract class. -// It implements the constructor to connect the event handlers to the -// CoreWindow object. -// For the Windows specific implementation it includes support for both -// relative mouse movement and XBox Controller input via XInput. -// NOTE: enabling and disabling the cursor glyphs is handled in DirectXPage.xaml.cpp -// because the game is running on a separate thread that does not have access to -// the CoreWindow. The DirectXPage.xaml.cpp HideCursor and ShowCursor marshall to -// the UI thread where Xaml is running with the CoreWindow. -// -// The following controls are mapped from the Xbox controller using XInput: -// XINPUT_GAMEPAD_START - is mapped to IsPressComplete in the WaitForInput state and -// IsPauseRequested in the Active state. -// Left Thumb stick - is mapped to the move control in Active mode -// Right Thumb stick - is mapped to the look control in Active mode -// Right Trigger - is mapped to IsFiring in Active mode or "Fire" button. -// - -#include "GameContent\MoveLookController.h" -#include - -ref class MoveLookControllerXaml : public MoveLookController -{ -internal: - static MoveLookController^ Create( - _In_ Windows::UI::Core::CoreWindow^ window, - _In_ Windows::UI::Core::CoreDispatcher^ dispatcher - ); - -private: - MoveLookControllerXaml( - _In_ Windows::UI::Core::CoreWindow^ window, - _In_ Windows::UI::Core::CoreDispatcher^ dispatcher - ); - -protected: - virtual void ResetState() override; - virtual void UpdatePollingDevices() override; - virtual bool PollingFireInUse() override { return m_xinputTriggerInUse; }; - virtual void ShowCursor() override; - virtual void HideCursor() override; - -protected private: - // Cached pointer to a dispatcher to marshal execution back to the Xaml UI thread. - Windows::UI::Core::CoreDispatcher^ m_dispatcher; - - // Xbox Input related members. - bool m_isControllerConnected; // Is the Xbox controller connected. - XINPUT_CAPABILITIES m_xinputCaps; // Capabilites of the controller. - XINPUT_STATE m_xinputState; // The current state of the controller. - bool m_xinputStartButtonInUse; - bool m_xinputTriggerInUse; -}; diff --git a/DirectXSceneStore/ProductItem.cpp b/DirectXSceneStore/ProductItem.cpp deleted file mode 100644 index 275439d..0000000 --- a/DirectXSceneStore/ProductItem.cpp +++ /dev/null @@ -1,179 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "ProductItem.h" - -using namespace DirectXSceneStore; -using namespace Platform; -using namespace Windows::Foundation; -using namespace Windows::UI::Xaml; -using namespace Windows::UI::Xaml::Interop; -using namespace Windows::UI::Xaml::Data; -using namespace Windows::ApplicationModel::Store; - -ProductItem::ProductItem( - ListingInformation^ listing, - LicenseInformation^ license, - Platform::String^ productId, - bool isApp - ) -{ - m_isApp = isApp; - m_isAppActive = license->IsActive; - m_isAppTrial = license->IsTrial; - m_productId = productId; - - if (m_isApp) - { - SetStatus(license); - if (listing != nullptr) - { - m_title = listing->Name; - m_formattedPrice = listing->FormattedPrice; - } - else - { - m_title = productId; - m_formattedPrice = ""; - } - } - else - { - if (listing != nullptr) - { - ProductListing^ productListing = listing->ProductListings->Lookup(m_productId); - m_title = productListing->Name; - m_formattedPrice = productListing->FormattedPrice; - } - else - { - m_title = m_productId; - m_formattedPrice = ""; - } - SetStatus(license); - } -} - -void ProductItem::SetStatus(LicenseInformation^ license) -{ - if (m_isApp) - { - if (m_isAppActive) - { - if (m_isAppTrial) - { - m_isAvailableForPurchase = true; - m_foreground = "#a0a0a0"; - m_status = "Trial"; - } - else - { - m_isAvailableForPurchase = false; - m_foreground = "#707070"; - m_status = "Purchased"; - } - } - else - { - m_isAvailableForPurchase = true; - m_foreground = "#a0a0a0"; - m_status = "No License"; - } - } - else - { - if (m_isAppActive) - { - if (m_isAppTrial) - { - m_isProductActive = false; - m_isAvailableForPurchase = false; - m_foreground = "#707070"; - m_status = "unavailable"; - } - else - { - ProductLicense^ productLicense = license->ProductLicenses->Lookup(m_productId); - - m_isProductActive = productLicense->IsActive; - m_isAvailableForPurchase = !m_isProductActive; - if (m_isProductActive) - { - m_status = "Purchased"; - m_foreground = "#707070"; - } - else - { - m_status = "No License"; - m_foreground = "#a0a0a0"; - } - } - } - else - { - m_isProductActive = false; - m_isAvailableForPurchase = false; - m_foreground = "#707070"; - } - } -} - -void ProductItem::UpdateContent(LicenseInformation^ license) -{ - if (m_isAppActive != license->IsActive || - m_isAppTrial != license->IsTrial) - { - m_isAppActive = license->IsActive; - m_isAppTrial = license->IsTrial; - SetStatus(license); - PropertyChanged(this, ref new PropertyChangedEventArgs("Status")); - PropertyChanged(this, ref new PropertyChangedEventArgs("BuyVisibility")); - PropertyChanged(this, ref new PropertyChangedEventArgs("Foreground")); - } - else if (!m_isApp && m_isAppActive && !m_isAppTrial) - { - if (license->ProductLicenses->Lookup(m_productId)->IsActive != m_isProductActive) - { - SetStatus(license); - PropertyChanged(this, ref new PropertyChangedEventArgs("Status")); - PropertyChanged(this, ref new PropertyChangedEventArgs("BuyVisibility")); - PropertyChanged(this, ref new PropertyChangedEventArgs("Foreground")); - } - } -} - -void ProductItem::UpdateContent(ListingInformation^ listing) -{ - if (m_isApp) - { - if (m_title != listing->Name) - { - m_title = listing->Name; - PropertyChanged(this, ref new PropertyChangedEventArgs("Title")); - } - if (m_formattedPrice != listing->FormattedPrice) - { - m_formattedPrice = listing->FormattedPrice; - PropertyChanged(this, ref new PropertyChangedEventArgs("Price")); - } - } - else - { - ProductListing^ productListing = listing->ProductListings->Lookup(m_productId); - if (m_title != productListing->Name) - { - m_title = productListing->Name; - PropertyChanged(this, ref new PropertyChangedEventArgs("Title")); - } - if (m_formattedPrice != productListing->FormattedPrice) - { - m_formattedPrice = productListing->FormattedPrice; - PropertyChanged(this, ref new PropertyChangedEventArgs("Price")); - } - } -} diff --git a/DirectXSceneStore/ProductItem.h b/DirectXSceneStore/ProductItem.h deleted file mode 100644 index 4b31cb0..0000000 --- a/DirectXSceneStore/ProductItem.h +++ /dev/null @@ -1,94 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -namespace DirectXSceneStore -{ - [Windows::UI::Xaml::Data::Bindable] - [Windows::Foundation::Metadata::WebHostHidden] - public ref class ProductItem sealed : - public Windows::UI::Xaml::Data::INotifyPropertyChanged - { - internal: - ProductItem( - Windows::ApplicationModel::Store::ListingInformation^ listing, - Windows::ApplicationModel::Store::LicenseInformation^ license, - Platform::String^ productId, - bool isApp - ); - - public: - virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged; - - property Platform::String^ Title - { - Platform::String^ get() - { - return m_title; - } - } - - property Platform::String^ Price - { - Platform::String^ get() - { - return m_formattedPrice; - } - } - - property Platform::String^ Status - { - Platform::String^ get() - { - return m_status; - } - } - - property int BuyVisibility - { - int get() - { - return static_cast(m_isAvailableForPurchase ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed); - } - } - - property Platform::String^ ProductId - { - Platform::String^ get() - { - return m_productId; - } - } - - property Platform::String^ Foreground - { - Platform::String^ get() - { - return m_foreground; - } - } - - [Windows::Foundation::Metadata::DefaultOverload] - void UpdateContent(Windows::ApplicationModel::Store::LicenseInformation^ license); - void UpdateContent(Windows::ApplicationModel::Store::ListingInformation^ listing); - - private: - void SetStatus(Windows::ApplicationModel::Store::LicenseInformation^ license); - - Platform::String^ m_title; - Platform::String^ m_formattedPrice; - Platform::String^ m_productId; - Platform::String^ m_status; - Platform::String^ m_foreground; - bool m_isApp; - bool m_isAppActive; - bool m_isAppTrial; - bool m_isProductActive; - bool m_isAvailableForPurchase; - }; -} diff --git a/DirectXSceneStore/ScenePanel.xaml b/DirectXSceneStore/ScenePanel.xaml deleted file mode 100644 index 1dc91b9..0000000 --- a/DirectXSceneStore/ScenePanel.xaml +++ /dev/null @@ -1,364 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/DirectXSceneStore/ScenePanel.xaml.cpp b/DirectXSceneStore/ScenePanel.xaml.cpp deleted file mode 100644 index f15281c..0000000 --- a/DirectXSceneStore/ScenePanel.xaml.cpp +++ /dev/null @@ -1,375 +0,0 @@ -// -// ScenePanel.xaml.cpp -// Implementation of the ScenePanel class -// - -#include "pch.h" -#include "ScenePanel.xaml.h" - -using namespace DirectXSceneStore; -using namespace Platform; -using namespace Windows::Foundation; -using namespace Windows::Foundation::Collections; -using namespace Windows::Graphics::Display; -using namespace Windows::UI::Core; -using namespace Windows::UI::Xaml; -using namespace Windows::UI::Xaml::Controls; -using namespace Windows::UI::Xaml::Controls::Primitives; -using namespace Windows::UI::Xaml::Data; -using namespace Windows::UI::Xaml::Input; -using namespace Windows::UI::Xaml::Media; -using namespace Windows::UI::Xaml::Navigation; -using namespace Concurrency; - -// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 - -ScenePanel::ScenePanel() -{ - InitializeComponent(); - - DXSwapChainPanel->CompositionScaleChanged += - ref new TypedEventHandler(this, &ScenePanel::OnCompositionScaleChanged); - - DXSwapChainPanel->SizeChanged += ref new Windows::UI::Xaml::SizeChangedEventHandler(this, &ScenePanel::OnSwapChainPanelSizeChanged); - - // At this point we have access to the device. - // We can create the device-dependent resources. - m_deviceResources = std::make_shared(); - m_deviceResources->SetSwapChainPanel(DXSwapChainPanel); - - m_main = std::unique_ptr(new GameMain(m_deviceResources, this)); - - m_main->StartRenderLoop(); -} - -void ScenePanel::OnSuspending() -{ - -} - -void ScenePanel::OnResuming() -{ - -} - -void ScenePanel::OnGameInfoOverlayTapped(Object^ /* sender */, TappedRoutedEventArgs^ /* args */) -{ - m_main->PressComplete(); -} - -//---------------- IGameUIControl methods-------------------- - -void ScenePanel::SetGameLoading() -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this]() - { - GameInfoOverlayTitle->Text = "Loading Resources"; - - Loading->Visibility = ::Visibility::Visible; - Stats->Visibility = ::Visibility::Collapsed; - LevelStart->Visibility = ::Visibility::Collapsed; - PauseData->Visibility = ::Visibility::Collapsed; - LoadingProgress->IsActive = true; - }) - ); -} - -void ScenePanel::SetGameStats( - int maxLevel, - int hitCount, - int shotCount - ) -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this, maxLevel, hitCount, shotCount]() - { - GameInfoOverlayTitle->Text = "Game Statistics"; - //m_possiblePurchaseUpgrade = true; - //OptionalTrialUpgrade(); - - Loading->Visibility = ::Visibility::Collapsed; - Stats->Visibility = ::Visibility::Visible; - LevelStart->Visibility = ::Visibility::Collapsed; - PauseData->Visibility = ::Visibility::Collapsed; - - static const int bufferLength = 20; - static char16 wsbuffer[bufferLength]; - - int length = swprintf_s(wsbuffer, bufferLength, L"%d", maxLevel); - LevelsCompleted->Text = ref new Platform::String(wsbuffer, length); - - length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount); - TotalPoints->Text = ref new Platform::String(wsbuffer, length); - - length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount); - TotalShots->Text = ref new Platform::String(wsbuffer, length); - - // High Score is not used for showing Game Statistics - HighScoreTitle->Visibility = ::Visibility::Collapsed; - HighScoreData->Visibility = ::Visibility::Collapsed; - }) - ); -} - -void ScenePanel::SetGameOver( - bool win, - int maxLevel, - int hitCount, - int shotCount, - int highScore - ) -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this, win, maxLevel, hitCount, shotCount, highScore]() - { - if (win) - { - GameInfoOverlayTitle->Text = "You Won!"; - //m_possiblePurchaseUpgrade = true; - //OptionalTrialUpgrade(); - } - else - { - GameInfoOverlayTitle->Text = "Game Over"; - //m_possiblePurchaseUpgrade = false; - //PurchaseUpgrade->Visibility = ::Visibility::Collapsed; - } - Loading->Visibility = ::Visibility::Collapsed; - Stats->Visibility = ::Visibility::Visible; - LevelStart->Visibility = ::Visibility::Collapsed; - PauseData->Visibility = ::Visibility::Collapsed; - - static const int bufferLength = 20; - static char16 wsbuffer[bufferLength]; - - int length = swprintf_s(wsbuffer, bufferLength, L"%d", maxLevel); - LevelsCompleted->Text = ref new Platform::String(wsbuffer, length); - - length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount); - TotalPoints->Text = ref new Platform::String(wsbuffer, length); - - length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount); - TotalShots->Text = ref new Platform::String(wsbuffer, length); - - // Show High Score - HighScoreTitle->Visibility = ::Visibility::Visible; - HighScoreData->Visibility = ::Visibility::Visible; - length = swprintf_s(wsbuffer, bufferLength, L"%d", highScore); - HighScore->Text = ref new Platform::String(wsbuffer, length); - }) - ); -} - -void ScenePanel::SetLevelStart( - int level, - Platform::String^ objective, - float timeLimit, - float bonusTime - ) -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this, level, objective, timeLimit, bonusTime]() - { - static const int bufferLength = 20; - static char16 wsbuffer[bufferLength]; - - int length = swprintf_s(wsbuffer, bufferLength, L"Level %d", level); - GameInfoOverlayTitle->Text = ref new Platform::String(wsbuffer, length); - - Loading->Visibility = ::Visibility::Collapsed; - Stats->Visibility = ::Visibility::Collapsed; - LevelStart->Visibility = ::Visibility::Visible; - PauseData->Visibility = ::Visibility::Collapsed; - - Objective->Text = objective; - - length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", timeLimit); - TimeLimit->Text = ref new Platform::String(wsbuffer, length); - - if (bonusTime > 0.0) - { - BonusTimeTitle->Visibility = ::Visibility::Visible; - BonusTimeData->Visibility = ::Visibility::Visible; - length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", bonusTime); - BonusTime->Text = ref new Platform::String(wsbuffer, length); - } - else - { - BonusTimeTitle->Visibility = ::Visibility::Collapsed; - BonusTimeData->Visibility = ::Visibility::Collapsed; - } - }) - ); -} - -void ScenePanel::SetPause(int level, int hitCount, int shotCount, float timeRemaining) -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this, level, hitCount, shotCount, timeRemaining]() - { - GameInfoOverlayTitle->Text = "Paused"; - Loading->Visibility = ::Visibility::Collapsed; - Stats->Visibility = ::Visibility::Collapsed; - LevelStart->Visibility = ::Visibility::Collapsed; - PauseData->Visibility = ::Visibility::Visible; - - static const int bufferLength = 20; - static char16 wsbuffer[bufferLength]; - - int length = swprintf_s(wsbuffer, bufferLength, L"%d", level); - PauseLevel->Text = ref new Platform::String(wsbuffer, length); - - length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount); - PauseHits->Text = ref new Platform::String(wsbuffer, length); - - length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount); - PauseShots->Text = ref new Platform::String(wsbuffer, length); - - length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", timeRemaining); - PauseTimeRemaining->Text = ref new Platform::String(wsbuffer, length); - }) - ); -} - -void ScenePanel::ShowTooSmall() -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this]() - { - VisualStateManager::GoToState(this, "TooSmallState", true); - }) - ); -} - -void ScenePanel::HideTooSmall() -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this]() - { - VisualStateManager::GoToState(this, "NotTooSmallState", true); - }) - ); -} - -void ScenePanel::HideGameInfoOverlay() -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this]() - { - VisualStateManager::GoToState(this, "NormalState", true); - - //StoreFlyout->IsOpen = false; - //StoreFlyout->Visibility = ::Visibility::Collapsed; - //GameAppBar->IsOpen = false; - //Play->Content = "Pause"; - //Play->Icon = ref new SymbolIcon(Symbol::Pause); - m_playActive = true; - }) - ); -} - -void ScenePanel::SetAction(GameInfoOverlayCommand action) -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this, action]() - { - // Enable only one of the four possible commands at the bottom of the - // Game Info Overlay. - - PlayAgain->Visibility = ::Visibility::Collapsed; - PleaseWait->Visibility = ::Visibility::Collapsed; - TapToContinue->Visibility = ::Visibility::Collapsed; - - switch (action) - { - case GameInfoOverlayCommand::PlayAgain: - PlayAgain->Visibility = ::Visibility::Visible; - break; - case GameInfoOverlayCommand::PleaseWait: - PleaseWait->Visibility = ::Visibility::Visible; - break; - case GameInfoOverlayCommand::TapToContinue: - TapToContinue->Visibility = ::Visibility::Visible; - break; - case GameInfoOverlayCommand::None: - break; - } - }) - ); -} - -void ScenePanel::ShowGameInfoOverlay() -{ - // This function may be called from a different thread. - // All XAML updates need to occur on the UI thread so dispatch to ensure this is true. - Dispatcher->RunAsync( - CoreDispatcherPriority::Normal, - ref new DispatchedHandler([this]() - { - VisualStateManager::GoToState(this, "GameInfoOverlayState", true); - //Play->Content = "Play"; - //Play->Icon = ref new SymbolIcon(Symbol::Play); - m_playActive = false; - }) - ); -} - -//-----------Buttons---------------------- - -void ScenePanel::OnChangeBackgroundButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */) -{ - m_main->CycleBackground(); -} - -void ScenePanel::OnCompositionScaleChanged(Windows::UI::Xaml::Controls::SwapChainPanel ^sender, Platform::Object ^args) -{ - critical_section::scoped_lock lock(m_main->GetCriticalSection()); - m_deviceResources->SetCompositionScale(sender->CompositionScaleX, sender->CompositionScaleY); - m_main->CreateWindowSizeDependentResources(); -} - -void ScenePanel::OnSwapChainPanelSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e) -{ - critical_section::scoped_lock lock(m_main->GetCriticalSection()); - m_deviceResources->SetLogicalSize(e->NewSize); - m_main->CreateWindowSizeDependentResources(); -} - -void ScenePanel::SetYawPitch(float yaw, float pitch) -{ - m_main->SetYawPitch(yaw, pitch); -} - -void ScenePanel::Fire() -{ - m_main->Fire(); -} \ No newline at end of file diff --git a/DirectXSceneStore/ScenePanel.xaml.h b/DirectXSceneStore/ScenePanel.xaml.h deleted file mode 100644 index 9ea2dfc..0000000 --- a/DirectXSceneStore/ScenePanel.xaml.h +++ /dev/null @@ -1,52 +0,0 @@ -// -// ScenePanel.xaml.h -// Declaration of the ScenePanel class -// - -#pragma once - -#include "ScenePanel.g.h" -#include "Common\DeviceResources.h" -#include "GameMain.h" -#include "ProductItem.h" - -namespace DirectXSceneStore -{ - [Windows::Foundation::Metadata::WebHostHidden] - public ref class ScenePanel sealed : IGameUIControl - { - public: - ScenePanel(); - - void OnSuspending(); - void OnResuming(); - - // Exposing control methods - void SetYawPitch(float yaw, float pitch); - void Fire(); - - // IGameUIControl methods. - virtual void SetAction(GameInfoOverlayCommand action); - virtual void SetGameLoading(); - virtual void SetGameStats(int maxLevel, int hitCount, int shotCount); - virtual void SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore); - virtual void SetLevelStart(int level, Platform::String^ objective, float timeLimit, float bonusTime); - virtual void SetPause(int level, int hitCount, int shotCount, float timeRemaining); - virtual void ShowTooSmall(); - virtual void HideTooSmall(); - virtual void HideGameInfoOverlay(); - virtual void ShowGameInfoOverlay(); - - private: - std::shared_ptr m_deviceResources; - std::unique_ptr m_main; - bool m_playActive; - - void OnGameInfoOverlayTapped(Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ args); - - void OnChangeBackgroundButtonClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args); - - void OnCompositionScaleChanged(Windows::UI::Xaml::Controls::SwapChainPanel ^sender, Platform::Object ^args); - void OnSwapChainPanelSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e); - }; -} diff --git a/DirectXSceneStore/Simple3DGame.cpp b/DirectXSceneStore/Simple3DGame.cpp deleted file mode 100644 index b1ec744..0000000 --- a/DirectXSceneStore/Simple3DGame.cpp +++ /dev/null @@ -1,1203 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#include "pch.h" -#include "GameRenderer.h" - -#include "GameContent\Level1.h" -//#include "Level2.h" -//#include "Level3.h" -//#include "Level4.h" -//#include "Level5.h" -//#include "Level6.h" -#include "GameContent\Animate.h" -#include "GameContent\Sphere.h" -#include "GameContent\Cylinder.h" -#include "GameContent\Face.h" -#include "GameContent\MediaReader.h" - -using namespace concurrency; -using namespace DirectX; -using namespace Microsoft::WRL; -using namespace Windows::ApplicationModel::Store; -using namespace Windows::Storage; -using namespace Windows::UI::Core; - -//---------------------------------------------------------------------- - -Simple3DGame::Simple3DGame(): - m_ammoCount(0), - m_ammoNext(0), - m_gameActive(false), - m_levelActive(false), - m_totalHits(0), - m_totalShots(0), - m_levelBonusTime(0.0), - m_levelTimeRemaining(0.0), - m_levelCount(0), - m_currentLevel(0), - m_activeBackground(0) -{ - m_topScore.totalHits = 0; - m_topScore.totalShots = 0; - m_topScore.levelCompleted = 0; -} - -//---------------------------------------------------------------------- - -void Simple3DGame::Initialize( - _In_ MoveLookController^ controller, - _In_ GameRenderer^ renderer - ) -{ - // This method is expected to be called as an asynchronous task. - // Care should be taken to not call rendering methods on the - // m_renderer as this would result in the D3D Context being - // used in multiple threads, which is not allowed. - - m_controller = controller; - m_renderer = renderer; - - m_audioController = ref new Audio; - m_audioController->CreateDeviceIndependentResources(); - - InitializeGameConfig(); - - m_ammo = std::vector(GameConstants::MaxAmmo); - m_objects = std::vector(); - m_renderObjects = std::vector(); - m_level = std::vector(); - - m_savedState = ref new PersistentState(); - m_savedState->Initialize(ApplicationData::Current->LocalSettings->Values, "Game"); - - m_timer = ref new GameTimer(); - - // Create a sphere primitive to represent the player. - // The sphere will be used to handle collisions and constrain the player in the world. - // It is not rendered so it is not added to the list of render objects. - // It is added to the object list so it will be included in intersection calculations. - m_player = ref new Sphere(XMFLOAT3(0.0f, 0.0f, 4.0f), 0.2f); - m_objects.push_back(m_player); - m_player->Active(true); - - m_camera = ref new Camera; - m_camera->SetProjParams(XM_PI / 2, 1.0f, 0.01f, 100.0f); - m_camera->SetViewParams( - m_player->Position(), // Eye point in world coordinates. - XMFLOAT3 (0.0f, 0.7f, 0.0f), // Look at point in world coordinates. - XMFLOAT3 (0.0f, 1.0f, 0.0f) // The Up vector for the camera. - ); - - m_controller->Pitch(m_camera->Pitch()); - m_controller->Yaw(m_camera->Yaw()); - - // Instantiate a set of primitives to represent the containing world. These objects - // maintain the geometry and material properties of the walls, floor and ceiling. - // The TargetId is used to identify the world objects so that the right geometry - // and textures can be associated with them later after those resources have - // been created. - GameObject^ world = ref new GameObject(); - world->TargetId(GameConstants::WorldFloorId); - world->Active(true); - m_renderObjects.push_back(world); - - world = ref new GameObject(); - world->TargetId(GameConstants::WorldCeilingId); - world->Active(true); - m_renderObjects.push_back(world); - - world = ref new GameObject(); - world->TargetId(GameConstants::WorldWallsId); - world->Active(true); - m_renderObjects.push_back(world); - - // Min and max Bound are defining the world space of the game. - // All camera motion and dynamics are confined to this space. - m_minBound = XMFLOAT3(-4.0f, -3.0f, -6.0f); - m_maxBound = XMFLOAT3(4.0f, 3.0f, 6.0f); - - // Instantiate the Cylinders for use in the various game levels. - // Each cylinder has a different initial position, radius and direction vector, - // but share a common set of material properties. - for (int a = 0; a < GameConstants::MaxCylinders; a++) - { - Cylinder^ cylinder; - switch (a) - { - case 0: - cylinder = ref new Cylinder(XMFLOAT3(-2.0f, -3.0f, 0.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f)); - break; - case 1: - cylinder = ref new Cylinder(XMFLOAT3(2.0f, -3.0f, 0.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f)); - break; - case 2: - cylinder = ref new Cylinder(XMFLOAT3(0.0f, -3.0f, -2.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f)); - break; - case 3: - cylinder = ref new Cylinder(XMFLOAT3(-1.5f, -3.0f, -4.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f)); - break; - case 4: - cylinder = ref new Cylinder(XMFLOAT3(1.5f, -3.0f, -4.0f), 0.50f, XMFLOAT3(0.0f, 6.0f, 0.0f)); - break; - } - cylinder->Active(true); - m_objects.push_back(cylinder); - m_renderObjects.push_back(cylinder); - } - - MediaReader^ mediaReader = ref new MediaReader; - auto targetHitSound = mediaReader->LoadMedia("DirectXSceneStore\\Assets\\hit.wav"); - - // Instantiate the targets for use in the game. - // Each target has a different initial position, size and orientation, - // but share a common set of material properties. - // The target is defined by a position and two vectors that define both - // the plane of the target in world space and the size of the parallelogram - // based on the lengths of the vectors. - // Each target is assigned a number for identification purposes. - // The Target ID number is 1 based. - // All targets have the same material properties. - for (int a = 1; a < GameConstants::MaxTargets; a++) - { - Face^ target; - switch (a) - { - case 1: - target = ref new Face(XMFLOAT3(-2.5f, -1.0f, -1.5f), XMFLOAT3(-1.5f, -1.0f, -2.0f), XMFLOAT3(-2.5f, 1.0f, -1.5f)); - break; - case 2: - target = ref new Face(XMFLOAT3(-1.0f, 1.0f, -3.0f), XMFLOAT3(0.0f, 1.0f, -3.0f), XMFLOAT3(-1.0f, 2.0f, -3.0f)); - break; - case 3: - target = ref new Face(XMFLOAT3(1.5f, 0.0f, -3.0f), XMFLOAT3(2.5f, 0.0f, -2.0f), XMFLOAT3(1.5f, 2.0f, -3.0f)); - break; - case 4: - target = ref new Face(XMFLOAT3(-2.5f, -1.0f, -5.5f), XMFLOAT3(-0.5f, -1.0f, -5.5f), XMFLOAT3(-2.5f, 1.0f, -5.5f)); - break; - case 5: - target = ref new Face(XMFLOAT3(0.5f, -2.0f, -5.0f), XMFLOAT3(1.5f, -2.0f, -5.0f), XMFLOAT3(0.5f, 0.0f, -5.0f)); - break; - case 6: - target = ref new Face(XMFLOAT3(1.5f, -2.0f, -5.5f), XMFLOAT3(2.5f, -2.0f, -5.0f), XMFLOAT3(1.5f, 0.0f, -5.5f)); - break; - case 7: - target = ref new Face(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.5f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.5f, 0.0f)); - break; - case 8: - target = ref new Face(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.5f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.5f, 0.0f)); - break; - case 9: - target = ref new Face(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.5f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.5f, 0.0f)); - break; - } - - target->Target(true); - target->TargetId(a); - target->Active(true); - target->HitSound(ref new SoundEffect()); - target->HitSound()->Initialize( - m_audioController->SoundEffectEngine(), - mediaReader->GetOutputWaveFormatEx(), - targetHitSound - ); - - m_objects.push_back(target); - m_renderObjects.push_back(target); - } - - // Instantiate a set of spheres to be used as ammunition for the game - // and set the material properties of the spheres. - auto ammoHitSound = mediaReader->LoadMedia("DirectXSceneStore\\Assets\\bounce.wav"); - - for (int a = 0; a < GameConstants::MaxAmmo; a++) - { - m_ammo[a] = ref new Sphere; - m_ammo[a]->Radius(GameConstants::AmmoRadius); - m_ammo[a]->HitSound(ref new SoundEffect()); - m_ammo[a]->HitSound()->Initialize( - m_audioController->SoundEffectEngine(), - mediaReader->GetOutputWaveFormatEx(), - ammoHitSound - ); - m_ammo[a]->Active(false); - m_renderObjects.push_back(m_ammo[a]); - } - - // Instantiate each of the game levels. The Level class contains methods - // that initialize the objects in the world for the given level and also - // define any motion paths for the objects in that level. - - m_level.push_back(ref new Level1); - /* m_level.push_back(ref new Level2); - if (!m_gameConfig.isTrial) - { - m_level.push_back(ref new Level3); - m_level.push_back(ref new Level4); - m_level.push_back(ref new Level5); - m_level.push_back(ref new Level6); - }*/ - m_levelCount = static_cast(m_level.size()); - - // Load the top score from disk if it exists. - LoadHighScore(); - - // Load the currentScore for saved state if it exists. - LoadState(); - - m_controller->Active(false); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::LoadGame() -{ - m_player->Position(XMFLOAT3 (0.0f, -1.0f, 4.0f)); - - m_camera->SetViewParams( - m_player->Position(), // Eye point in world coordinates. - XMFLOAT3 (0.0f, 0.7f, 0.0f), // Look at point in world coordinates. - XMFLOAT3 (0.0f, 1.0f, 0.0f) // The Up vector for the camera. - ); - - m_controller->Pitch(m_camera->Pitch()); - m_controller->Yaw(m_camera->Yaw()); - m_currentLevel = 0; - m_levelTimeRemaining = 0.0f; - m_levelBonusTime = m_levelTimeRemaining; - m_levelDuration = m_level[m_currentLevel]->TimeLimit() + m_levelBonusTime; - InitializeAmmo(); - m_totalHits = 0; - m_totalShots = 0; - m_gameActive = false; - m_levelActive = false; - m_timer->Reset(); -} - -//---------------------------------------------------------------------- - -task Simple3DGame::LoadLevelAsync() -{ - // Initialize the level and spin up the async loading of the rendering - // resources for the level. - // This will run in a separate thread, so for Direct3D 11, only Device - // methods are allowed. Any DeviceContext method calls need to be - // done in FinalizeLoadLevel. - - m_level[m_currentLevel]->Initialize(m_objects); - m_levelDuration = m_level[m_currentLevel]->TimeLimit() + m_levelBonusTime; - - return m_renderer->LoadLevelResourcesAsync(); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::FinalizeLoadLevel() -{ - // This method is called on the main thread, so Direct3D 11 DeviceContext - // method calls are allowable here. - - // Finalize the Level loading. - m_renderer->FinalizeLoadLevelResources(); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::StartLevel() -{ - m_timer->Reset(); - m_timer->Start(); - if (m_currentLevel == 0) - { - m_gameActive = true; - } - m_levelActive = true; - m_controller->Active(true); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::PauseGame() -{ - m_timer->Stop(); - SaveState(); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::ContinueGame() -{ - m_timer->Start(); - m_controller->Active(true); -} - -//---------------------------------------------------------------------- - -GameState Simple3DGame::RunGame() -{ - // This method is called to execute a single time interval for active game play. - // It returns the resulting state of game play after the interval has been executed. - - m_timer->Update(); - - m_levelTimeRemaining = m_levelDuration - m_timer->PlayingTime(); - - if (m_levelTimeRemaining <= 0.0f) - { - // Time expired, so the game is over. - m_levelTimeRemaining = 0.0f; - InitializeAmmo(); - m_timer->Reset(); - m_gameActive = false; - m_levelActive = false; - SaveState(); - - if (m_totalHits > m_topScore.totalHits) - { - // There is a new high score so save it. - m_topScore.totalHits = m_totalHits; - m_topScore.totalShots = m_totalShots; - m_topScore.levelCompleted = m_currentLevel; - - SaveHighScore(); - } - return GameState::TimeExpired; - } - else - { - // Time has not expired, so run one frame of game play. - m_player->Velocity(m_controller->Velocity()); - m_camera->LookDirection(m_controller->LookDirection()); - - UpdateDynamics(); - - // Update the Camera with the player position updates from the dynamics calculations. - m_camera->Eye(m_player->Position()); - m_camera->LookDirection(m_controller->LookDirection()); - - if (m_level[m_currentLevel]->Update(m_timer->PlayingTime(), m_timer->DeltaTime(), m_levelTimeRemaining, m_objects)) - { - // The level has been completed. - m_levelActive = false; - InitializeAmmo(); - - if (m_currentLevel < m_levelCount-1) - { - // More levels to go so increment the level number. - // Actual level loading will occur in the LoadLevelAsync / FinalizeLoadLevel - // methods. - m_timer->Reset(); - m_currentLevel++; - m_levelBonusTime = m_levelTimeRemaining; - SaveState(); - return GameState::LevelComplete; - } - else - { - // All levels have been completed. - m_timer->Reset(); - m_gameActive = false; - m_levelActive = false; - SaveState(); - - if (m_totalHits > m_topScore.totalHits) - { - // There is a new high score so save it. - m_topScore.totalHits = m_totalHits; - m_topScore.totalShots = m_totalShots; - m_topScore.levelCompleted = m_currentLevel; - - SaveHighScore(); - } - return GameState::GameComplete; - } - } - } - return GameState::Active; -} - -//---------------------------------------------------------------------- - -void Simple3DGame::OnSuspending() -{ - m_audioController->SuspendAudio(); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::OnResuming() -{ - m_audioController->ResumeAudio(); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::UpdateDynamics() -{ - float timeTotal = m_timer->PlayingTime(); - float timeFrame = m_timer->DeltaTime(); - bool fire = m_controller->IsFiring(); - -#pragma region Shoot Ammo - // Shoot ammo. - if (fire) - { - static float lastFired; // Timestamp of last ammo fired. - - if (timeTotal < lastFired) - { - // timeTotal is not guarenteed to be monotomically increasing because it is - // reset at each level. - lastFired = timeTotal - GameConstants::Physics::AutoFireDelay; - } - - if (timeTotal - lastFired >= GameConstants::Physics::AutoFireDelay) - { - // Get inverse view matrix. - XMMATRIX invView; - XMVECTOR det; - invView = XMMatrixInverse(&det, m_camera->View()); - - // Compute initial velocity in world space from camera space. - XMFLOAT4 initialVelocity(0.0f, 0.0f, 15.0f, 0.0f); - m_ammo[m_ammoNext]->Velocity(XMVector4Transform(XMLoadFloat4(&initialVelocity), invView)); - - // Set the initial position of the ammo to be fired. The position is offset from the player - // to avoid an initial collision with the player object. - XMFLOAT4 initialPosition(0.0f, -0.15f, m_player->Radius() + GameConstants::AmmoSize, 1.0f); - m_ammo[m_ammoNext]->Position(XMVector4Transform(XMLoadFloat4(&initialPosition), invView)); - - // Initially not laying on ground. - m_ammo[m_ammoNext]->OnGround(false); - m_ammo[m_ammoNext]->Active(true); - - // Set position in array of next Ammo to use. - // We will re-use ammo taking the least recently used once we have hit the - // MaxAmmo in use. - m_ammoNext = (m_ammoNext + 1) % GameConstants::MaxAmmo; - m_ammoCount = min(m_ammoCount + 1, GameConstants::MaxAmmo); - - lastFired = timeTotal; - m_totalShots++; - } - } -#pragma endregion - -#pragma region Animate Objects - // Walk the list of objects looking for any objects that have an animation associated with it. - // Update the position of the object based on evaluating the animation object with the current time. - // Once the current time (timeTotal) is past the end of the animation time remove - // the animation object since it is no longer needed. - for (uint32 i = 0; i < m_objects.size(); i++) - { - if (m_objects[i]->AnimatePosition()) - { - m_objects[i]->Position(m_objects[i]->AnimatePosition()->Evaluate(timeTotal)); - if (m_objects[i]->AnimatePosition()->IsFinished(timeTotal)) - { - m_objects[i]->AnimatePosition(nullptr); - } - } - } -#pragma endregion - - // If the elapsed time is too long, we slice up the time and handle physics over several - // smaller time steps to avoid missing collisions. - float timeLeft = timeFrame; - float elapsedFrameTime; - while (timeLeft > 0.0f) - { - elapsedFrameTime = min(timeLeft, GameConstants::Physics::FrameLength); - timeLeft -= elapsedFrameTime; - - // Update the player position. - m_player->Position(m_player->VectorPosition() + m_player->VectorVelocity() * elapsedFrameTime); - - // Do m_player / object intersections. - for (uint32 a = 0; a < m_objects.size(); a++) - { - if (m_objects[a]->Active() && m_objects[a] != m_player) - { - XMFLOAT3 contact; - XMFLOAT3 normal; - - if (m_objects[a]->IsTouching(m_player->Position(), m_player->Radius(), &contact, &normal)) - { - // Player is in contact with m_objects[a]. - XMVECTOR oneToTwo; - oneToTwo = -XMLoadFloat3(&normal); - - float impact = XMVectorGetX( - XMVector3Dot (oneToTwo, m_player->VectorVelocity()) - ); - // Make sure that the player is actually headed towards the object. At grazing angles there - // could appear to be an impact when the player is actually already hit and moving away. - if (impact > 0.0f) - { - // Compute the normal and tangential components of the player's velocity. - XMVECTOR velocityOneNormal = XMVector3Dot(oneToTwo, m_player->VectorVelocity()) * oneToTwo; - XMVECTOR velocityOneTangent = m_player->VectorVelocity() - velocityOneNormal; - - // Compute post-collision velocity. - m_player->Velocity(velocityOneTangent - velocityOneNormal); - - // Fix the positions so that the player is just touching the object. - float distanceToMove = m_player->Radius(); - m_player->Position(XMLoadFloat3(&contact) - (oneToTwo * distanceToMove)); - } - } - } - } - { - // Do collision detection of the player with the bounding world. - XMFLOAT3 position = m_player->Position(); - XMFLOAT3 velocity = m_player->Velocity(); - float radius = m_player->Radius(); - - // Check for player collisions with the walls floor or ceiling and adjust the position. - float limit = m_minBound.x + radius; - if (position.x < limit) - { - position.x = limit; - velocity.x = -velocity.x * GameConstants::Physics::GroundRestitution; - } - limit = m_maxBound.x - radius; - if (position.x > limit) - { - position.x = limit; - velocity.x = -velocity.x + GameConstants::Physics::GroundRestitution; - } - limit = m_minBound.y + radius; - if (position.y < limit) - { - position.y = limit; - velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution; - } - limit = m_maxBound.y - radius; - if (position.y > limit) - { - position.y = limit; - velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution; - } - limit = m_minBound.z + radius; - if (position.z < limit) - { - position.z = limit; - velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution; - } - limit = m_maxBound.z - radius; - if (position.z > limit) - { - position.z = limit; - velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution; - } - m_player->Position(position); - m_player->Velocity(velocity); - } - - // Animate the ammo. - if (m_ammoCount > 0) - { - // Check for collisions between ammo. -#pragma region inter-ammo collision detection - if (m_ammoCount > 1) - { - for (uint32 one = 0; one < m_ammoCount; one++) - { - for (uint32 two = (one + 1); two < m_ammoCount; two++) - { - // Check collision between instances One and Two. - // OneToTwo is the vector between the centers of the two ammo that are being checked. - XMVECTOR oneToTwo; - oneToTwo = m_ammo[two]->VectorPosition() - m_ammo[one]->VectorPosition(); - float distanceSquared; - distanceSquared = XMVectorGetX( - XMVector3LengthSq(oneToTwo) - ); - if (distanceSquared < (GameConstants::AmmoSize * GameConstants::AmmoSize)) - { - // The two ammo are intersecting. - oneToTwo = XMVector3Normalize(oneToTwo); - - // Check if the two instances are already moving away from each other. - // If so, skip collision. This can happen when a lot of instances are - // bunched up next to each other. - float impact; - impact = XMVectorGetX( - XMVector3Dot(oneToTwo, m_ammo[one]->VectorVelocity()) - - XMVector3Dot(oneToTwo, m_ammo[two]->VectorVelocity()) - ); - if (impact > 0.0f) - { - // Compute the normal and tangential components of one's velocity. - XMVECTOR velocityOne = (1 - GameConstants::Physics::BounceLost) * m_ammo[one]->VectorVelocity(); - XMVECTOR velocityOneNormal = XMVector3Dot(oneToTwo, velocityOne) * oneToTwo; - XMVECTOR velocityOneTangent = velocityOne - velocityOneNormal; - // Compute the normal and tangential components of two's velocity. - XMVECTOR velocityTwo = (1 - GameConstants::Physics::BounceLost) * m_ammo[two]->VectorVelocity(); - XMVECTOR velocityTwoNormal = XMVector3Dot(oneToTwo, velocityTwo) * oneToTwo; - XMVECTOR velocityTwoTangent = velocityTwo - velocityTwoNormal; - - // Compute the post-collision velocities. - m_ammo[one]->Velocity(velocityOneTangent - velocityOneNormal * (1 - GameConstants::Physics::BounceTransfer) + - velocityTwoNormal * GameConstants::Physics::BounceTransfer - ); - m_ammo[two]->Velocity(velocityTwoTangent - velocityTwoNormal * (1 - GameConstants::Physics::BounceTransfer) + - velocityOneNormal * GameConstants::Physics::BounceTransfer - ); - - // Fix the positions so that the two balls are exactly GameConstants::AmmoSize apart. - float distanceToMove = (GameConstants::AmmoSize - sqrtf(distanceSquared)) * 0.5f; - m_ammo[one]->Position(m_ammo[one]->VectorPosition() - (oneToTwo * distanceToMove)); - m_ammo[two]->Position(m_ammo[two]->VectorPosition() + (oneToTwo * distanceToMove)); - - // Flag the two instances so that they are not laying on ground. - m_ammo[one]->OnGround(false); - m_ammo[two]->OnGround(false); - - // Start playing the sounds for the impact between the two balls. - m_ammo[one]->PlaySound(impact, m_player->Position()); - m_ammo[two]->PlaySound(impact, m_player->Position()); - } - } - } - } - } -#pragma endregion - -#pragma region Ammo-Object intersections - // Check for intersections between the ammo and the other objects in the scene. - for (uint32 one = 0; one < m_ammoCount; one++) - { - if (m_objects.size() > 0) - { - if (!m_ammo[one]->OnGround()) - { - for (uint32 i = 0; i < m_objects.size(); i++) - { - if (m_objects[i]->Active()) - { - // The object is currently active in the scene. There may be objects in the list - // that are currently inactive, so those are skipped. - XMFLOAT3 contact; - XMFLOAT3 normal; - - if (m_objects[i]->IsTouching(m_ammo[one]->Position(), GameConstants::AmmoRadius, &contact, &normal)) - { - // Ball is in contact with Object. - XMVECTOR oneToTwo; - oneToTwo = -XMLoadFloat3(&normal); - - float impact; - impact = XMVectorGetX( - XMVector3Dot (oneToTwo, m_ammo[one]->VectorVelocity()) - ); - // Make sure that the ball is actually headed towards the object. At grazing angles there - // could appear to be an impact when the ball is actually already hit and moving away. - if (impact > 0.0f) - { - // Compute the normal and tangential components of the ammo's velocity. - XMVECTOR velocityOne = (1 - GameConstants::Physics::BounceLost) * m_ammo[one]->VectorVelocity(); - XMVECTOR velocityOneNormal = XMVector3Dot(oneToTwo, velocityOne) * oneToTwo; - XMVECTOR velocityOneTangent = velocityOne - velocityOneNormal; - - // Compute post-collision velocity of the ammo. - m_ammo[one]->Velocity(velocityOneTangent - velocityOneNormal * (1 - GameConstants::Physics::BounceTransfer)); - - // Fix the position so that the ball is exactly GameConstants::AmmoRadius from target. - float distanceToMove = GameConstants::AmmoSize; - m_ammo[one]->Position(XMLoadFloat3(&contact) - (oneToTwo * distanceToMove)); - - // Flag the Ammo as not laying on ground. - m_ammo[one]->OnGround(false); - - // Play the sound associated with the Ammo hitting something. - m_ammo[one]->PlaySound(impact, m_player->Position()); - - if (m_objects[i]->Target() && !m_objects[i]->Hit()) - { - // The object is a target and isn't currently hit, so mark it as hit and - // play the sound associated with the impact. - m_objects[i]->Hit(true); - m_objects[i]->HitTime(timeTotal); - m_totalHits++; - - m_objects[i]->PlaySound(impact, m_player->Position()); - } - } - } - } - } - } - } - } -#pragma endregion - -#pragma region Apply Gravity and world intersection - // Apply gravity and check for collision against enclosing volume. - for (uint32 i = 0; i < m_ammoCount; i++) - { - // Update the position and velocity of the ammo instance. - m_ammo[i]->Position(m_ammo[i]->VectorPosition() + m_ammo[i]->VectorVelocity() * elapsedFrameTime); - - XMFLOAT3 velocity = m_ammo[i]->Velocity(); - XMFLOAT3 position = m_ammo[i]->Position(); - - velocity.x -= velocity.x * 0.1f * elapsedFrameTime; - velocity.z -= velocity.z * 0.1f * elapsedFrameTime; - if (!m_ammo[i]->OnGround()) - { - // Apply gravity if the ammo instance is not already resting on the ground. - velocity.y -= GameConstants::Physics::Gravity * elapsedFrameTime; - } - - if (!m_ammo[i]->OnGround()) - { - float limit = m_minBound.y + GameConstants::AmmoRadius; - if (position.y < limit) - { - // The ammo instance hit the ground. - // Align the ammo instance to the ground, invert the Y component of the velocity and - // play the impact sound. The X and Z velocity components will be reduced - // because of friction. - position.y = limit; - m_ammo[i]->PlaySound(-velocity.y, m_player->Position()); - - velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution; - velocity.x *= GameConstants::Physics::Friction; - velocity.z *= GameConstants::Physics::Friction; - } - } - else - { - // The ammo instance is resting or rolling on ground. - // X and Z velocity components are reduced because of friction. - velocity.x *= GameConstants::Physics::Friction; - velocity.z *= GameConstants::Physics::Friction; - } - - float limit = m_maxBound.y - GameConstants::AmmoRadius; - if (position.y > limit) - { - // The ammo instance hit the ceiling. - // Align the ammo instance to the ceiling, invert the Y component of the velocity and - // play the impact sound. The X and Z velocity components will be reduced - // because of friction. - position.y = limit; - m_ammo[i]->PlaySound(-velocity.y, m_player->Position()); - - velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution; - velocity.x *= GameConstants::Physics::Friction; - velocity.z *= GameConstants::Physics::Friction; - } - - limit = m_minBound.y + GameConstants::AmmoRadius; - if ((GameConstants::Physics::Gravity * (position.y - limit) + 0.5f * velocity.y * velocity.y) < GameConstants::Physics::RestThreshold) - { - // The Y velocity component is below the resting threshold so flag the instance as - // laying on the ground and set the Y velocity component to zero. - position.y = limit; - velocity.y = 0.0f; - m_ammo[i]->OnGround(true); - } - - limit = m_minBound.z + GameConstants::AmmoRadius; - if (position.z < limit) - { - // The ammo instance hit the a wall in the min Z direction. - // Align the ammo instance to the wall, invert the Z component of the velocity and - // play the impact sound. - position.z = limit; - m_ammo[i]->PlaySound(-velocity.z, m_player->Position()); - velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution; - } - - limit = m_maxBound.z - GameConstants::AmmoRadius; - if (position.z > limit) - { - // The ammo instance hit the a wall in the max Z direction. - // Align the ammo instance to the wall, invert the Z component of the velocity and - // play the impact sound. - position.z = limit; - m_ammo[i]->PlaySound(-velocity.z, m_player->Position()); - velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution; - } - - limit = m_minBound.x + GameConstants::AmmoRadius; - if (position.x < limit) - { - // The ammo instance hit the a wall in the min X direction. - // Align the ammo instance to the wall, invert the X component of the velocity and - // play the impact sound. - position.x = limit; - m_ammo[i]->PlaySound(-velocity.x, m_player->Position()); - velocity.x = -velocity.x * GameConstants::Physics::GroundRestitution; - } - - limit = m_maxBound.x - GameConstants::AmmoRadius; - if (position.x > limit) - { - // The ammo instance hit the a wall in the max X direction. - // Align the ammo instance to the wall, invert the X component of the velocity and - // play the impact sound. - position.x = limit; - m_ammo[i]->PlaySound(-velocity.x, m_player->Position()); - velocity.x = -velocity.x * GameConstants::Physics::GroundRestitution; - } - - // Save the updated velocity and position for the ammo instance. - m_ammo[i]->Velocity(velocity); - m_ammo[i]->Position(position); - } - } - } -#pragma endregion -} - -//---------------------------------------------------------------------- - -void Simple3DGame::SaveState() -{ - // Save basic state of the game. - m_savedState->SaveBool(":GameActive", m_gameActive); - m_savedState->SaveBool(":LevelActive", m_levelActive); - m_savedState->SaveInt32(":LevelCompleted", m_currentLevel); - m_savedState->SaveInt32(":TotalShots", m_totalShots); - m_savedState->SaveInt32(":TotalHits", m_totalHits); - m_savedState->SaveSingle(":BonusRoundTime", m_levelBonusTime); - m_savedState->SaveXMFLOAT3(":PlayerPosition", m_player->Position()); - m_savedState->SaveXMFLOAT3(":PlayerLookDirection", m_controller->LookDirection()); - - if (m_levelActive) - { - // The game is currently in the middle of a level, so save the extended state of - // the game. - m_savedState->SaveSingle(":LevelDuration", m_levelDuration); - m_savedState->SaveSingle(":LevelPlayingTime", m_timer->PlayingTime()); - - m_savedState->SaveInt32(":AmmoCount", m_ammoCount); - m_savedState->SaveInt32(":AmmoNext", m_ammoNext); - - const int bufferLength = 16; - char16 str[bufferLength]; - - for (uint32 i = 0; i < m_ammoCount; i++) - { - int len = swprintf_s(str, bufferLength, L"%d", i); - Platform::String^ string = ref new Platform::String(str, len); - - m_savedState->SaveBool(Platform::String::Concat(":AmmoActive", string), m_ammo[i]->Active()); - m_savedState->SaveXMFLOAT3(Platform::String::Concat(":AmmoPosition", string), m_ammo[i]->Position()); - m_savedState->SaveXMFLOAT3(Platform::String::Concat(":AmmoVelocity", string), m_ammo[i]->Velocity()); - } - - m_savedState->SaveInt32(":ObjectCount", static_cast(m_objects.size())); - - for (uint32 i = 0; i < m_objects.size(); i++) - { - int len = swprintf_s(str, bufferLength, L"%d", i); - Platform::String^ string = ref new Platform::String(str, len); - - m_savedState->SaveBool(Platform::String::Concat(":ObjectActive", string), m_objects[i]->Active()); - m_savedState->SaveBool(Platform::String::Concat(":ObjectTarget", string), m_objects[i]->Target()); - m_savedState->SaveXMFLOAT3(Platform::String::Concat(":ObjectPosition", string), m_objects[i]->Position()); - } - - m_level[m_currentLevel]->SaveState(m_savedState); - } -} - -//---------------------------------------------------------------------- - -void Simple3DGame::LoadState() -{ - m_gameActive = m_savedState->LoadBool(":GameActive", m_gameActive); - m_levelActive = m_savedState->LoadBool(":LevelActive", m_levelActive); - - if (m_gameActive) - { - // Loading from the last known state means the game wasn't finished when it was last played, - // so set the current level. - - m_totalShots = m_savedState->LoadInt32(":TotalShots", 0); - m_totalHits = m_savedState->LoadInt32(":TotalHits", 0); - m_currentLevel = m_savedState->LoadInt32(":LevelCompleted", 0); - m_levelBonusTime = m_savedState->LoadSingle(":BonusRoundTime", 0.0f); - - m_levelTimeRemaining = m_levelBonusTime; - - // Reload the current player position and set both the camera and the controller - // with the current Look Direction. - m_player->Position( - m_savedState->LoadXMFLOAT3(":PlayerPosition", XMFLOAT3(0.0f, 0.0f, 0.0f)) - ); - m_camera->Eye(m_player->Position()); - m_camera->LookDirection( - m_savedState->LoadXMFLOAT3(":PlayerLookDirection", XMFLOAT3(0.0f, 0.0f, 1.0f)) - ); - m_controller->Pitch(m_camera->Pitch()); - m_controller->Yaw(m_camera->Yaw()); - } - else - { - // The game was not being played when it was last saved, so initialize to the beginning. - m_currentLevel = 0; - m_levelBonusTime = 0; - } - - if (m_currentLevel >= m_levelCount) - { - // The current level is not valid so, reset to a known state and abandon the current game. - m_currentLevel = 0; - m_levelBonusTime = 0; - m_gameActive = false; - m_levelActive = false; - } -} - -//---------------------------------------------------------------------- - -void Simple3DGame::SetCurrentLevelToSavedState() -{ - if (m_gameActive) - { - if (m_levelActive) - { - // Middle of a level so restart where left off. - m_levelDuration = m_savedState->LoadSingle(":LevelDuration", 0.0f); - - m_timer->Reset(); - m_timer->PlayingTime(m_savedState->LoadSingle(":LevelPlayingTime", 0.0f)); - - m_ammoCount = m_savedState->LoadInt32(":AmmoCount", 0); - - m_ammoNext = m_savedState->LoadInt32(":AmmoNext", 0); - - const int bufferLength = 16; - char16 str[bufferLength]; - - for (uint32 i = 0; i < m_ammoCount; i++) - { - int len = swprintf_s(str, bufferLength, L"%d", i); - Platform::String^ string = ref new Platform::String(str, len); - - m_ammo[i]->Active( - m_savedState->LoadBool( - Platform::String::Concat(":AmmoActive", string), - m_ammo[i]->Active() - ) - ); - if (m_ammo[i]->Active()) - { - m_ammo[i]->OnGround(false); - } - - m_ammo[i]->Position( - m_savedState->LoadXMFLOAT3( - Platform::String::Concat(":AmmoPosition", string), - m_ammo[i]->Position() - ) - ); - - m_ammo[i]->Velocity( - m_savedState->LoadXMFLOAT3( - Platform::String::Concat(":AmmoVelocity", string), - m_ammo[i]->Velocity() - ) - ); - } - - int storedObjectCount = 0; - storedObjectCount = m_savedState->LoadInt32(":ObjectCount", 0); - - storedObjectCount = min(storedObjectCount, static_cast(m_objects.size())); - - for (int i = 0; i < storedObjectCount; i++) - { - int len = swprintf_s(str, bufferLength, L"%d", i); - Platform::String^ string = ref new Platform::String(str, len); - - m_objects[i]->Active( - m_savedState->LoadBool( - Platform::String::Concat(":ObjectActive", string), - m_objects[i]->Active() - ) - ); - - m_objects[i]->Target( - m_savedState->LoadBool( - Platform::String::Concat(":ObjectTarget", string), - m_objects[i]->Target() - ) - ); - - m_objects[i]->Position( - m_savedState->LoadXMFLOAT3( - Platform::String::Concat(":ObjectPosition", string), - m_objects[i]->Position() - ) - ); - } - - m_level[m_currentLevel]->LoadState(m_savedState); - m_levelTimeRemaining = m_level[m_currentLevel]->TimeLimit() + m_levelBonusTime - m_timer->PlayingTime(); - } - } -} - -//---------------------------------------------------------------------- - -void Simple3DGame::SaveHighScore() -{ - m_savedState->SaveInt32(":HighScore:LevelCompleted", m_topScore.levelCompleted); - m_savedState->SaveInt32(":HighScore:TotalShots", m_topScore.totalShots); - m_savedState->SaveInt32(":HighScore:TotalHits", m_topScore.totalHits); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::LoadHighScore() -{ - m_topScore.levelCompleted = m_savedState->LoadInt32(":HighScore:LevelCompleted", 0); - m_topScore.totalShots = m_savedState->LoadInt32(":HighScore:TotalShots", 0); - m_topScore.totalHits = m_savedState->LoadInt32(":HighScore:TotalHits", 0); -} - -//---------------------------------------------------------------------- - -void Simple3DGame::InitializeAmmo() -{ - m_ammoCount = 0; - m_ammoNext = 0; - for (uint32 i = 0; i < GameConstants::MaxAmmo; i++) - { - m_ammo[i]->Active(false); - } -} - -//---------------------------------------------------------------------- - -void Simple3DGame::InitializeGameConfig() -{ - m_gameConfig.isTrial = true; - m_gameConfig.autoFire = false; - m_controller->AutoFire(false); - m_activeBackground = 0; - m_gameConfig.backgroundAvailable[0] = true; - for (int i = 1; i < GameConstants::MaxBackgroundTextures; i++) - { - m_gameConfig.backgroundAvailable[i] = false; - } -} - -//-------------------------------------------------------------------------------------- - -void Simple3DGame::UpdateGameConfig(LicenseInformation^ licenseInformation) -{ - if (licenseInformation->IsActive) - { - m_gameConfig.isTrial = licenseInformation->IsTrial; - if (!m_gameConfig.isTrial && licenseInformation->ProductLicenses->Lookup("AutoFire")->IsActive) - { - m_gameConfig.autoFire = true; - m_controller->AutoFire(true); - } - else - { - m_gameConfig.autoFire = false; - m_controller->AutoFire(false); - } - if (!m_gameConfig.isTrial && licenseInformation->ProductLicenses->Lookup("NightBackground")->IsActive) - { - m_gameConfig.backgroundAvailable[1] = true; - } - else - { - m_gameConfig.backgroundAvailable[1] = false; - } - if (!m_gameConfig.isTrial && licenseInformation->ProductLicenses->Lookup("DayBackground")->IsActive) - { - m_gameConfig.backgroundAvailable[2] = true; - } - else - { - m_gameConfig.backgroundAvailable[2] = false; - } - } - else - { - // If no active license then default back to trial version. - InitializeGameConfig(); - } - - if (m_gameConfig.isTrial) - { - if (m_level.size() > 2) - { - m_level.erase(m_level.begin() + 2, m_level.end()); - } - } - else - { - if (m_level.size() == 2) - { - //m_level.push_back(ref new Level3); - //m_level.push_back(ref new Level4); - //m_level.push_back(ref new Level5); - //m_level.push_back(ref new Level6); - } - } - m_levelCount = static_cast(m_level.size()); -} - -//-------------------------------------------------------------------------------------- - -void Simple3DGame::SetBackground(uint32 background) -{ - if (background < GameConstants::MaxBackgroundTextures) - { - if (m_gameConfig.backgroundAvailable[background]) - { - m_activeBackground = background; - m_renderer->SetBackground(background); - } - } -} - -//-------------------------------------------------------------------------------------- - -void Simple3DGame::CycleBackground() -{ - // There may be gaps in the background textures list that are available for use because the - // user has not purchased all them in order or at all. - // Cycle through the list looking for the next one that is valid. This may require wrapping - // back to the beginning. - - unsigned int newBackground = m_activeBackground; - - while (newBackground < GameConstants::MaxBackgroundTextures) - { - newBackground++; - if (newBackground >= GameConstants::MaxBackgroundTextures) - { - newBackground = 0; - break; - } - else if (m_gameConfig.backgroundAvailable[newBackground]) - { - break; - } - } - - if (newBackground != m_activeBackground) - { - m_activeBackground = newBackground; - m_renderer->SetBackground(newBackground); - } -} -//-------------------------------------------------------------------------------------- - diff --git a/DirectXSceneStore/Simple3DGame.h b/DirectXSceneStore/Simple3DGame.h deleted file mode 100644 index c03e415..0000000 --- a/DirectXSceneStore/Simple3DGame.h +++ /dev/null @@ -1,157 +0,0 @@ -//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -//// PARTICULAR PURPOSE. -//// -//// Copyright (c) Microsoft Corporation. All rights reserved - -#pragma once - -// Simple3DGame: -// This is the main game class. It controls game play logic and game state. -// Some of the key object classes used by Simple3DGame are: -// MoveLookController - for handling all input to control player movement, aiming, -// and firing. -// GameRenderer - for handling all graphics presentation. -// Camera - for handling view projections. -// Audio - for handling sound output. -// This class maintains several lists of objects: -// m_ammo - is the list of the balls used to throw at targets. Simple3DGame -// cycles through the list in a LRU fashion each time a ball is thrown by the player. -// m_objects - is the list of all objects in the scene that participate in -// game physics. This includes m_player to represent the player in the scene. -// The player object (m_player) is not visible in the scene so it is not rendered. -// m_renderObjects - is the list of all objects in the scene that may be -// rendered. It includes both the m_ammo list, most of the m_objects list excluding m_player -// object and the objects representing the bounding world. - -#include "GameContent\GameConstants.h" -#include "GameUIConstants.h" -#include "GameContent\Audio.h" -#include "GameContent\Camera.h" -#include "GameContent\Level.h" -#include "GameContent\GameObject.h" -#include "GameContent\GameTimer.h" -#include "GameContent\MoveLookController.h" -#include "Common\PersistentState.h" -#include "GameContent\Sphere.h" -#include "GameRenderer.h" - -//-------------------------------------------------------------------------------------- - -enum class GameState -{ - Waiting, - Active, - LevelComplete, - TimeExpired, - GameComplete, -}; - -typedef struct -{ - Platform::String^ tag; - int totalHits; - int totalShots; - int levelCompleted; -} HighScoreEntry; - -typedef std::vector HighScoreEntries; - -typedef struct -{ - bool isTrial; - bool autoFire; - bool backgroundAvailable[GameConstants::MaxBackgroundTextures]; -} GameConfig; - -//-------------------------------------------------------------------------------------- - -ref class GameRenderer; - -ref class Simple3DGame -{ -internal: - Simple3DGame(); - - void Initialize( - _In_ MoveLookController^ controller, - _In_ GameRenderer^ renderer - ); - - void LoadGame(); - concurrency::task LoadLevelAsync(); - void FinalizeLoadLevel(); - void StartLevel(); - void PauseGame(); - void ContinueGame(); - GameState RunGame(); - void SetCurrentLevelToSavedState(); - - void OnSuspending(); - void OnResuming(); - - bool IsActivePlay() { return m_timer->Active(); } - bool IsTrial() { return m_gameConfig.isTrial; } - int LevelCompleted() { return m_currentLevel; }; - int TotalShots() { return m_totalShots; }; - int TotalHits() { return m_totalHits; }; - float BonusTime() { return m_levelBonusTime; }; - bool GameActive() { return m_gameActive; }; - bool LevelActive() { return m_levelActive; }; - HighScoreEntry HighScore() { return m_topScore; }; - Level^ CurrentLevel() { return m_level[m_currentLevel]; }; - float TimeRemaining() { return m_levelTimeRemaining; }; - Camera^ GameCamera() { return m_camera; }; - std::vector RenderObjects() { return m_renderObjects; }; - - void UpdateGameConfig(Windows::ApplicationModel::Store::LicenseInformation^ licenseInformation); - void SetBackground(uint32 background); - void CycleBackground(); - - -private: - void LoadState(); - void SaveState(); - void SaveHighScore(); - void LoadHighScore(); - void InitializeAmmo(); - void UpdateDynamics(); - void InitializeGameConfig(); - - MoveLookController^ m_controller; - GameRenderer^ m_renderer; - Camera^ m_camera; - - Audio^ m_audioController; - - std::vector m_ammo; - uint32 m_ammoCount; - uint32 m_ammoNext; - - HighScoreEntry m_topScore; - PersistentState^ m_savedState; - - GameTimer^ m_timer; - bool m_gameActive; - bool m_levelActive; - int m_totalHits; - int m_totalShots; - float m_levelDuration; - float m_levelBonusTime; - float m_levelTimeRemaining; - std::vector m_level; - uint32 m_levelCount; - uint32 m_currentLevel; - - GameConfig m_gameConfig; - uint32 m_activeBackground; - - Sphere^ m_player; - std::vector m_objects; // List of all objects to be included in intersection calculations. - std::vector m_renderObjects; // List of all objects to be rendered. - - DirectX::XMFLOAT3 m_minBound; - DirectX::XMFLOAT3 m_maxBound; -}; - diff --git a/DirectXSceneStore/pch.cpp b/DirectXSceneStore/pch.cpp deleted file mode 100644 index 01484ff..0000000 --- a/DirectXSceneStore/pch.cpp +++ /dev/null @@ -1,6 +0,0 @@ -// -// pch.cpp -// Include the standard header and generate the precompiled header. -// - -#include "pch.h" diff --git a/DirectXSceneStore/pch.h b/DirectXSceneStore/pch.h deleted file mode 100644 index 59c9f1e..0000000 --- a/DirectXSceneStore/pch.h +++ /dev/null @@ -1,33 +0,0 @@ -// -// pch.h -// Header for standard system include files. -// - -#pragma once - - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include \ No newline at end of file diff --git a/FinalLibraryZips/DirectXSceneStore.zip b/FinalLibraryZips/DirectXSceneStore.zip deleted file mode 100644 index 43cb41d..0000000 Binary files a/FinalLibraryZips/DirectXSceneStore.zip and /dev/null differ diff --git a/FinalLibraryZips/KinectFaceStore.zip b/FinalLibraryZips/KinectFaceStore.zip deleted file mode 100644 index ea01784..0000000 Binary files a/FinalLibraryZips/KinectFaceStore.zip and /dev/null differ diff --git a/Kinect2Sample.Lab1/Kinect2Sample.sln b/Kinect2Sample.Lab1/Kinect2Sample.sln deleted file mode 100644 index 887b8ec..0000000 --- a/Kinect2Sample.Lab1/Kinect2Sample.sln +++ /dev/null @@ -1,32 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kinect2Sample", "Kinect2Sample\Kinect2Sample.csproj", "{10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Build.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Deploy.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.ActiveCfg = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Build.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Deploy.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.ActiveCfg = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Build.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Deploy.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.ActiveCfg = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Build.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Deploy.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Kinect2Sample.Lab1/Kinect2Sample/App.xaml b/Kinect2Sample.Lab1/Kinect2Sample/App.xaml deleted file mode 100644 index b34ea9d..0000000 --- a/Kinect2Sample.Lab1/Kinect2Sample/App.xaml +++ /dev/null @@ -1,7 +0,0 @@ - - - diff --git a/Kinect2Sample.Lab1/Kinect2Sample/App.xaml.cs b/Kinect2Sample.Lab1/Kinect2Sample/App.xaml.cs deleted file mode 100644 index 1692c86..0000000 --- a/Kinect2Sample.Lab1/Kinect2Sample/App.xaml.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 - -namespace Kinect2Sample -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = true; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - // Set the default language - rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Kinect2Sample.Lab1/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample.Lab1/Kinect2Sample/Kinect2Sample.csproj deleted file mode 100644 index 926ec2f..0000000 --- a/Kinect2Sample.Lab1/Kinect2Sample/Kinect2Sample.csproj +++ /dev/null @@ -1,115 +0,0 @@ - - - - - Debug - AnyCPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F} - AppContainerExe - Properties - Kinect2Sample - Kinect2Sample - en-US - 8.1 - 12 - 512 - {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Kinect2Sample_TemporaryKey.pfx - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x64 - false - prompt - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x64 - false - prompt - true - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x86 - false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x86 - false - prompt - true - - - - App.xaml - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - Microsoft Visual C++ 2013 Runtime Package for Windows - - - WindowsPreview.Kinect - - - - - - - 12.0 - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab1/Kinect2Sample/MainPage.xaml b/Kinect2Sample.Lab1/Kinect2Sample/MainPage.xaml deleted file mode 100644 index 8cd1547..0000000 --- a/Kinect2Sample.Lab1/Kinect2Sample/MainPage.xaml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - diff --git a/Kinect2Sample.Lab1/Kinect2Sample/MainPage.xaml.cs b/Kinect2Sample.Lab1/Kinect2Sample/MainPage.xaml.cs deleted file mode 100644 index d501b81..0000000 --- a/Kinect2Sample.Lab1/Kinect2Sample/MainPage.xaml.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - - public sealed partial class MainPage : Page - { - - private KinectSensor kinectSensor = null; - - public MainPage() - { - // one sensor is currently supported - this.kinectSensor = KinectSensor.GetDefault(); - - // open the sensor - this.kinectSensor.Open(); - - this.InitializeComponent(); - } - } -} diff --git a/Kinect2Sample.Lab1/Kinect2Sample/Package.appxmanifest b/Kinect2Sample.Lab1/Kinect2Sample/Package.appxmanifest deleted file mode 100644 index 297bc48..0000000 --- a/Kinect2Sample.Lab1/Kinect2Sample/Package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Kinect2Sample - Jesse - Assets\StoreLogo.png - - - 6.3.0 - 6.3.0 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample.Lab10/Kinect2Sample/Kinect2Sample.csproj deleted file mode 100644 index 913ba8e..0000000 --- a/Kinect2Sample.Lab10/Kinect2Sample/Kinect2Sample.csproj +++ /dev/null @@ -1,123 +0,0 @@ - - - - - Debug - AnyCPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F} - AppContainerExe - Properties - Kinect2Sample - Kinect2Sample - en-US - 8.1 - 12 - 512 - {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Kinect2Sample_TemporaryKey.pfx - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x64 - false - prompt - true - true - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x64 - false - prompt - true - - - - App.xaml - - - - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - Microsoft.Kinect.Face - - - Microsoft.Kinect.Toolkit.Input - - - Microsoft.Kinect.Xaml.Controls - - - Microsoft Visual C++ 2013 Runtime Package for Windows - - - WindowsPreview.Kinect - - - - - - - - Libraries\x64\DirectXSceneStore.winmd - - - Libraries\x64\KinectFaceStore.dll - - - - 12.0 - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx b/Kinect2Sample.Lab10/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx deleted file mode 100644 index 7cb3591..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/bounce.wav b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/bounce.wav deleted file mode 100644 index 8267695..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/bounce.wav and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellceiling.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellceiling.dds deleted file mode 100644 index dd24b59..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellceiling.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellfloor.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellfloor.dds deleted file mode 100644 index 790df24..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellfloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellwall.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellwall.dds deleted file mode 100644 index 7bfc4af..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellwall.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayceiling.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayceiling.dds deleted file mode 100644 index 6148ae3..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayceiling.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayfloor.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayfloor.dds deleted file mode 100644 index 22f11fa..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayfloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/daywall.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/daywall.dds deleted file mode 100644 index 6148ae3..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/daywall.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/hit.wav b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/hit.wav deleted file mode 100644 index f4a78ac..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/hit.wav and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/mediumTile-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/mediumTile-sdk.png deleted file mode 100644 index 1c9f68e..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/mediumTile-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/metal_texture.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/metal_texture.dds deleted file mode 100644 index af2e355..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/metal_texture.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightceiling.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightceiling.dds deleted file mode 100644 index 291a923..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightceiling.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightfloor.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightfloor.dds deleted file mode 100644 index 04e424b..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightfloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightwall.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightwall.dds deleted file mode 100644 index 291a923..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightwall.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/seafloor.dds b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/seafloor.dds deleted file mode 100644 index 3c8eed9..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/seafloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-phone-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-phone-sdk.png deleted file mode 100644 index 4476cda..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-phone-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-windows-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-windows-sdk.png deleted file mode 100644 index e39b01f..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-phone-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-phone-sdk.png deleted file mode 100644 index 435f872..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-phone-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-windows-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-windows-sdk.png deleted file mode 100644 index e00df02..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/squareTile-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/squareTile-sdk.png deleted file mode 100644 index 2a8cf87..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/squareTile-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/storeLogo-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/storeLogo-sdk.png deleted file mode 100644 index 5c397de..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/storeLogo-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/tile-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/tile-sdk.png deleted file mode 100644 index f72683f..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/tile-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/windows-sdk.png b/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/windows-sdk.png deleted file mode 100644 index 6726802..0000000 Binary files a/Kinect2Sample.Lab10/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab10/Kinect2Sample/MainPage.xaml b/Kinect2Sample.Lab10/Kinect2Sample/MainPage.xaml deleted file mode 100644 index 3379e32..0000000 --- a/Kinect2Sample.Lab10/Kinect2Sample/MainPage.xaml +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Kinect2Sample.Lab5/Kinect2Sample/MainPage.xaml.cs b/Kinect2Sample.Lab5/Kinect2Sample/MainPage.xaml.cs deleted file mode 100644 index bf55f1d..0000000 --- a/Kinect2Sample.Lab5/Kinect2Sample/MainPage.xaml.cs +++ /dev/null @@ -1,540 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Media.Imaging; -using Windows.UI.Xaml.Navigation; -using WindowsPreview.Kinect; -using System.ComponentModel; -using Windows.Storage.Streams; -using System.Runtime.InteropServices; -using System.Diagnostics; - -namespace Kinect2Sample -{ - public enum DisplayFrameType - { - Infrared, - Color, - Depth, - BodyMask - } - - public sealed partial class MainPage : Page, INotifyPropertyChanged - { - private const DisplayFrameType DEFAULT_DISPLAYFRAMETYPE = DisplayFrameType.Infrared; - - /// - /// The highest value that can be returned in the InfraredFrame. - /// It is cast to a float for readability in the visualization code. - /// - private const float InfraredSourceValueMaximum = (float)ushort.MaxValue; - - /// - /// Used to set the lower limit, post processing, of the - /// infrared data that we will render. - /// Increasing or decreasing this value sets a brightness - /// "wall" either closer or further away. - /// - private const float InfraredOutputValueMinimum = 0.01f; - - /// - /// The upper limit, post processing, of the - /// infrared data that will render. - /// - private const float InfraredOutputValueMaximum = 1.0f; - - /// - /// The InfraredSceneValueAverage value specifies the average infrared - /// value of the scene. This value was selected by analyzing the average - /// pixel intensity for a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneValueAverage = 0.08f; - - /// - /// The InfraredSceneStandardDeviations value specifies the number of - /// standard deviations to apply to InfraredSceneValueAverage. - /// This value was selected by analyzing data from a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneStandardDeviations = 3.0f; - - // Size of the RGB pixel in the bitmap - private const int BytesPerPixel = 4; - - private KinectSensor kinectSensor = null; - private string statusText = null; - private WriteableBitmap bitmap = null; - private FrameDescription currentFrameDescription; - private DisplayFrameType currentDisplayFrameType; - private MultiSourceFrameReader multiSourceFrameReader = null; - private CoordinateMapper coordinateMapper = null; - - //Infrared Frame - private ushort[] infraredFrameData = null; - private byte[] infraredPixels = null; - - //Depth Frame - private ushort[] depthFrameData = null; - private byte[] depthPixels = null; - - //BodyMask Frames - private DepthSpacePoint[] colorMappedToDepthPoints = null; - - public event PropertyChangedEventHandler PropertyChanged; - public string StatusText - { - get { return this.statusText; } - set - { - if (this.statusText != value) - { - this.statusText = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); - } - } - } - } - - public FrameDescription CurrentFrameDescription - { - get { return this.currentFrameDescription; } - set - { - if (this.currentFrameDescription != value) - { - this.currentFrameDescription = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentFrameDescription")); - } - } - } - } - - public MainPage() - { - // one sensor is currently supported - this.kinectSensor = KinectSensor.GetDefault(); - - SetupCurrentDisplay(DEFAULT_DISPLAYFRAMETYPE); - - this.coordinateMapper = this.kinectSensor.CoordinateMapper; - - this.multiSourceFrameReader = this.kinectSensor.OpenMultiSourceFrameReader(FrameSourceTypes.Infrared | FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.BodyIndex); - - this.multiSourceFrameReader.MultiSourceFrameArrived += this.Reader_MultiSourceFrameArrived; - - // set IsAvailableChanged event notifier - this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; - - // use the window object as the view model in this simple example - this.DataContext = this; - - // open the sensor - this.kinectSensor.Open(); - - this.InitializeComponent(); - } - - private void SetupCurrentDisplay(DisplayFrameType newDisplayFrameType) - { - currentDisplayFrameType = newDisplayFrameType; - // Frames used by more than one type are declared outside the switch - FrameDescription colorFrameDescription = null; - switch (currentDisplayFrameType) - { - case DisplayFrameType.Infrared: - FrameDescription infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription; - this.CurrentFrameDescription = infraredFrameDescription; - // allocate space to put the pixels being received and converted - this.infraredFrameData = new ushort[infraredFrameDescription.Width * infraredFrameDescription.Height]; - this.infraredPixels = new byte[infraredFrameDescription.Width * infraredFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(infraredFrameDescription.Width, infraredFrameDescription.Height); - break; - - case DisplayFrameType.Color: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // create the bitmap to display - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.Depth: - FrameDescription depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - this.CurrentFrameDescription = depthFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.depthPixels = new byte[depthFrameDescription.Width * depthFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(depthFrameDescription.Width, depthFrameDescription.Height); - break; - - case DisplayFrameType.BodyMask: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - default: - break; - } - } - - private void Sensor_IsAvailableChanged(KinectSensor sender, IsAvailableChangedEventArgs args) - { - this.StatusText = this.kinectSensor.IsAvailable ? "Running" : "Not Available"; - } - - private void Reader_MultiSourceFrameArrived(MultiSourceFrameReader sender, MultiSourceFrameArrivedEventArgs e) - { - - MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame(); - - // If the Frame has expired by the time we process this event, return. - if (multiSourceFrame == null) - { - return; - } - DepthFrame depthFrame = null; - ColorFrame colorFrame = null; - InfraredFrame infraredFrame = null; - BodyIndexFrame bodyIndexFrame = null; - //windows.storage.streams - IBuffer depthFrameData = null; - IBuffer bodyIndexFrameData = null; - // Com interface for unsafe byte manipulation - IBufferByteAccess bodyIndexByteAccess = null; - - switch (currentDisplayFrameType) - { - case DisplayFrameType.Infrared: - using (infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame()) - { - ShowInfraredFrame(infraredFrame); - } - break; - case DisplayFrameType.Color: - using (colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame()) - { - ShowColorFrame(colorFrame); - } - break; - case DisplayFrameType.Depth: - using (depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame()) - { - ShowDepthFrame(depthFrame); - } - break; - case DisplayFrameType.BodyMask: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - bodyIndexFrame = multiSourceFrame.BodyIndexFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null) || (bodyIndexFrame == null)) - { - return; - } - - // Access the depth frame data directly via LockImageBuffer to avoid making a copy - depthFrameData = depthFrame.LockImageBuffer(); - this.coordinateMapper.MapColorFrameToDepthSpaceUsingIBuffer(depthFrameData, this.colorMappedToDepthPoints); - // Process Color - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - // Access the body index frame data directly via LockImageBuffer to avoid making a copy - bodyIndexFrameData = bodyIndexFrame.LockImageBuffer(); - ShowMappedBodyFrame(depthFrame.FrameDescription.Width, depthFrame.FrameDescription.Height, bodyIndexFrameData, bodyIndexByteAccess); - - } - finally - { - // ... disposing of depth, color and bodyIndex frames - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - if (bodyIndexFrame != null) - { - bodyIndexFrame.Dispose(); - } - - if (depthFrameData != null) - { - // We must force a release of the IBuffer in order to ensure that we have dropped all references to it. - System.Runtime.InteropServices.Marshal.ReleaseComObject(depthFrameData); - } - if (bodyIndexFrameData != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bodyIndexFrameData); - } - if (bodyIndexByteAccess != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bodyIndexByteAccess); - } - - } - break; - - default: - break; - } - } - - unsafe private void ShowMappedBodyFrame(int depthWidth, int depthHeight, IBuffer bodyIndexFrameData, IBufferByteAccess bodyIndexByteAccess) - { - bodyIndexByteAccess = (IBufferByteAccess)bodyIndexFrameData; - byte* bodyIndexBytes = null; - bodyIndexByteAccess.Buffer(out bodyIndexBytes); - - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = this.colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - int colorMappedLength = this.colorMappedToDepthPoints.Length; - for (int colorIndex = 0; colorIndex < colorMappedLength; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPointsPointer[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPointsPointer[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - // If we are tracking a body for the current pixel, do not zero out the pixel - if (bodyIndexBytes[depthIndex] != 0xff) - { - // this bodyIndexByte is good and is a body, loop again. - continue; - } - } - } - // this pixel does not correspond to a body so make it black and transparent - bitmapPixelsPointer[colorIndex] = 0; - } - } - - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - - private void ShowDepthFrame(DepthFrame depthFrame) - { - bool depthFrameProcessed = false; - ushort minDepth = 0; - ushort maxDepth = 0; - - if (depthFrame != null) - { - FrameDescription depthFrameDescription = depthFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((depthFrameDescription.Width * depthFrameDescription.Height) - == this.infraredFrameData.Length) && - (depthFrameDescription.Width == this.bitmap.PixelWidth) && - (depthFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - depthFrame.CopyFrameDataToArray(this.depthFrameData); - - minDepth = depthFrame.DepthMinReliableDistance; - maxDepth = depthFrame.DepthMaxReliableDistance; - //maxDepth = 8000; - - depthFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (depthFrameProcessed) - { - ConvertDepthDataToPixels(minDepth, maxDepth); - RenderPixelArray(this.depthPixels); - } - } - - private void ConvertDepthDataToPixels(ushort minDepth, ushort maxDepth) - { - int colorPixelIndex = 0; - // Shape the depth to the range of a byte - int mapDepthToByte = maxDepth / 256; - - for (int i = 0; i < this.depthFrameData.Length; ++i) - { - // Get the depth for this pixel - ushort depth = this.depthFrameData[i]; - - // To convert to a byte, we're mapping the depth value to the byte range. - // Values outside the reliable depth range are mapped to 0 (black). - byte intensity = (byte)(depth >= minDepth && - depth <= maxDepth ? (depth / mapDepthToByte) : 0); - - this.depthPixels[colorPixelIndex++] = intensity; //Blue - this.depthPixels[colorPixelIndex++] = intensity; //Green - this.depthPixels[colorPixelIndex++] = intensity; //Red - this.depthPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void ShowColorFrame(ColorFrame colorFrame) - { - bool colorFrameProcessed = false; - - if (colorFrame != null) - { - FrameDescription colorFrameDescription = colorFrame.FrameDescription; - - // verify data and write the new color frame data to the Writeable bitmap - if ((colorFrameDescription.Width == this.bitmap.PixelWidth) && (colorFrameDescription.Height == this.bitmap.PixelHeight)) - { - if (colorFrame.RawColorImageFormat == ColorImageFormat.Bgra) - { - colorFrame.CopyRawFrameDataToBuffer(this.bitmap.PixelBuffer); - } - else - { - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - } - - colorFrameProcessed = true; - } - } - - if (colorFrameProcessed) - { - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - } - - private void ShowInfraredFrame(InfraredFrame infraredFrame) - { - bool infraredFrameProcessed = false; - - if (infraredFrame != null) - { - FrameDescription infraredFrameDescription = infraredFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((infraredFrameDescription.Width * infraredFrameDescription.Height) - == this.infraredFrameData.Length) && - (infraredFrameDescription.Width == this.bitmap.PixelWidth) && - (infraredFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - infraredFrame.CopyFrameDataToArray(this.infraredFrameData); - - infraredFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (infraredFrameProcessed) - { - this.ConvertInfraredDataToPixels(); - this.RenderPixelArray(this.infraredPixels); - } - } - - private void ConvertInfraredDataToPixels() - { - // Convert the infrared to RGB - int colorPixelIndex = 0; - for (int i = 0; i < this.infraredFrameData.Length; ++i) - { - // normalize the incoming infrared data (ushort) to a float ranging from - // [InfraredOutputValueMinimum, InfraredOutputValueMaximum] by - // 1. dividing the incoming value by the source maximum value - float intensityRatio = (float)this.infraredFrameData[i] / InfraredSourceValueMaximum; - - // 2. dividing by the (average scene value * standard deviations) - intensityRatio /= InfraredSceneValueAverage * InfraredSceneStandardDeviations; - - // 3. limiting the value to InfraredOutputValueMaximum - intensityRatio = Math.Min(InfraredOutputValueMaximum, intensityRatio); - - // 4. limiting the lower value InfraredOutputValueMinimum - intensityRatio = Math.Max(InfraredOutputValueMinimum, intensityRatio); - - // 5. converting the normalized value to a byte and using the result - // as the RGB components required by the image - byte intensity = (byte)(intensityRatio * 255.0f); - this.infraredPixels[colorPixelIndex++] = intensity; //Blue - this.infraredPixels[colorPixelIndex++] = intensity; //Green - this.infraredPixels[colorPixelIndex++] = intensity; //Red - this.infraredPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void RenderPixelArray(byte[] pixels) - { - pixels.CopyTo(this.bitmap.PixelBuffer); - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - - private void InfraredButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Infrared); - } - - private void ColorButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Color); - } - - private void DepthButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Depth); - } - - private void BodyMaskButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyMask); - } - - [Guid("905a0fef-bc53-11df-8c49-001e4fc686da"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IBufferByteAccess - { - unsafe void Buffer(out byte* pByte); - } - - - } -} diff --git a/Kinect2Sample.Lab5/Kinect2Sample/Package.appxmanifest b/Kinect2Sample.Lab5/Kinect2Sample/Package.appxmanifest deleted file mode 100644 index 297bc48..0000000 --- a/Kinect2Sample.Lab5/Kinect2Sample/Package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Kinect2Sample - Jesse - Assets\StoreLogo.png - - - 6.3.0 - 6.3.0 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab5/Kinect2Sample/Properties/AssemblyInfo.cs b/Kinect2Sample.Lab5/Kinect2Sample/Properties/AssemblyInfo.cs deleted file mode 100644 index 991ad4a..0000000 --- a/Kinect2Sample.Lab5/Kinect2Sample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Kinect2Sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Kinect2Sample")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/Kinect2Sample.Lab6/Kinect2Sample.sln b/Kinect2Sample.Lab6/Kinect2Sample.sln deleted file mode 100644 index 887b8ec..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample.sln +++ /dev/null @@ -1,32 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kinect2Sample", "Kinect2Sample\Kinect2Sample.csproj", "{10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Build.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Deploy.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.ActiveCfg = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Build.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Deploy.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.ActiveCfg = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Build.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Deploy.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.ActiveCfg = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Build.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Deploy.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Kinect2Sample.Lab6/Kinect2Sample/App.xaml b/Kinect2Sample.Lab6/Kinect2Sample/App.xaml deleted file mode 100644 index b34ea9d..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/App.xaml +++ /dev/null @@ -1,7 +0,0 @@ - - - diff --git a/Kinect2Sample.Lab6/Kinect2Sample/App.xaml.cs b/Kinect2Sample.Lab6/Kinect2Sample/App.xaml.cs deleted file mode 100644 index 1692c86..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/App.xaml.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 - -namespace Kinect2Sample -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = true; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - // Set the default language - rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Assets/Logo.scale-100.png b/Kinect2Sample.Lab6/Kinect2Sample/Assets/Logo.scale-100.png deleted file mode 100644 index e26771c..0000000 Binary files a/Kinect2Sample.Lab6/Kinect2Sample/Assets/Logo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Assets/SmallLogo.scale-100.png b/Kinect2Sample.Lab6/Kinect2Sample/Assets/SmallLogo.scale-100.png deleted file mode 100644 index 1eb0d9d..0000000 Binary files a/Kinect2Sample.Lab6/Kinect2Sample/Assets/SmallLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Assets/SplashScreen.scale-100.png b/Kinect2Sample.Lab6/Kinect2Sample/Assets/SplashScreen.scale-100.png deleted file mode 100644 index c951e03..0000000 Binary files a/Kinect2Sample.Lab6/Kinect2Sample/Assets/SplashScreen.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Assets/StoreLogo.scale-100.png b/Kinect2Sample.Lab6/Kinect2Sample/Assets/StoreLogo.scale-100.png deleted file mode 100644 index dcb6727..0000000 Binary files a/Kinect2Sample.Lab6/Kinect2Sample/Assets/StoreLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab6/Kinect2Sample/BodiesManager.cs b/Kinect2Sample.Lab6/Kinect2Sample/BodiesManager.cs deleted file mode 100644 index ba728a6..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/BodiesManager.cs +++ /dev/null @@ -1,492 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Foundation; -using Windows.UI; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - public class BodiesManager - { - /// - /// Radius of drawn hand circles - /// - private const double HighConfidenceHandSize = 40; - - /// - /// Radius of drawn hand circles - /// - private const double LowConfidenceHandSize = 20; - - /// - /// Thickness of drawn joint lines - /// - private const double JointThickness = 8.0; - - /// - /// Thickness of seen bone lines - /// - private const double TrackedBoneThickness = 4.0; - - /// - /// Thickness of inferred joint lines - /// - private const double InferredBoneThickness = 1.0; - - /// - /// Thickness of clip edge rectangles - /// - private const double ClipBoundsThickness = 5; - - /// - /// Constant for clamping Z values of camera space points from being negative - /// - private const float InferredZPositionClamp = 0.1f; - - private CoordinateMapper coordinateMapper; - private Canvas drawingCanvas; - - private Rectangle LeftClipEdge; - private Rectangle RightClipEdge; - private Rectangle TopClipEdge; - private Rectangle BottomClipEdge; - - /// - /// List of BodyInfo objects for each potential body - /// - private BodyInfo[] bodyInfos; - - /// - /// List of colors for each body tracked - /// - private List bodyColors; - - private int BodyCount - { - set - { - if (value == 0) - { - this.bodyInfos = null; - return; - } - - // creates instances of BodyInfo objects for potential number of bodies - if (this.bodyInfos == null || this.bodyInfos.Length != value) - { - this.bodyInfos = new BodyInfo[value]; - - for (int bodyIndex = 0; bodyIndex < value; bodyIndex++) - { - this.bodyInfos[bodyIndex] = new BodyInfo(this.bodyColors[bodyIndex], JointThickness); - } - } - } - - get { return this.bodyInfos == null ? 0 : this.bodyInfos.Length; } - } - - /// - /// Maps bodies and joints to render them in a canvas. - /// - /// The current co-ordinate mapper from the Kinect Sensor - /// The canvas upon which the joints and bones are drawn - /// The amount of bodies concurrently drawable - public BodiesManager(CoordinateMapper coordMapper, Canvas drawableCanvas, int bodyCount) - { - this.coordinateMapper = coordMapper; - this.drawingCanvas = drawableCanvas; - // populate body colors, one for each BodyIndex - this.bodyColors = new List - { - Colors.Red, - Colors.Orange, - Colors.Green, - Colors.Blue, - Colors.Indigo, - Colors.Violet - }; - - // sets total number of possible tracked bodies - // create ellipses and lines for drawing bodies - this.BodyCount = bodyCount; - - PopulateVisualJoints(); - } - - /// - /// Instantiate new objects for joints, bone lines, and clipped edge rectangles - /// - private void PopulateVisualJoints() - { - // create clipped edges and set to collapsed initially - this.LeftClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.RightClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.TopClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.BottomClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - foreach (var bodyInfo in this.bodyInfos) - { - // add left and right hand ellipses of all bodies to canvas - this.drawingCanvas.Children.Add(bodyInfo.HandLeftEllipse); - this.drawingCanvas.Children.Add(bodyInfo.HandRightEllipse); - - // add joint ellipses of all bodies to canvas - foreach (var joint in bodyInfo.JointPoints) - { - this.drawingCanvas.Children.Add(joint.Value); - } - - // add bone lines of all bodies to canvas - foreach (var bone in bodyInfo.Bones) - { - this.drawingCanvas.Children.Add(bodyInfo.BoneLines[bone]); - } - } - - // add clipped edges rectanges to main canvas - this.drawingCanvas.Children.Add(this.LeftClipEdge); - this.drawingCanvas.Children.Add(this.RightClipEdge); - this.drawingCanvas.Children.Add(this.TopClipEdge); - this.drawingCanvas.Children.Add(this.BottomClipEdge); - - // position the clipped edges - Canvas.SetLeft(this.LeftClipEdge, 0); - Canvas.SetTop(this.LeftClipEdge, 0); - Canvas.SetLeft(this.RightClipEdge, this.drawingCanvas.Width - ClipBoundsThickness); - Canvas.SetTop(this.RightClipEdge, 0); - Canvas.SetLeft(this.TopClipEdge, 0); - Canvas.SetTop(this.TopClipEdge, 0); - Canvas.SetLeft(this.BottomClipEdge, 0); - Canvas.SetTop(this.BottomClipEdge, this.drawingCanvas.Height - ClipBoundsThickness); - } - - /// - /// Updates all elipses and lines representing joints and bones - /// with the latest tracked bodies. - /// - /// An array containing body data. - internal void UpdateBodiesAndEdges(Body[] bodies) - { - bool hasTrackedBody = false; - // iterate through each body - for (int bodyIndex = 0; bodyIndex < bodies.Length; bodyIndex++) - { - Body body = bodies[bodyIndex]; - - if (body.IsTracked) - { - // check if this body clips an edge - this.UpdateClippedEdges(body, hasTrackedBody); - - this.UpdateBody(body, bodyIndex); - - hasTrackedBody = true; - } - else - { - // collapse this body from canvas as it goes out of view - this.ClearBody(bodyIndex); - } - } - - if (!hasTrackedBody) - { - // clear clipped edges if no bodies are tracked - this.ClearClippedEdges(); - } - } - - /// - /// Update body data for each body that is tracked. - /// - /// body for getting joint info - /// index for body we are currently updating - internal void UpdateBody(Body body, int bodyIndex) - { - IReadOnlyDictionary joints = body.Joints; - var jointPointsInDepthSpace = new Dictionary(); - - var bodyInfo = this.bodyInfos[bodyIndex]; - - // update all joints - foreach (var jointType in body.Joints.Keys) - { - // sometimes the depth(Z) of an inferred joint may show as negative - // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity) - CameraSpacePoint position = body.Joints[jointType].Position; - if (position.Z < 0) - { - position.Z = InferredZPositionClamp; - } - - // map joint position to depth space - DepthSpacePoint depthSpacePoint = coordinateMapper.MapCameraPointToDepthSpace(position); - jointPointsInDepthSpace[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y); - - // modify the joint's visibility and location - this.UpdateJoint(bodyInfo.JointPoints[jointType], joints[jointType], jointPointsInDepthSpace[jointType]); - - // modify hand ellipse colors based on hand states - // modity hand ellipse sizes based on tracking confidences - if (jointType == JointType.HandRight) - { - this.UpdateHand(bodyInfo.HandRightEllipse, body.HandRightState, body.HandRightConfidence, jointPointsInDepthSpace[jointType]); - } - - if (jointType == JointType.HandLeft) - { - this.UpdateHand(bodyInfo.HandLeftEllipse, body.HandLeftState, body.HandLeftConfidence, jointPointsInDepthSpace[jointType]); - } - } - - // update all bones - foreach (var bone in bodyInfo.Bones) - { - this.UpdateBone(bodyInfo.BoneLines[bone], joints[bone.Item1], joints[bone.Item2], - jointPointsInDepthSpace[bone.Item1], - jointPointsInDepthSpace[bone.Item2]); - } - } - /// - /// Updates hand state ellipses depending on tracking state and it's confidence. - /// - /// ellipse representing handstate - /// open, closed, or lasso - /// confidence of handstate - /// location of handjoint - private void UpdateHand(Ellipse ellipse, HandState handState, TrackingConfidence trackingConfidence, Point point) - { - ellipse.Fill = new SolidColorBrush(this.HandStateToColor(handState)); - - // draw handstate ellipse based on tracking confidence - ellipse.Width = ellipse.Height = (trackingConfidence == TrackingConfidence.Low) ? LowConfidenceHandSize : HighConfidenceHandSize; - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - - // don't draw handstate if hand joints are not tracked - if (!Double.IsInfinity(point.X) && !Double.IsInfinity(point.Y)) - { - Canvas.SetLeft(ellipse, point.X - ellipse.Width / 2); - Canvas.SetTop(ellipse, point.Y - ellipse.Width / 2); - } - } - - /// - /// Update a joint. - /// - /// - /// - /// - private void UpdateJoint(Ellipse ellipse, Joint joint, Point point) - { - TrackingState trackingState = joint.TrackingState; - - // only draw if joint is tracked or inferred - if (trackingState != TrackingState.NotTracked) - { - if (trackingState == TrackingState.Tracked) - { - ellipse.Fill = new SolidColorBrush(Colors.Green); - } - else - { - // inferred joints are yellow - ellipse.Fill = new SolidColorBrush(Colors.Yellow); - } - - Canvas.SetLeft(ellipse, point.X - JointThickness / 2); - Canvas.SetTop(ellipse, point.Y - JointThickness / 2); - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else - { - ellipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Update a bone line. - /// - /// line representing a bone line - /// start joint of bone line - /// end joint of bone line - /// location of start joint - /// location of end joint - private void UpdateBone(Line line, Joint startJoint, Joint endJoint, Point startPoint, Point endPoint) - { - // don't draw if neither joints are tracked - if (startJoint.TrackingState == TrackingState.NotTracked || endJoint.TrackingState == TrackingState.NotTracked) - { - line.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - return; - } - - // all lines are inferred thickness unless both joints are tracked - line.StrokeThickness = InferredBoneThickness; - - if (startJoint.TrackingState == TrackingState.Tracked && - endJoint.TrackingState == TrackingState.Tracked) - { - line.StrokeThickness = TrackedBoneThickness; - } - - line.Visibility = Windows.UI.Xaml.Visibility.Visible; - - line.X1 = startPoint.X; - line.Y1 = startPoint.Y; - line.X2 = endPoint.X; - line.Y2 = endPoint.Y; - } - - /// - /// Draws indicators to show which edges are clipping body data. - /// - /// body to draw clipping information for - /// bool to determine if another body is triggering a clipped edge - private void UpdateClippedEdges(Body body, bool hasTrackedBody) - { - // BUG (waiting for confirmation): - // Clip dectection works differently for top and right edges compared to left and bottom edges - // due to the current joint confidence model. This is an ST issue. - // Joints become inferred immediately as they touch the left/bottom edges and clip detection triggers. - // Joints squish on the right/top edges and clip detection doesn't trigger until more joints of - // the body goes out of view (e.g all hand joints vs only handtip). - - FrameEdges clippedEdges = body.ClippedEdges; - - if (clippedEdges.HasFlag(FrameEdges.Left)) - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - // don't clear this edge if another body is triggering clipped edge - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Right)) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Top)) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Bottom)) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Select color of hand state - /// - /// - /// - private Color HandStateToColor(HandState handState) - { - switch (handState) - { - case HandState.Open: - return Colors.Green; - - case HandState.Closed: - return Colors.Red; - - case HandState.Lasso: - return Colors.Blue; - } - - return Colors.Transparent; - } - - /// - /// Collapse the body from the canvas. - /// - /// - private void ClearBody(int bodyIndex) - { - var bodyInfo = this.bodyInfos[bodyIndex]; - - // collapse all joint ellipses - foreach (var joint in bodyInfo.JointPoints) - { - joint.Value.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse all bone lines - foreach (var bone in bodyInfo.Bones) - { - bodyInfo.BoneLines[bone].Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse handstate ellipses - bodyInfo.HandLeftEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - bodyInfo.HandRightEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - /// - /// Clear all clipped edges. - /// - private void ClearClippedEdges() - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } -} diff --git a/Kinect2Sample.Lab6/Kinect2Sample/BodyInfo.cs b/Kinect2Sample.Lab6/Kinect2Sample/BodyInfo.cs deleted file mode 100644 index 2f03930..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/BodyInfo.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - /// - /// BodyInfo class that contains joint ellipses, handstate ellipses, lines for bones between two joints. - /// - public class BodyInfo - { - public bool Updated { get; set; } - - public Color BodyColor { get; set; } - - // ellipse representing left handstate - public Ellipse HandLeftEllipse { get; set; } - - // ellipse representing right handstate - public Ellipse HandRightEllipse { get; set; } - - // dictionary of all joints in a body - public Dictionary JointPoints { get; private set; } - - // definition of bones - public TupleList Bones { get; private set; } - - // collection of bones associated with the line object - public Dictionary, Line> BoneLines { get; private set; } - - public BodyInfo(Color bodyColor, double jointThickness) - { - this.BodyColor = bodyColor; - - // create hand state ellipses - this.HandLeftEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.HandRightEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - // a joint defined as a jointType with a point location in XY space represented by an ellipse - this.JointPoints = new Dictionary(); - - // pre-populate list of joints and set to non-visible initially - foreach (JointType jointType in Enum.GetValues(typeof(JointType))) - { - this.JointPoints.Add(jointType, new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed, - Fill = new SolidColorBrush(BodyColor), - Width = jointThickness, - Height = jointThickness - }); - } - - // collection of bones - this.BoneLines = new Dictionary, Line>(); - - // a bone defined as a line between two joints - this.Bones = new TupleList - { - // Torso - { JointType.Head, JointType.Neck }, - { JointType.Neck, JointType.SpineShoulder }, - { JointType.SpineShoulder, JointType.SpineMid }, - { JointType.SpineMid, JointType.SpineBase }, - { JointType.SpineShoulder, JointType.ShoulderRight }, - { JointType.SpineShoulder, JointType.ShoulderLeft }, - { JointType.SpineBase, JointType.HipRight }, - { JointType.SpineBase, JointType.HipLeft }, - - // Right Arm - { JointType.ShoulderRight, JointType.ElbowRight }, - { JointType.ElbowRight, JointType.WristRight }, - { JointType.WristRight, JointType.HandRight }, - { JointType.HandRight, JointType.HandTipRight }, - { JointType.WristRight, JointType.ThumbRight }, - - // Left Arm - { JointType.ShoulderLeft, JointType.ElbowLeft }, - { JointType.ElbowLeft, JointType.WristLeft }, - { JointType.WristLeft, JointType.HandLeft }, - { JointType.HandLeft, JointType.HandTipLeft }, - { JointType.WristLeft, JointType.ThumbLeft }, - - // Right Leg - { JointType.HipRight, JointType.KneeRight }, - { JointType.KneeRight, JointType.AnkleRight }, - { JointType.AnkleRight, JointType.FootRight }, - - // Left Leg - { JointType.HipLeft, JointType.KneeLeft }, - { JointType.KneeLeft, JointType.AnkleLeft }, - { JointType.AnkleLeft, JointType.FootLeft }, - }; - - // pre-populate list of bones that are non-visible initially - foreach (var bone in this.Bones) - { - this.BoneLines.Add(bone, new Line() - { - Stroke = new SolidColorBrush(BodyColor), - Visibility = Visibility.Collapsed - }); - } - } - } - - public class TupleList : List> - { - public void Add(T1 item, T2 item2) - { - this.Add(new Tuple(item, item2)); - } - } - -} diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample.Lab6/Kinect2Sample/Kinect2Sample.csproj deleted file mode 100644 index 8d7dff2..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/Kinect2Sample.csproj +++ /dev/null @@ -1,119 +0,0 @@ - - - - - Debug - AnyCPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F} - AppContainerExe - Properties - Kinect2Sample - Kinect2Sample - en-US - 8.1 - 12 - 512 - {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Kinect2Sample_TemporaryKey.pfx - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x64 - false - prompt - true - true - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x64 - false - prompt - true - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x86 - false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x86 - false - prompt - true - - - - App.xaml - - - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - Microsoft Visual C++ 2013 Runtime Package for Windows - - - WindowsPreview.Kinect - - - - - - - 12.0 - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx b/Kinect2Sample.Lab6/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx deleted file mode 100644 index 7cb3591..0000000 Binary files a/Kinect2Sample.Lab6/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx and /dev/null differ diff --git a/Kinect2Sample.Lab6/Kinect2Sample/MainPage.xaml b/Kinect2Sample.Lab6/Kinect2Sample/MainPage.xaml deleted file mode 100644 index 0211157..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/MainPage.xaml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Kinect2Sample.Lab6/Kinect2Sample/MainPage.xaml.cs b/Kinect2Sample.Lab6/Kinect2Sample/MainPage.xaml.cs deleted file mode 100644 index a4b58a9..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/MainPage.xaml.cs +++ /dev/null @@ -1,602 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Media.Imaging; -using Windows.UI.Xaml.Navigation; -using WindowsPreview.Kinect; -using System.ComponentModel; -using Windows.Storage.Streams; -using System.Runtime.InteropServices; -using System.Diagnostics; -using Windows.UI.Xaml.Shapes; - -namespace Kinect2Sample -{ - public enum DisplayFrameType - { - Infrared, - Color, - Depth, - BodyMask, - BodyJoints - } - - public sealed partial class MainPage : Page, INotifyPropertyChanged - { - private const DisplayFrameType DEFAULT_DISPLAYFRAMETYPE = DisplayFrameType.Infrared; - - /// - /// The highest value that can be returned in the InfraredFrame. - /// It is cast to a float for readability in the visualization code. - /// - private const float InfraredSourceValueMaximum = (float)ushort.MaxValue; - - /// - /// Used to set the lower limit, post processing, of the - /// infrared data that we will render. - /// Increasing or decreasing this value sets a brightness - /// "wall" either closer or further away. - /// - private const float InfraredOutputValueMinimum = 0.01f; - - /// - /// The upper limit, post processing, of the - /// infrared data that will render. - /// - private const float InfraredOutputValueMaximum = 1.0f; - - /// - /// The InfraredSceneValueAverage value specifies the average infrared - /// value of the scene. This value was selected by analyzing the average - /// pixel intensity for a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneValueAverage = 0.08f; - - /// - /// The InfraredSceneStandardDeviations value specifies the number of - /// standard deviations to apply to InfraredSceneValueAverage. - /// This value was selected by analyzing data from a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneStandardDeviations = 3.0f; - - // Size of the RGB pixel in the bitmap - private const int BytesPerPixel = 4; - - private KinectSensor kinectSensor = null; - private string statusText = null; - private WriteableBitmap bitmap = null; - private FrameDescription currentFrameDescription; - private DisplayFrameType currentDisplayFrameType; - private MultiSourceFrameReader multiSourceFrameReader = null; - private CoordinateMapper coordinateMapper = null; - private BodiesManager bodiesManager = null; - - //Infrared Frame - private ushort[] infraredFrameData = null; - private byte[] infraredPixels = null; - - //Depth Frame - private ushort[] depthFrameData = null; - private byte[] depthPixels = null; - - //BodyMask Frames - private DepthSpacePoint[] colorMappedToDepthPoints = null; - - //Body Joints are drawn here - private Canvas drawingCanvas; - - - public event PropertyChangedEventHandler PropertyChanged; - public string StatusText - { - get { return this.statusText; } - set - { - if (this.statusText != value) - { - this.statusText = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); - } - } - } - } - - public FrameDescription CurrentFrameDescription - { - get { return this.currentFrameDescription; } - set - { - if (this.currentFrameDescription != value) - { - this.currentFrameDescription = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentFrameDescription")); - } - } - } - } - - public MainPage() - { - // one sensor is currently supported - this.kinectSensor = KinectSensor.GetDefault(); - - SetupCurrentDisplay(DEFAULT_DISPLAYFRAMETYPE); - - this.coordinateMapper = this.kinectSensor.CoordinateMapper; - - this.multiSourceFrameReader = this.kinectSensor.OpenMultiSourceFrameReader(FrameSourceTypes.Infrared | FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.BodyIndex | FrameSourceTypes.Body); - - this.multiSourceFrameReader.MultiSourceFrameArrived += this.Reader_MultiSourceFrameArrived; - - // set IsAvailableChanged event notifier - this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; - - // use the window object as the view model in this simple example - this.DataContext = this; - - // open the sensor - this.kinectSensor.Open(); - - this.InitializeComponent(); - } - - private void SetupCurrentDisplay(DisplayFrameType newDisplayFrameType) - { - currentDisplayFrameType = newDisplayFrameType; - // Frames used by more than one type are declared outside the switch - FrameDescription colorFrameDescription = null; - // reset the display methods - if (this.BodyJointsGrid != null) - { - this.BodyJointsGrid.Visibility = Visibility.Collapsed; - } - if (this.FrameDisplayImage != null) - { - this.FrameDisplayImage.Source = null; - } - switch (currentDisplayFrameType) - { - case DisplayFrameType.Infrared: - FrameDescription infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription; - this.CurrentFrameDescription = infraredFrameDescription; - // allocate space to put the pixels being received and converted - this.infraredFrameData = new ushort[infraredFrameDescription.Width * infraredFrameDescription.Height]; - this.infraredPixels = new byte[infraredFrameDescription.Width * infraredFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(infraredFrameDescription.Width, infraredFrameDescription.Height); - break; - - case DisplayFrameType.Color: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // create the bitmap to display - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.Depth: - FrameDescription depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - this.CurrentFrameDescription = depthFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.depthPixels = new byte[depthFrameDescription.Width * depthFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(depthFrameDescription.Width, depthFrameDescription.Height); - break; - - case DisplayFrameType.BodyMask: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.BodyJoints: - // instantiate a new Canvas - this.drawingCanvas = new Canvas(); - // set the clip rectangle to prevent rendering outside the canvas - this.drawingCanvas.Clip = new RectangleGeometry(); - this.drawingCanvas.Clip.Rect = new Rect(0.0, 0.0, this.BodyJointsGrid.Width, this.BodyJointsGrid.Height); - this.drawingCanvas.Width = this.BodyJointsGrid.Width; - this.drawingCanvas.Height = this.BodyJointsGrid.Height; - // reset the body joints grid - this.BodyJointsGrid.Visibility = Visibility.Visible; - this.BodyJointsGrid.Children.Clear(); - // add canvas to DisplayGrid - this.BodyJointsGrid.Children.Add(this.drawingCanvas); - bodiesManager = new BodiesManager(this.coordinateMapper, this.drawingCanvas, this.kinectSensor.BodyFrameSource.BodyCount); - break; - default: - break; - } - } - - private void Sensor_IsAvailableChanged(KinectSensor sender, IsAvailableChangedEventArgs args) - { - this.StatusText = this.kinectSensor.IsAvailable ? "Running" : "Not Available"; - } - - private void Reader_MultiSourceFrameArrived(MultiSourceFrameReader sender, MultiSourceFrameArrivedEventArgs e) - { - - MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame(); - - // If the Frame has expired by the time we process this event, return. - if (multiSourceFrame == null) - { - return; - } - DepthFrame depthFrame = null; - ColorFrame colorFrame = null; - InfraredFrame infraredFrame = null; - BodyFrame bodyFrame = null; - BodyIndexFrame bodyIndexFrame = null; - IBuffer depthFrameData = null; - IBuffer bodyIndexFrameData = null; - // Com interface for unsafe byte manipulation - IBufferByteAccess bodyIndexByteAccess = null; - - switch (currentDisplayFrameType) - { - case DisplayFrameType.Infrared: - using (infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame()) - { - ShowInfraredFrame(infraredFrame); - } - break; - case DisplayFrameType.Color: - using (colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame()) - { - ShowColorFrame(colorFrame); - } - break; - case DisplayFrameType.Depth: - using (depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame()) - { - ShowDepthFrame(depthFrame); - } - break; - case DisplayFrameType.BodyMask: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - bodyIndexFrame = multiSourceFrame.BodyIndexFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null) || (bodyIndexFrame == null)) - { - return; - } - - // Access the depth frame data directly via LockImageBuffer to avoid making a copy - depthFrameData = depthFrame.LockImageBuffer(); - this.coordinateMapper.MapColorFrameToDepthSpaceUsingIBuffer(depthFrameData, this.colorMappedToDepthPoints); - // Process Color - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - // Access the body index frame data directly via LockImageBuffer to avoid making a copy - bodyIndexFrameData = bodyIndexFrame.LockImageBuffer(); - ShowMappedBodyFrame(depthFrame.FrameDescription.Width, depthFrame.FrameDescription.Height, bodyIndexFrameData, bodyIndexByteAccess); - - } - finally - { - // ... disposing of depth, color and bodyIndex frames - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - if (bodyIndexFrame != null) - { - bodyIndexFrame.Dispose(); - } - - if (depthFrameData != null) - { - // We must force a release of the IBuffer in order to ensure that we have dropped all references to it. - System.Runtime.InteropServices.Marshal.ReleaseComObject(depthFrameData); - } - if (bodyIndexFrameData != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bodyIndexFrameData); - } - if (bodyIndexByteAccess != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bodyIndexByteAccess); - } - - } - break; - case DisplayFrameType.BodyJoints: - using (bodyFrame = multiSourceFrame.BodyFrameReference.AcquireFrame()) - { - ShowBodyJoints(bodyFrame); - } - break; - default: - break; - } - } - - private void ShowBodyJoints(BodyFrame bodyFrame) - { - Body[] bodies = new Body[this.kinectSensor.BodyFrameSource.BodyCount]; - bool dataReceived = false; - if (bodyFrame != null) - { - bodyFrame.GetAndRefreshBodyData(bodies); - dataReceived = true; - } - - if (dataReceived) - { - this.bodiesManager.UpdateBodiesAndEdges(bodies); - } - } - - unsafe private void ShowMappedBodyFrame(int depthWidth, int depthHeight, IBuffer bodyIndexFrameData, IBufferByteAccess bodyIndexByteAccess) - { - bodyIndexByteAccess = (IBufferByteAccess)bodyIndexFrameData; - byte* bodyIndexBytes = null; - bodyIndexByteAccess.Buffer(out bodyIndexBytes); - - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = this.colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - int colorMappedLength = this.colorMappedToDepthPoints.Length; - for (int colorIndex = 0; colorIndex < colorMappedLength; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPointsPointer[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPointsPointer[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - // If we are tracking a body for the current pixel, do not zero out the pixel - if (bodyIndexBytes[depthIndex] != 0xff) - { - // this bodyIndexByte is good and is a body, loop again. - continue; - } - } - } - // this pixel does not correspond to a body so make it black and transparent - bitmapPixelsPointer[colorIndex] = 0; - } - } - - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - - } - - private void ShowDepthFrame(DepthFrame depthFrame) - { - bool depthFrameProcessed = false; - ushort minDepth = 0; - ushort maxDepth = 0; - - if (depthFrame != null) - { - FrameDescription depthFrameDescription = depthFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((depthFrameDescription.Width * depthFrameDescription.Height) - == this.infraredFrameData.Length) && - (depthFrameDescription.Width == this.bitmap.PixelWidth) && - (depthFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - depthFrame.CopyFrameDataToArray(this.depthFrameData); - - minDepth = depthFrame.DepthMinReliableDistance; - maxDepth = depthFrame.DepthMaxReliableDistance; - //maxDepth = 8000; - - depthFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (depthFrameProcessed) - { - ConvertDepthDataToPixels(minDepth, maxDepth); - RenderPixelArray(this.depthPixels); - } - } - - private void ConvertDepthDataToPixels(ushort minDepth, ushort maxDepth) - { - int colorPixelIndex = 0; - // Shape the depth to the range of a byte - int mapDepthToByte = maxDepth / 256; - - for (int i = 0; i < this.depthFrameData.Length; ++i) - { - // Get the depth for this pixel - ushort depth = this.depthFrameData[i]; - - // To convert to a byte, we're mapping the depth value to the byte range. - // Values outside the reliable depth range are mapped to 0 (black). - byte intensity = (byte)(depth >= minDepth && - depth <= maxDepth ? (depth / mapDepthToByte) : 0); - - this.depthPixels[colorPixelIndex++] = intensity; //Blue - this.depthPixels[colorPixelIndex++] = intensity; //Green - this.depthPixels[colorPixelIndex++] = intensity; //Red - this.depthPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void ShowColorFrame(ColorFrame colorFrame) - { - bool colorFrameProcessed = false; - - if (colorFrame != null) - { - FrameDescription colorFrameDescription = colorFrame.FrameDescription; - - // verify data and write the new color frame data to the Writeable bitmap - if ((colorFrameDescription.Width == this.bitmap.PixelWidth) && (colorFrameDescription.Height == this.bitmap.PixelHeight)) - { - if (colorFrame.RawColorImageFormat == ColorImageFormat.Bgra) - { - colorFrame.CopyRawFrameDataToBuffer(this.bitmap.PixelBuffer); - } - else - { - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - } - - colorFrameProcessed = true; - } - } - - if (colorFrameProcessed) - { - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - } - - private void ShowInfraredFrame(InfraredFrame infraredFrame) - { - bool infraredFrameProcessed = false; - - if (infraredFrame != null) - { - FrameDescription infraredFrameDescription = infraredFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((infraredFrameDescription.Width * infraredFrameDescription.Height) - == this.infraredFrameData.Length) && - (infraredFrameDescription.Width == this.bitmap.PixelWidth) && - (infraredFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - infraredFrame.CopyFrameDataToArray(this.infraredFrameData); - - infraredFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (infraredFrameProcessed) - { - this.ConvertInfraredDataToPixels(); - this.RenderPixelArray(this.infraredPixels); - } - } - - private void ConvertInfraredDataToPixels() - { - // Convert the infrared to RGB - int colorPixelIndex = 0; - for (int i = 0; i < this.infraredFrameData.Length; ++i) - { - // normalize the incoming infrared data (ushort) to a float ranging from - // [InfraredOutputValueMinimum, InfraredOutputValueMaximum] by - // 1. dividing the incoming value by the source maximum value - float intensityRatio = (float)this.infraredFrameData[i] / InfraredSourceValueMaximum; - - // 2. dividing by the (average scene value * standard deviations) - intensityRatio /= InfraredSceneValueAverage * InfraredSceneStandardDeviations; - - // 3. limiting the value to InfraredOutputValueMaximum - intensityRatio = Math.Min(InfraredOutputValueMaximum, intensityRatio); - - // 4. limiting the lower value InfraredOutputValueMinimum - intensityRatio = Math.Max(InfraredOutputValueMinimum, intensityRatio); - - // 5. converting the normalized value to a byte and using the result - // as the RGB components required by the image - byte intensity = (byte)(intensityRatio * 255.0f); - this.infraredPixels[colorPixelIndex++] = intensity; //Blue - this.infraredPixels[colorPixelIndex++] = intensity; //Green - this.infraredPixels[colorPixelIndex++] = intensity; //Red - this.infraredPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void RenderPixelArray(byte[] pixels) - { - pixels.CopyTo(this.bitmap.PixelBuffer); - this.bitmap.Invalidate(); - this.FrameDisplayImage.Source = this.bitmap; - } - - - - private void InfraredButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Infrared); - } - - private void ColorButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Color); - } - - private void DepthButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Depth); - } - - private void BodyMaskButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyMask); - } - - private void BodyJointsButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyJoints); - } - - [Guid("905a0fef-bc53-11df-8c49-001e4fc686da"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IBufferByteAccess - { - unsafe void Buffer(out byte* pByte); - } - - - - } -} diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Package.appxmanifest b/Kinect2Sample.Lab6/Kinect2Sample/Package.appxmanifest deleted file mode 100644 index 297bc48..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/Package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Kinect2Sample - Jesse - Assets\StoreLogo.png - - - 6.3.0 - 6.3.0 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab6/Kinect2Sample/Properties/AssemblyInfo.cs b/Kinect2Sample.Lab6/Kinect2Sample/Properties/AssemblyInfo.cs deleted file mode 100644 index 991ad4a..0000000 --- a/Kinect2Sample.Lab6/Kinect2Sample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Kinect2Sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Kinect2Sample")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/Kinect2Sample.Lab7/Kinect2Sample.sln b/Kinect2Sample.Lab7/Kinect2Sample.sln deleted file mode 100644 index 887b8ec..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample.sln +++ /dev/null @@ -1,32 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kinect2Sample", "Kinect2Sample\Kinect2Sample.csproj", "{10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Build.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Deploy.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.ActiveCfg = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Build.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Deploy.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.ActiveCfg = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Build.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Deploy.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.ActiveCfg = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Build.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Deploy.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Kinect2Sample.Lab7/Kinect2Sample/App.xaml b/Kinect2Sample.Lab7/Kinect2Sample/App.xaml deleted file mode 100644 index b34ea9d..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/App.xaml +++ /dev/null @@ -1,7 +0,0 @@ - - - diff --git a/Kinect2Sample.Lab7/Kinect2Sample/App.xaml.cs b/Kinect2Sample.Lab7/Kinect2Sample/App.xaml.cs deleted file mode 100644 index 1692c86..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/App.xaml.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 - -namespace Kinect2Sample -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = true; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - // Set the default language - rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Assets/Background.png b/Kinect2Sample.Lab7/Kinect2Sample/Assets/Background.png deleted file mode 100644 index 44e6e19..0000000 Binary files a/Kinect2Sample.Lab7/Kinect2Sample/Assets/Background.png and /dev/null differ diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Assets/Logo.scale-100.png b/Kinect2Sample.Lab7/Kinect2Sample/Assets/Logo.scale-100.png deleted file mode 100644 index e26771c..0000000 Binary files a/Kinect2Sample.Lab7/Kinect2Sample/Assets/Logo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Assets/SmallLogo.scale-100.png b/Kinect2Sample.Lab7/Kinect2Sample/Assets/SmallLogo.scale-100.png deleted file mode 100644 index 1eb0d9d..0000000 Binary files a/Kinect2Sample.Lab7/Kinect2Sample/Assets/SmallLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Assets/SplashScreen.scale-100.png b/Kinect2Sample.Lab7/Kinect2Sample/Assets/SplashScreen.scale-100.png deleted file mode 100644 index c951e03..0000000 Binary files a/Kinect2Sample.Lab7/Kinect2Sample/Assets/SplashScreen.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Assets/StoreLogo.scale-100.png b/Kinect2Sample.Lab7/Kinect2Sample/Assets/StoreLogo.scale-100.png deleted file mode 100644 index dcb6727..0000000 Binary files a/Kinect2Sample.Lab7/Kinect2Sample/Assets/StoreLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab7/Kinect2Sample/BodiesManager.cs b/Kinect2Sample.Lab7/Kinect2Sample/BodiesManager.cs deleted file mode 100644 index ba728a6..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/BodiesManager.cs +++ /dev/null @@ -1,492 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Foundation; -using Windows.UI; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - public class BodiesManager - { - /// - /// Radius of drawn hand circles - /// - private const double HighConfidenceHandSize = 40; - - /// - /// Radius of drawn hand circles - /// - private const double LowConfidenceHandSize = 20; - - /// - /// Thickness of drawn joint lines - /// - private const double JointThickness = 8.0; - - /// - /// Thickness of seen bone lines - /// - private const double TrackedBoneThickness = 4.0; - - /// - /// Thickness of inferred joint lines - /// - private const double InferredBoneThickness = 1.0; - - /// - /// Thickness of clip edge rectangles - /// - private const double ClipBoundsThickness = 5; - - /// - /// Constant for clamping Z values of camera space points from being negative - /// - private const float InferredZPositionClamp = 0.1f; - - private CoordinateMapper coordinateMapper; - private Canvas drawingCanvas; - - private Rectangle LeftClipEdge; - private Rectangle RightClipEdge; - private Rectangle TopClipEdge; - private Rectangle BottomClipEdge; - - /// - /// List of BodyInfo objects for each potential body - /// - private BodyInfo[] bodyInfos; - - /// - /// List of colors for each body tracked - /// - private List bodyColors; - - private int BodyCount - { - set - { - if (value == 0) - { - this.bodyInfos = null; - return; - } - - // creates instances of BodyInfo objects for potential number of bodies - if (this.bodyInfos == null || this.bodyInfos.Length != value) - { - this.bodyInfos = new BodyInfo[value]; - - for (int bodyIndex = 0; bodyIndex < value; bodyIndex++) - { - this.bodyInfos[bodyIndex] = new BodyInfo(this.bodyColors[bodyIndex], JointThickness); - } - } - } - - get { return this.bodyInfos == null ? 0 : this.bodyInfos.Length; } - } - - /// - /// Maps bodies and joints to render them in a canvas. - /// - /// The current co-ordinate mapper from the Kinect Sensor - /// The canvas upon which the joints and bones are drawn - /// The amount of bodies concurrently drawable - public BodiesManager(CoordinateMapper coordMapper, Canvas drawableCanvas, int bodyCount) - { - this.coordinateMapper = coordMapper; - this.drawingCanvas = drawableCanvas; - // populate body colors, one for each BodyIndex - this.bodyColors = new List - { - Colors.Red, - Colors.Orange, - Colors.Green, - Colors.Blue, - Colors.Indigo, - Colors.Violet - }; - - // sets total number of possible tracked bodies - // create ellipses and lines for drawing bodies - this.BodyCount = bodyCount; - - PopulateVisualJoints(); - } - - /// - /// Instantiate new objects for joints, bone lines, and clipped edge rectangles - /// - private void PopulateVisualJoints() - { - // create clipped edges and set to collapsed initially - this.LeftClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.RightClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.TopClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.BottomClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - foreach (var bodyInfo in this.bodyInfos) - { - // add left and right hand ellipses of all bodies to canvas - this.drawingCanvas.Children.Add(bodyInfo.HandLeftEllipse); - this.drawingCanvas.Children.Add(bodyInfo.HandRightEllipse); - - // add joint ellipses of all bodies to canvas - foreach (var joint in bodyInfo.JointPoints) - { - this.drawingCanvas.Children.Add(joint.Value); - } - - // add bone lines of all bodies to canvas - foreach (var bone in bodyInfo.Bones) - { - this.drawingCanvas.Children.Add(bodyInfo.BoneLines[bone]); - } - } - - // add clipped edges rectanges to main canvas - this.drawingCanvas.Children.Add(this.LeftClipEdge); - this.drawingCanvas.Children.Add(this.RightClipEdge); - this.drawingCanvas.Children.Add(this.TopClipEdge); - this.drawingCanvas.Children.Add(this.BottomClipEdge); - - // position the clipped edges - Canvas.SetLeft(this.LeftClipEdge, 0); - Canvas.SetTop(this.LeftClipEdge, 0); - Canvas.SetLeft(this.RightClipEdge, this.drawingCanvas.Width - ClipBoundsThickness); - Canvas.SetTop(this.RightClipEdge, 0); - Canvas.SetLeft(this.TopClipEdge, 0); - Canvas.SetTop(this.TopClipEdge, 0); - Canvas.SetLeft(this.BottomClipEdge, 0); - Canvas.SetTop(this.BottomClipEdge, this.drawingCanvas.Height - ClipBoundsThickness); - } - - /// - /// Updates all elipses and lines representing joints and bones - /// with the latest tracked bodies. - /// - /// An array containing body data. - internal void UpdateBodiesAndEdges(Body[] bodies) - { - bool hasTrackedBody = false; - // iterate through each body - for (int bodyIndex = 0; bodyIndex < bodies.Length; bodyIndex++) - { - Body body = bodies[bodyIndex]; - - if (body.IsTracked) - { - // check if this body clips an edge - this.UpdateClippedEdges(body, hasTrackedBody); - - this.UpdateBody(body, bodyIndex); - - hasTrackedBody = true; - } - else - { - // collapse this body from canvas as it goes out of view - this.ClearBody(bodyIndex); - } - } - - if (!hasTrackedBody) - { - // clear clipped edges if no bodies are tracked - this.ClearClippedEdges(); - } - } - - /// - /// Update body data for each body that is tracked. - /// - /// body for getting joint info - /// index for body we are currently updating - internal void UpdateBody(Body body, int bodyIndex) - { - IReadOnlyDictionary joints = body.Joints; - var jointPointsInDepthSpace = new Dictionary(); - - var bodyInfo = this.bodyInfos[bodyIndex]; - - // update all joints - foreach (var jointType in body.Joints.Keys) - { - // sometimes the depth(Z) of an inferred joint may show as negative - // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity) - CameraSpacePoint position = body.Joints[jointType].Position; - if (position.Z < 0) - { - position.Z = InferredZPositionClamp; - } - - // map joint position to depth space - DepthSpacePoint depthSpacePoint = coordinateMapper.MapCameraPointToDepthSpace(position); - jointPointsInDepthSpace[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y); - - // modify the joint's visibility and location - this.UpdateJoint(bodyInfo.JointPoints[jointType], joints[jointType], jointPointsInDepthSpace[jointType]); - - // modify hand ellipse colors based on hand states - // modity hand ellipse sizes based on tracking confidences - if (jointType == JointType.HandRight) - { - this.UpdateHand(bodyInfo.HandRightEllipse, body.HandRightState, body.HandRightConfidence, jointPointsInDepthSpace[jointType]); - } - - if (jointType == JointType.HandLeft) - { - this.UpdateHand(bodyInfo.HandLeftEllipse, body.HandLeftState, body.HandLeftConfidence, jointPointsInDepthSpace[jointType]); - } - } - - // update all bones - foreach (var bone in bodyInfo.Bones) - { - this.UpdateBone(bodyInfo.BoneLines[bone], joints[bone.Item1], joints[bone.Item2], - jointPointsInDepthSpace[bone.Item1], - jointPointsInDepthSpace[bone.Item2]); - } - } - /// - /// Updates hand state ellipses depending on tracking state and it's confidence. - /// - /// ellipse representing handstate - /// open, closed, or lasso - /// confidence of handstate - /// location of handjoint - private void UpdateHand(Ellipse ellipse, HandState handState, TrackingConfidence trackingConfidence, Point point) - { - ellipse.Fill = new SolidColorBrush(this.HandStateToColor(handState)); - - // draw handstate ellipse based on tracking confidence - ellipse.Width = ellipse.Height = (trackingConfidence == TrackingConfidence.Low) ? LowConfidenceHandSize : HighConfidenceHandSize; - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - - // don't draw handstate if hand joints are not tracked - if (!Double.IsInfinity(point.X) && !Double.IsInfinity(point.Y)) - { - Canvas.SetLeft(ellipse, point.X - ellipse.Width / 2); - Canvas.SetTop(ellipse, point.Y - ellipse.Width / 2); - } - } - - /// - /// Update a joint. - /// - /// - /// - /// - private void UpdateJoint(Ellipse ellipse, Joint joint, Point point) - { - TrackingState trackingState = joint.TrackingState; - - // only draw if joint is tracked or inferred - if (trackingState != TrackingState.NotTracked) - { - if (trackingState == TrackingState.Tracked) - { - ellipse.Fill = new SolidColorBrush(Colors.Green); - } - else - { - // inferred joints are yellow - ellipse.Fill = new SolidColorBrush(Colors.Yellow); - } - - Canvas.SetLeft(ellipse, point.X - JointThickness / 2); - Canvas.SetTop(ellipse, point.Y - JointThickness / 2); - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else - { - ellipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Update a bone line. - /// - /// line representing a bone line - /// start joint of bone line - /// end joint of bone line - /// location of start joint - /// location of end joint - private void UpdateBone(Line line, Joint startJoint, Joint endJoint, Point startPoint, Point endPoint) - { - // don't draw if neither joints are tracked - if (startJoint.TrackingState == TrackingState.NotTracked || endJoint.TrackingState == TrackingState.NotTracked) - { - line.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - return; - } - - // all lines are inferred thickness unless both joints are tracked - line.StrokeThickness = InferredBoneThickness; - - if (startJoint.TrackingState == TrackingState.Tracked && - endJoint.TrackingState == TrackingState.Tracked) - { - line.StrokeThickness = TrackedBoneThickness; - } - - line.Visibility = Windows.UI.Xaml.Visibility.Visible; - - line.X1 = startPoint.X; - line.Y1 = startPoint.Y; - line.X2 = endPoint.X; - line.Y2 = endPoint.Y; - } - - /// - /// Draws indicators to show which edges are clipping body data. - /// - /// body to draw clipping information for - /// bool to determine if another body is triggering a clipped edge - private void UpdateClippedEdges(Body body, bool hasTrackedBody) - { - // BUG (waiting for confirmation): - // Clip dectection works differently for top and right edges compared to left and bottom edges - // due to the current joint confidence model. This is an ST issue. - // Joints become inferred immediately as they touch the left/bottom edges and clip detection triggers. - // Joints squish on the right/top edges and clip detection doesn't trigger until more joints of - // the body goes out of view (e.g all hand joints vs only handtip). - - FrameEdges clippedEdges = body.ClippedEdges; - - if (clippedEdges.HasFlag(FrameEdges.Left)) - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - // don't clear this edge if another body is triggering clipped edge - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Right)) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Top)) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Bottom)) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Select color of hand state - /// - /// - /// - private Color HandStateToColor(HandState handState) - { - switch (handState) - { - case HandState.Open: - return Colors.Green; - - case HandState.Closed: - return Colors.Red; - - case HandState.Lasso: - return Colors.Blue; - } - - return Colors.Transparent; - } - - /// - /// Collapse the body from the canvas. - /// - /// - private void ClearBody(int bodyIndex) - { - var bodyInfo = this.bodyInfos[bodyIndex]; - - // collapse all joint ellipses - foreach (var joint in bodyInfo.JointPoints) - { - joint.Value.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse all bone lines - foreach (var bone in bodyInfo.Bones) - { - bodyInfo.BoneLines[bone].Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse handstate ellipses - bodyInfo.HandLeftEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - bodyInfo.HandRightEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - /// - /// Clear all clipped edges. - /// - private void ClearClippedEdges() - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } -} diff --git a/Kinect2Sample.Lab7/Kinect2Sample/BodyInfo.cs b/Kinect2Sample.Lab7/Kinect2Sample/BodyInfo.cs deleted file mode 100644 index 2f03930..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/BodyInfo.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - /// - /// BodyInfo class that contains joint ellipses, handstate ellipses, lines for bones between two joints. - /// - public class BodyInfo - { - public bool Updated { get; set; } - - public Color BodyColor { get; set; } - - // ellipse representing left handstate - public Ellipse HandLeftEllipse { get; set; } - - // ellipse representing right handstate - public Ellipse HandRightEllipse { get; set; } - - // dictionary of all joints in a body - public Dictionary JointPoints { get; private set; } - - // definition of bones - public TupleList Bones { get; private set; } - - // collection of bones associated with the line object - public Dictionary, Line> BoneLines { get; private set; } - - public BodyInfo(Color bodyColor, double jointThickness) - { - this.BodyColor = bodyColor; - - // create hand state ellipses - this.HandLeftEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.HandRightEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - // a joint defined as a jointType with a point location in XY space represented by an ellipse - this.JointPoints = new Dictionary(); - - // pre-populate list of joints and set to non-visible initially - foreach (JointType jointType in Enum.GetValues(typeof(JointType))) - { - this.JointPoints.Add(jointType, new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed, - Fill = new SolidColorBrush(BodyColor), - Width = jointThickness, - Height = jointThickness - }); - } - - // collection of bones - this.BoneLines = new Dictionary, Line>(); - - // a bone defined as a line between two joints - this.Bones = new TupleList - { - // Torso - { JointType.Head, JointType.Neck }, - { JointType.Neck, JointType.SpineShoulder }, - { JointType.SpineShoulder, JointType.SpineMid }, - { JointType.SpineMid, JointType.SpineBase }, - { JointType.SpineShoulder, JointType.ShoulderRight }, - { JointType.SpineShoulder, JointType.ShoulderLeft }, - { JointType.SpineBase, JointType.HipRight }, - { JointType.SpineBase, JointType.HipLeft }, - - // Right Arm - { JointType.ShoulderRight, JointType.ElbowRight }, - { JointType.ElbowRight, JointType.WristRight }, - { JointType.WristRight, JointType.HandRight }, - { JointType.HandRight, JointType.HandTipRight }, - { JointType.WristRight, JointType.ThumbRight }, - - // Left Arm - { JointType.ShoulderLeft, JointType.ElbowLeft }, - { JointType.ElbowLeft, JointType.WristLeft }, - { JointType.WristLeft, JointType.HandLeft }, - { JointType.HandLeft, JointType.HandTipLeft }, - { JointType.WristLeft, JointType.ThumbLeft }, - - // Right Leg - { JointType.HipRight, JointType.KneeRight }, - { JointType.KneeRight, JointType.AnkleRight }, - { JointType.AnkleRight, JointType.FootRight }, - - // Left Leg - { JointType.HipLeft, JointType.KneeLeft }, - { JointType.KneeLeft, JointType.AnkleLeft }, - { JointType.AnkleLeft, JointType.FootLeft }, - }; - - // pre-populate list of bones that are non-visible initially - foreach (var bone in this.Bones) - { - this.BoneLines.Add(bone, new Line() - { - Stroke = new SolidColorBrush(BodyColor), - Visibility = Visibility.Collapsed - }); - } - } - } - - public class TupleList : List> - { - public void Add(T1 item, T2 item2) - { - this.Add(new Tuple(item, item2)); - } - } - -} diff --git a/Kinect2Sample.Lab7/Kinect2Sample/DisplayTypeToVisibilityConverter.cs b/Kinect2Sample.Lab7/Kinect2Sample/DisplayTypeToVisibilityConverter.cs deleted file mode 100644 index 1b2c5d0..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/DisplayTypeToVisibilityConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Data; - -namespace Kinect2Sample -{ - class DisplayTypeToVisibilityConverter :IValueConverter - { - public object Convert(object value, Type targetType, object parameter, string language) - { - String boundString = Enum.GetName(typeof(DisplayFrameType), value); - String matchString = (String)parameter; - - if (String.Equals(boundString, matchString)) - { - return Visibility.Visible; - } - else - { - return Visibility.Collapsed; - } - } - - public object ConvertBack(object value, Type targetType, object parameter, string language) - { - throw new NotImplementedException(); - } - } -} diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample.Lab7/Kinect2Sample/Kinect2Sample.csproj deleted file mode 100644 index b80bb1f..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/Kinect2Sample.csproj +++ /dev/null @@ -1,121 +0,0 @@ - - - - - Debug - AnyCPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F} - AppContainerExe - Properties - Kinect2Sample - Kinect2Sample - en-US - 8.1 - 12 - 512 - {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Kinect2Sample_TemporaryKey.pfx - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x64 - false - prompt - true - true - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x64 - false - prompt - true - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x86 - false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x86 - false - prompt - true - - - - App.xaml - - - - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - Microsoft Visual C++ 2013 Runtime Package for Windows - - - WindowsPreview.Kinect - - - - - - - 12.0 - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx b/Kinect2Sample.Lab7/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx deleted file mode 100644 index 7cb3591..0000000 Binary files a/Kinect2Sample.Lab7/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx and /dev/null differ diff --git a/Kinect2Sample.Lab7/Kinect2Sample/MainPage.xaml b/Kinect2Sample.Lab7/Kinect2Sample/MainPage.xaml deleted file mode 100644 index adfd6f6..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/MainPage.xaml +++ /dev/null @@ -1,89 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Kinect2Sample.Lab7/Kinect2Sample/MainPage.xaml.cs b/Kinect2Sample.Lab7/Kinect2Sample/MainPage.xaml.cs deleted file mode 100644 index abd69f5..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/MainPage.xaml.cs +++ /dev/null @@ -1,728 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Media.Imaging; -using Windows.UI.Xaml.Navigation; -using WindowsPreview.Kinect; -using System.ComponentModel; -using Windows.Storage.Streams; -using System.Runtime.InteropServices; -using System.Diagnostics; -using Windows.UI.Xaml.Shapes; - -namespace Kinect2Sample -{ - public enum DisplayFrameType - { - Infrared, - Color, - Depth, - BodyMask, - BodyJoints, - BackgroundRemoved - } - - public sealed partial class MainPage : Page, INotifyPropertyChanged - { - private const DisplayFrameType DEFAULT_DISPLAYFRAMETYPE = DisplayFrameType.Infrared; - - /// - /// The highest value that can be returned in the InfraredFrame. - /// It is cast to a float for readability in the visualization code. - /// - private const float InfraredSourceValueMaximum = (float)ushort.MaxValue; - - /// - /// Used to set the lower limit, post processing, of the - /// infrared data that we will render. - /// Increasing or decreasing this value sets a brightness - /// "wall" either closer or further away. - /// - private const float InfraredOutputValueMinimum = 0.01f; - - /// - /// The upper limit, post processing, of the - /// infrared data that will render. - /// - private const float InfraredOutputValueMaximum = 1.0f; - - /// - /// The InfraredSceneValueAverage value specifies the average infrared - /// value of the scene. This value was selected by analyzing the average - /// pixel intensity for a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneValueAverage = 0.08f; - - /// - /// The InfraredSceneStandardDeviations value specifies the number of - /// standard deviations to apply to InfraredSceneValueAverage. - /// This value was selected by analyzing data from a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneStandardDeviations = 3.0f; - - // Size of the RGB pixel in the bitmap - private const int BytesPerPixel = 4; - - private KinectSensor kinectSensor = null; - private string statusText = null; - private WriteableBitmap bitmap = null; - private FrameDescription currentFrameDescription; - private DisplayFrameType currentDisplayFrameType; - private MultiSourceFrameReader multiSourceFrameReader = null; - private CoordinateMapper coordinateMapper = null; - private BodiesManager bodiesManager = null; - - //Infrared Frame - private ushort[] infraredFrameData = null; - private byte[] infraredPixels = null; - - //Depth Frame - private ushort[] depthFrameData = null; - private byte[] depthPixels = null; - private ushort depthMax = 8000; - - //BodyMask Frames - private DepthSpacePoint[] colorMappedToDepthPoints = null; - - //Body Joints are drawn here - private Canvas drawingCanvas; - - public event PropertyChangedEventHandler PropertyChanged; - public string StatusText - { - get { return this.statusText; } - set - { - if (this.statusText != value) - { - this.statusText = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); - } - } - } - } - - public FrameDescription CurrentFrameDescription - { - get { return this.currentFrameDescription; } - set - { - if (this.currentFrameDescription != value) - { - this.currentFrameDescription = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentFrameDescription")); - } - } - } - } - - public DisplayFrameType CurrentDisplayFrameType - { - get { return this.currentDisplayFrameType; } - set - { - if (this.currentDisplayFrameType != value) - { - this.currentDisplayFrameType = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentDisplayFrameType")); - } - } - } - } - - public ushort DepthMax - { - get { return this.depthMax; } - set - { - if (this.depthMax != value) - { - this.depthMax = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("DepthMax")); - } - } - } - } - - public MainPage() - { - // one sensor is currently supported - this.kinectSensor = KinectSensor.GetDefault(); - - SetupCurrentDisplay(DEFAULT_DISPLAYFRAMETYPE); - - this.coordinateMapper = this.kinectSensor.CoordinateMapper; - - this.multiSourceFrameReader = this.kinectSensor.OpenMultiSourceFrameReader(FrameSourceTypes.Infrared | FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.BodyIndex | FrameSourceTypes.Body); - - this.multiSourceFrameReader.MultiSourceFrameArrived += this.Reader_MultiSourceFrameArrived; - - // set IsAvailableChanged event notifier - this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; - - // use the window object as the view model in this simple example - this.DataContext = this; - - // open the sensor - this.kinectSensor.Open(); - - this.InitializeComponent(); - } - - private void SetupCurrentDisplay(DisplayFrameType newDisplayFrameType) - { - CurrentDisplayFrameType = newDisplayFrameType; - // Frames used by more than one type are declared outside the switch - FrameDescription colorFrameDescription = null; - FrameDescription depthFrameDescription = null; - // reset the display methods - if (this.BodyJointsGrid != null) - { - this.BodyJointsGrid.Visibility = Visibility.Collapsed; - } - if (this.FrameDisplayImage != null) - { - this.FrameDisplayImage.Source = null; - } - switch (CurrentDisplayFrameType) - { - case DisplayFrameType.Infrared: - FrameDescription infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription; - this.CurrentFrameDescription = infraredFrameDescription; - // allocate space to put the pixels being received and converted - this.infraredFrameData = new ushort[infraredFrameDescription.Width * infraredFrameDescription.Height]; - this.infraredPixels = new byte[infraredFrameDescription.Width * infraredFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(infraredFrameDescription.Width, infraredFrameDescription.Height); - break; - - case DisplayFrameType.Color: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // create the bitmap to display - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.Depth: - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - this.CurrentFrameDescription = depthFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.depthPixels = new byte[depthFrameDescription.Width * depthFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(depthFrameDescription.Width, depthFrameDescription.Height); - break; - - case DisplayFrameType.BodyMask: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.BodyJoints: - // instantiate a new Canvas - this.drawingCanvas = new Canvas(); - // set the clip rectangle to prevent rendering outside the canvas - this.drawingCanvas.Clip = new RectangleGeometry(); - this.drawingCanvas.Clip.Rect = new Rect(0.0, 0.0, this.BodyJointsGrid.Width, this.BodyJointsGrid.Height); - this.drawingCanvas.Width = this.BodyJointsGrid.Width; - this.drawingCanvas.Height = this.BodyJointsGrid.Height; - // reset the body joints grid - this.BodyJointsGrid.Visibility = Visibility.Visible; - this.BodyJointsGrid.Children.Clear(); - // add canvas to DisplayGrid - this.BodyJointsGrid.Children.Add(this.drawingCanvas); - bodiesManager = new BodiesManager(this.coordinateMapper, this.drawingCanvas, this.kinectSensor.BodyFrameSource.BodyCount); - break; - - case DisplayFrameType.BackgroundRemoved: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - // Actual current frame is going to be a map of depth and color, choosing the larger to display(color) - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - default: - break; - } - } - - private void Sensor_IsAvailableChanged(KinectSensor sender, IsAvailableChangedEventArgs args) - { - this.StatusText = this.kinectSensor.IsAvailable ? "Running" : "Not Available"; - } - - private void Reader_MultiSourceFrameArrived(MultiSourceFrameReader sender, MultiSourceFrameArrivedEventArgs e) - { - MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame(); - - // If the Frame has expired by the time we process this event, return. - if (multiSourceFrame == null) - { - return; - } - DepthFrame depthFrame = null; - ColorFrame colorFrame = null; - InfraredFrame infraredFrame = null; - BodyFrame bodyFrame = null; - BodyIndexFrame bodyIndexFrame = null; - IBuffer depthFrameDataBuffer = null; - IBuffer bodyIndexFrameData = null; - // Com interface for unsafe byte manipulation - IBufferByteAccess bufferByteAccess = null; - - switch (CurrentDisplayFrameType) - { - case DisplayFrameType.Infrared: - using (infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame()) - { - ShowInfraredFrame(infraredFrame); - } - break; - case DisplayFrameType.Color: - using (colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame()) - { - ShowColorFrame(colorFrame); - } - break; - case DisplayFrameType.Depth: - using (depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame()) - { - ShowDepthFrame(depthFrame); - } - break; - case DisplayFrameType.BodyMask: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - bodyIndexFrame = multiSourceFrame.BodyIndexFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null) || (bodyIndexFrame == null)) - { - return; - } - - // Access the depth frame data directly via LockImageBuffer to avoid making a copy - depthFrameDataBuffer = depthFrame.LockImageBuffer(); - this.coordinateMapper.MapColorFrameToDepthSpaceUsingIBuffer(depthFrameDataBuffer, this.colorMappedToDepthPoints); - // Process Color - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - // Access the body index frame data directly via LockImageBuffer to avoid making a copy - bodyIndexFrameData = bodyIndexFrame.LockImageBuffer(); - ShowMappedBodyFrame(depthFrame.FrameDescription.Width, depthFrame.FrameDescription.Height, bodyIndexFrameData, bufferByteAccess); - } - finally - { - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - if (bodyIndexFrame != null) - { - bodyIndexFrame.Dispose(); - } - - if (depthFrameDataBuffer != null) - { - // We must force a release of the IBuffer in order to ensure that we have dropped all references to it. - System.Runtime.InteropServices.Marshal.ReleaseComObject(depthFrameDataBuffer); - } - if (bodyIndexFrameData != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bodyIndexFrameData); - } - if (bufferByteAccess != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bufferByteAccess); - } - - } - break; - case DisplayFrameType.BodyJoints: - using (bodyFrame = multiSourceFrame.BodyFrameReference.AcquireFrame()) - { - ShowBodyJoints(bodyFrame); - } - break; - case DisplayFrameType.BackgroundRemoved: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null)) - { - return; - } - depthFrame.CopyFrameDataToArray(depthFrameData); - this.coordinateMapper.MapColorFrameToDepthSpace(depthFrameData, this.colorMappedToDepthPoints); - // Process Color. - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - - ShowMappedColorBackgroundRemoved(colorMappedToDepthPoints, depthFrameData, depthFrame.FrameDescription); - } - finally - { - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - } - break; - default: - break; - } - } - - unsafe private void ShowMappedColorBackgroundRemoved(DepthSpacePoint[] colorMappedToDepthPoints, ushort[] depthFrameData, FrameDescription frameDescription) - { - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - int depthWidth = frameDescription.Width; - int depthHeight = frameDescription.Height; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - for (int colorIndex = 0; colorIndex < this.colorMappedToDepthPoints.Length; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPoints[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPoints[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - if (depthFrameData[depthIndex] < DepthMax) - { - continue; - } - } - } - // no matching depth. zero out the pixel. - bitmapPixelsPointer[colorIndex] = 0; - } - } - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - - private void ShowBodyJoints(BodyFrame bodyFrame) - { - Body[] bodies = new Body[this.kinectSensor.BodyFrameSource.BodyCount]; - bool dataReceived = false; - if (bodyFrame != null) - { - bodyFrame.GetAndRefreshBodyData(bodies); - dataReceived = true; - } - - if (dataReceived) - { - this.bodiesManager.UpdateBodiesAndEdges(bodies); - } - } - - unsafe private void ShowMappedBodyFrame(int depthWidth, int depthHeight, IBuffer bodyIndexFrameData, IBufferByteAccess bodyIndexByteAccess) - { - bodyIndexByteAccess = (IBufferByteAccess)bodyIndexFrameData; - byte* bodyIndexBytes = null; - bodyIndexByteAccess.Buffer(out bodyIndexBytes); - - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = this.colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - int colorMappedLength = this.colorMappedToDepthPoints.Length; - for (int colorIndex = 0; colorIndex < colorMappedLength; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPointsPointer[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPointsPointer[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - // If we are tracking a body for the current pixel, do not zero out the pixel - if (bodyIndexBytes[depthIndex] != 0xff) - { - // this bodyIndexByte is good and is a body, loop again. - continue; - } - } - } - // this pixel does not correspond to a body so make it black and transparent - bitmapPixelsPointer[colorIndex] = 0; - } - } - - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - - } - - private void ShowDepthFrame(DepthFrame depthFrame) - { - bool depthFrameProcessed = false; - ushort minDepth = 0; - ushort maxDepth = 0; - - if (depthFrame != null) - { - FrameDescription depthFrameDescription = depthFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((depthFrameDescription.Width * depthFrameDescription.Height) - == this.infraredFrameData.Length) && - (depthFrameDescription.Width == this.bitmap.PixelWidth) && - (depthFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - depthFrame.CopyFrameDataToArray(this.depthFrameData); - - minDepth = depthFrame.DepthMinReliableDistance; - maxDepth = depthFrame.DepthMaxReliableDistance; - //maxDepth = 8000; - - depthFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (depthFrameProcessed) - { - ConvertDepthDataToPixels(minDepth, maxDepth); - RenderPixelArray(this.depthPixels); - } - } - - private void ConvertDepthDataToPixels(ushort minDepth, ushort maxDepth) - { - int colorPixelIndex = 0; - // Shape the depth to the range of a byte - int mapDepthToByte = maxDepth / 256; - - for (int i = 0; i < this.depthFrameData.Length; ++i) - { - // Get the depth for this pixel - ushort depth = this.depthFrameData[i]; - - // To convert to a byte, we're mapping the depth value to the byte range. - // Values outside the reliable depth range are mapped to 0 (black). - byte intensity = (byte)(depth >= minDepth && - depth <= maxDepth ? (depth / mapDepthToByte) : 0); - - this.depthPixels[colorPixelIndex++] = intensity; //Blue - this.depthPixels[colorPixelIndex++] = intensity; //Green - this.depthPixels[colorPixelIndex++] = intensity; //Red - this.depthPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void ShowColorFrame(ColorFrame colorFrame) - { - bool colorFrameProcessed = false; - - if (colorFrame != null) - { - FrameDescription colorFrameDescription = colorFrame.FrameDescription; - - // verify data and write the new color frame data to the Writeable bitmap - if ((colorFrameDescription.Width == this.bitmap.PixelWidth) && (colorFrameDescription.Height == this.bitmap.PixelHeight)) - { - if (colorFrame.RawColorImageFormat == ColorImageFormat.Bgra) - { - colorFrame.CopyRawFrameDataToBuffer(this.bitmap.PixelBuffer); - } - else - { - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - } - - colorFrameProcessed = true; - } - } - - if (colorFrameProcessed) - { - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - } - - private void ShowInfraredFrame(InfraredFrame infraredFrame) - { - bool infraredFrameProcessed = false; - - if (infraredFrame != null) - { - FrameDescription infraredFrameDescription = infraredFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((infraredFrameDescription.Width * infraredFrameDescription.Height) - == this.infraredFrameData.Length) && - (infraredFrameDescription.Width == this.bitmap.PixelWidth) && - (infraredFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - infraredFrame.CopyFrameDataToArray(this.infraredFrameData); - - infraredFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (infraredFrameProcessed) - { - this.ConvertInfraredDataToPixels(); - this.RenderPixelArray(this.infraredPixels); - } - } - - private void ConvertInfraredDataToPixels() - { - // Convert the infrared to RGB - int colorPixelIndex = 0; - for (int i = 0; i < this.infraredFrameData.Length; ++i) - { - // normalize the incoming infrared data (ushort) to a float ranging from - // [InfraredOutputValueMinimum, InfraredOutputValueMaximum] by - // 1. dividing the incoming value by the source maximum value - float intensityRatio = (float)this.infraredFrameData[i] / InfraredSourceValueMaximum; - - // 2. dividing by the (average scene value * standard deviations) - intensityRatio /= InfraredSceneValueAverage * InfraredSceneStandardDeviations; - - // 3. limiting the value to InfraredOutputValueMaximum - intensityRatio = Math.Min(InfraredOutputValueMaximum, intensityRatio); - - // 4. limiting the lower value InfraredOutputValueMinimum - intensityRatio = Math.Max(InfraredOutputValueMinimum, intensityRatio); - - // 5. converting the normalized value to a byte and using the result - // as the RGB components required by the image - byte intensity = (byte)(intensityRatio * 255.0f); - this.infraredPixels[colorPixelIndex++] = intensity; //Blue - this.infraredPixels[colorPixelIndex++] = intensity; //Green - this.infraredPixels[colorPixelIndex++] = intensity; //Red - this.infraredPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void RenderPixelArray(byte[] pixels) - { - pixels.CopyTo(this.bitmap.PixelBuffer); - this.bitmap.Invalidate(); - this.FrameDisplayImage.Source = this.bitmap; - } - - - - private void InfraredButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Infrared); - } - - private void ColorButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Color); - } - - private void DepthButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Depth); - } - - private void BodyMaskButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyMask); - } - - private void BodyJointsButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyJoints); - } - - private void BackgroundButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BackgroundRemoved); - } - - - [Guid("905a0fef-bc53-11df-8c49-001e4fc686da"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IBufferByteAccess - { - unsafe void Buffer(out byte* pByte); - } - - - - } -} diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Package.appxmanifest b/Kinect2Sample.Lab7/Kinect2Sample/Package.appxmanifest deleted file mode 100644 index 297bc48..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/Package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Kinect2Sample - Jesse - Assets\StoreLogo.png - - - 6.3.0 - 6.3.0 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab7/Kinect2Sample/Properties/AssemblyInfo.cs b/Kinect2Sample.Lab7/Kinect2Sample/Properties/AssemblyInfo.cs deleted file mode 100644 index 991ad4a..0000000 --- a/Kinect2Sample.Lab7/Kinect2Sample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Kinect2Sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Kinect2Sample")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/Kinect2Sample.Lab8/Kinect2Sample.sln b/Kinect2Sample.Lab8/Kinect2Sample.sln deleted file mode 100644 index 1178479..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kinect2Sample", "Kinect2Sample\Kinect2Sample.csproj", "{10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Build.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Deploy.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.ActiveCfg = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Build.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Deploy.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.ActiveCfg = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Kinect2Sample.Lab8/Kinect2Sample/App.xaml b/Kinect2Sample.Lab8/Kinect2Sample/App.xaml deleted file mode 100644 index b34ea9d..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/App.xaml +++ /dev/null @@ -1,7 +0,0 @@ - - - diff --git a/Kinect2Sample.Lab8/Kinect2Sample/App.xaml.cs b/Kinect2Sample.Lab8/Kinect2Sample/App.xaml.cs deleted file mode 100644 index 1692c86..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/App.xaml.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 - -namespace Kinect2Sample -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = true; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - // Set the default language - rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/Background.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/Background.png deleted file mode 100644 index 44e6e19..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/Background.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatEye_left_closed.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatEye_left_closed.png deleted file mode 100644 index 32b7544..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatEye_left_closed.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatEye_left_open.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatEye_left_open.png deleted file mode 100644 index 62c7ac0..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatEye_left_open.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatNose.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatNose.png deleted file mode 100644 index 8732b28..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/CatNose.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/Logo.scale-100.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/Logo.scale-100.png deleted file mode 100644 index e26771c..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/Logo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/SmallLogo.scale-100.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/SmallLogo.scale-100.png deleted file mode 100644 index 1eb0d9d..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/SmallLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/SplashScreen.scale-100.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/SplashScreen.scale-100.png deleted file mode 100644 index c951e03..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/SplashScreen.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Assets/StoreLogo.scale-100.png b/Kinect2Sample.Lab8/Kinect2Sample/Assets/StoreLogo.scale-100.png deleted file mode 100644 index dcb6727..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Assets/StoreLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/BodiesManager.cs b/Kinect2Sample.Lab8/Kinect2Sample/BodiesManager.cs deleted file mode 100644 index ba728a6..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/BodiesManager.cs +++ /dev/null @@ -1,492 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Foundation; -using Windows.UI; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - public class BodiesManager - { - /// - /// Radius of drawn hand circles - /// - private const double HighConfidenceHandSize = 40; - - /// - /// Radius of drawn hand circles - /// - private const double LowConfidenceHandSize = 20; - - /// - /// Thickness of drawn joint lines - /// - private const double JointThickness = 8.0; - - /// - /// Thickness of seen bone lines - /// - private const double TrackedBoneThickness = 4.0; - - /// - /// Thickness of inferred joint lines - /// - private const double InferredBoneThickness = 1.0; - - /// - /// Thickness of clip edge rectangles - /// - private const double ClipBoundsThickness = 5; - - /// - /// Constant for clamping Z values of camera space points from being negative - /// - private const float InferredZPositionClamp = 0.1f; - - private CoordinateMapper coordinateMapper; - private Canvas drawingCanvas; - - private Rectangle LeftClipEdge; - private Rectangle RightClipEdge; - private Rectangle TopClipEdge; - private Rectangle BottomClipEdge; - - /// - /// List of BodyInfo objects for each potential body - /// - private BodyInfo[] bodyInfos; - - /// - /// List of colors for each body tracked - /// - private List bodyColors; - - private int BodyCount - { - set - { - if (value == 0) - { - this.bodyInfos = null; - return; - } - - // creates instances of BodyInfo objects for potential number of bodies - if (this.bodyInfos == null || this.bodyInfos.Length != value) - { - this.bodyInfos = new BodyInfo[value]; - - for (int bodyIndex = 0; bodyIndex < value; bodyIndex++) - { - this.bodyInfos[bodyIndex] = new BodyInfo(this.bodyColors[bodyIndex], JointThickness); - } - } - } - - get { return this.bodyInfos == null ? 0 : this.bodyInfos.Length; } - } - - /// - /// Maps bodies and joints to render them in a canvas. - /// - /// The current co-ordinate mapper from the Kinect Sensor - /// The canvas upon which the joints and bones are drawn - /// The amount of bodies concurrently drawable - public BodiesManager(CoordinateMapper coordMapper, Canvas drawableCanvas, int bodyCount) - { - this.coordinateMapper = coordMapper; - this.drawingCanvas = drawableCanvas; - // populate body colors, one for each BodyIndex - this.bodyColors = new List - { - Colors.Red, - Colors.Orange, - Colors.Green, - Colors.Blue, - Colors.Indigo, - Colors.Violet - }; - - // sets total number of possible tracked bodies - // create ellipses and lines for drawing bodies - this.BodyCount = bodyCount; - - PopulateVisualJoints(); - } - - /// - /// Instantiate new objects for joints, bone lines, and clipped edge rectangles - /// - private void PopulateVisualJoints() - { - // create clipped edges and set to collapsed initially - this.LeftClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.RightClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.TopClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.BottomClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - foreach (var bodyInfo in this.bodyInfos) - { - // add left and right hand ellipses of all bodies to canvas - this.drawingCanvas.Children.Add(bodyInfo.HandLeftEllipse); - this.drawingCanvas.Children.Add(bodyInfo.HandRightEllipse); - - // add joint ellipses of all bodies to canvas - foreach (var joint in bodyInfo.JointPoints) - { - this.drawingCanvas.Children.Add(joint.Value); - } - - // add bone lines of all bodies to canvas - foreach (var bone in bodyInfo.Bones) - { - this.drawingCanvas.Children.Add(bodyInfo.BoneLines[bone]); - } - } - - // add clipped edges rectanges to main canvas - this.drawingCanvas.Children.Add(this.LeftClipEdge); - this.drawingCanvas.Children.Add(this.RightClipEdge); - this.drawingCanvas.Children.Add(this.TopClipEdge); - this.drawingCanvas.Children.Add(this.BottomClipEdge); - - // position the clipped edges - Canvas.SetLeft(this.LeftClipEdge, 0); - Canvas.SetTop(this.LeftClipEdge, 0); - Canvas.SetLeft(this.RightClipEdge, this.drawingCanvas.Width - ClipBoundsThickness); - Canvas.SetTop(this.RightClipEdge, 0); - Canvas.SetLeft(this.TopClipEdge, 0); - Canvas.SetTop(this.TopClipEdge, 0); - Canvas.SetLeft(this.BottomClipEdge, 0); - Canvas.SetTop(this.BottomClipEdge, this.drawingCanvas.Height - ClipBoundsThickness); - } - - /// - /// Updates all elipses and lines representing joints and bones - /// with the latest tracked bodies. - /// - /// An array containing body data. - internal void UpdateBodiesAndEdges(Body[] bodies) - { - bool hasTrackedBody = false; - // iterate through each body - for (int bodyIndex = 0; bodyIndex < bodies.Length; bodyIndex++) - { - Body body = bodies[bodyIndex]; - - if (body.IsTracked) - { - // check if this body clips an edge - this.UpdateClippedEdges(body, hasTrackedBody); - - this.UpdateBody(body, bodyIndex); - - hasTrackedBody = true; - } - else - { - // collapse this body from canvas as it goes out of view - this.ClearBody(bodyIndex); - } - } - - if (!hasTrackedBody) - { - // clear clipped edges if no bodies are tracked - this.ClearClippedEdges(); - } - } - - /// - /// Update body data for each body that is tracked. - /// - /// body for getting joint info - /// index for body we are currently updating - internal void UpdateBody(Body body, int bodyIndex) - { - IReadOnlyDictionary joints = body.Joints; - var jointPointsInDepthSpace = new Dictionary(); - - var bodyInfo = this.bodyInfos[bodyIndex]; - - // update all joints - foreach (var jointType in body.Joints.Keys) - { - // sometimes the depth(Z) of an inferred joint may show as negative - // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity) - CameraSpacePoint position = body.Joints[jointType].Position; - if (position.Z < 0) - { - position.Z = InferredZPositionClamp; - } - - // map joint position to depth space - DepthSpacePoint depthSpacePoint = coordinateMapper.MapCameraPointToDepthSpace(position); - jointPointsInDepthSpace[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y); - - // modify the joint's visibility and location - this.UpdateJoint(bodyInfo.JointPoints[jointType], joints[jointType], jointPointsInDepthSpace[jointType]); - - // modify hand ellipse colors based on hand states - // modity hand ellipse sizes based on tracking confidences - if (jointType == JointType.HandRight) - { - this.UpdateHand(bodyInfo.HandRightEllipse, body.HandRightState, body.HandRightConfidence, jointPointsInDepthSpace[jointType]); - } - - if (jointType == JointType.HandLeft) - { - this.UpdateHand(bodyInfo.HandLeftEllipse, body.HandLeftState, body.HandLeftConfidence, jointPointsInDepthSpace[jointType]); - } - } - - // update all bones - foreach (var bone in bodyInfo.Bones) - { - this.UpdateBone(bodyInfo.BoneLines[bone], joints[bone.Item1], joints[bone.Item2], - jointPointsInDepthSpace[bone.Item1], - jointPointsInDepthSpace[bone.Item2]); - } - } - /// - /// Updates hand state ellipses depending on tracking state and it's confidence. - /// - /// ellipse representing handstate - /// open, closed, or lasso - /// confidence of handstate - /// location of handjoint - private void UpdateHand(Ellipse ellipse, HandState handState, TrackingConfidence trackingConfidence, Point point) - { - ellipse.Fill = new SolidColorBrush(this.HandStateToColor(handState)); - - // draw handstate ellipse based on tracking confidence - ellipse.Width = ellipse.Height = (trackingConfidence == TrackingConfidence.Low) ? LowConfidenceHandSize : HighConfidenceHandSize; - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - - // don't draw handstate if hand joints are not tracked - if (!Double.IsInfinity(point.X) && !Double.IsInfinity(point.Y)) - { - Canvas.SetLeft(ellipse, point.X - ellipse.Width / 2); - Canvas.SetTop(ellipse, point.Y - ellipse.Width / 2); - } - } - - /// - /// Update a joint. - /// - /// - /// - /// - private void UpdateJoint(Ellipse ellipse, Joint joint, Point point) - { - TrackingState trackingState = joint.TrackingState; - - // only draw if joint is tracked or inferred - if (trackingState != TrackingState.NotTracked) - { - if (trackingState == TrackingState.Tracked) - { - ellipse.Fill = new SolidColorBrush(Colors.Green); - } - else - { - // inferred joints are yellow - ellipse.Fill = new SolidColorBrush(Colors.Yellow); - } - - Canvas.SetLeft(ellipse, point.X - JointThickness / 2); - Canvas.SetTop(ellipse, point.Y - JointThickness / 2); - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else - { - ellipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Update a bone line. - /// - /// line representing a bone line - /// start joint of bone line - /// end joint of bone line - /// location of start joint - /// location of end joint - private void UpdateBone(Line line, Joint startJoint, Joint endJoint, Point startPoint, Point endPoint) - { - // don't draw if neither joints are tracked - if (startJoint.TrackingState == TrackingState.NotTracked || endJoint.TrackingState == TrackingState.NotTracked) - { - line.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - return; - } - - // all lines are inferred thickness unless both joints are tracked - line.StrokeThickness = InferredBoneThickness; - - if (startJoint.TrackingState == TrackingState.Tracked && - endJoint.TrackingState == TrackingState.Tracked) - { - line.StrokeThickness = TrackedBoneThickness; - } - - line.Visibility = Windows.UI.Xaml.Visibility.Visible; - - line.X1 = startPoint.X; - line.Y1 = startPoint.Y; - line.X2 = endPoint.X; - line.Y2 = endPoint.Y; - } - - /// - /// Draws indicators to show which edges are clipping body data. - /// - /// body to draw clipping information for - /// bool to determine if another body is triggering a clipped edge - private void UpdateClippedEdges(Body body, bool hasTrackedBody) - { - // BUG (waiting for confirmation): - // Clip dectection works differently for top and right edges compared to left and bottom edges - // due to the current joint confidence model. This is an ST issue. - // Joints become inferred immediately as they touch the left/bottom edges and clip detection triggers. - // Joints squish on the right/top edges and clip detection doesn't trigger until more joints of - // the body goes out of view (e.g all hand joints vs only handtip). - - FrameEdges clippedEdges = body.ClippedEdges; - - if (clippedEdges.HasFlag(FrameEdges.Left)) - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - // don't clear this edge if another body is triggering clipped edge - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Right)) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Top)) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Bottom)) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Select color of hand state - /// - /// - /// - private Color HandStateToColor(HandState handState) - { - switch (handState) - { - case HandState.Open: - return Colors.Green; - - case HandState.Closed: - return Colors.Red; - - case HandState.Lasso: - return Colors.Blue; - } - - return Colors.Transparent; - } - - /// - /// Collapse the body from the canvas. - /// - /// - private void ClearBody(int bodyIndex) - { - var bodyInfo = this.bodyInfos[bodyIndex]; - - // collapse all joint ellipses - foreach (var joint in bodyInfo.JointPoints) - { - joint.Value.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse all bone lines - foreach (var bone in bodyInfo.Bones) - { - bodyInfo.BoneLines[bone].Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse handstate ellipses - bodyInfo.HandLeftEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - bodyInfo.HandRightEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - /// - /// Clear all clipped edges. - /// - private void ClearClippedEdges() - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } -} diff --git a/Kinect2Sample.Lab8/Kinect2Sample/BodyInfo.cs b/Kinect2Sample.Lab8/Kinect2Sample/BodyInfo.cs deleted file mode 100644 index 2f03930..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/BodyInfo.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - /// - /// BodyInfo class that contains joint ellipses, handstate ellipses, lines for bones between two joints. - /// - public class BodyInfo - { - public bool Updated { get; set; } - - public Color BodyColor { get; set; } - - // ellipse representing left handstate - public Ellipse HandLeftEllipse { get; set; } - - // ellipse representing right handstate - public Ellipse HandRightEllipse { get; set; } - - // dictionary of all joints in a body - public Dictionary JointPoints { get; private set; } - - // definition of bones - public TupleList Bones { get; private set; } - - // collection of bones associated with the line object - public Dictionary, Line> BoneLines { get; private set; } - - public BodyInfo(Color bodyColor, double jointThickness) - { - this.BodyColor = bodyColor; - - // create hand state ellipses - this.HandLeftEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.HandRightEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - // a joint defined as a jointType with a point location in XY space represented by an ellipse - this.JointPoints = new Dictionary(); - - // pre-populate list of joints and set to non-visible initially - foreach (JointType jointType in Enum.GetValues(typeof(JointType))) - { - this.JointPoints.Add(jointType, new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed, - Fill = new SolidColorBrush(BodyColor), - Width = jointThickness, - Height = jointThickness - }); - } - - // collection of bones - this.BoneLines = new Dictionary, Line>(); - - // a bone defined as a line between two joints - this.Bones = new TupleList - { - // Torso - { JointType.Head, JointType.Neck }, - { JointType.Neck, JointType.SpineShoulder }, - { JointType.SpineShoulder, JointType.SpineMid }, - { JointType.SpineMid, JointType.SpineBase }, - { JointType.SpineShoulder, JointType.ShoulderRight }, - { JointType.SpineShoulder, JointType.ShoulderLeft }, - { JointType.SpineBase, JointType.HipRight }, - { JointType.SpineBase, JointType.HipLeft }, - - // Right Arm - { JointType.ShoulderRight, JointType.ElbowRight }, - { JointType.ElbowRight, JointType.WristRight }, - { JointType.WristRight, JointType.HandRight }, - { JointType.HandRight, JointType.HandTipRight }, - { JointType.WristRight, JointType.ThumbRight }, - - // Left Arm - { JointType.ShoulderLeft, JointType.ElbowLeft }, - { JointType.ElbowLeft, JointType.WristLeft }, - { JointType.WristLeft, JointType.HandLeft }, - { JointType.HandLeft, JointType.HandTipLeft }, - { JointType.WristLeft, JointType.ThumbLeft }, - - // Right Leg - { JointType.HipRight, JointType.KneeRight }, - { JointType.KneeRight, JointType.AnkleRight }, - { JointType.AnkleRight, JointType.FootRight }, - - // Left Leg - { JointType.HipLeft, JointType.KneeLeft }, - { JointType.KneeLeft, JointType.AnkleLeft }, - { JointType.AnkleLeft, JointType.FootLeft }, - }; - - // pre-populate list of bones that are non-visible initially - foreach (var bone in this.Bones) - { - this.BoneLines.Add(bone, new Line() - { - Stroke = new SolidColorBrush(BodyColor), - Visibility = Visibility.Collapsed - }); - } - } - } - - public class TupleList : List> - { - public void Add(T1 item, T2 item2) - { - this.Add(new Tuple(item, item2)); - } - } - -} diff --git a/Kinect2Sample.Lab8/Kinect2Sample/DisplayTypeToVisibilityConverter.cs b/Kinect2Sample.Lab8/Kinect2Sample/DisplayTypeToVisibilityConverter.cs deleted file mode 100644 index 1b2c5d0..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/DisplayTypeToVisibilityConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Data; - -namespace Kinect2Sample -{ - class DisplayTypeToVisibilityConverter :IValueConverter - { - public object Convert(object value, Type targetType, object parameter, string language) - { - String boundString = Enum.GetName(typeof(DisplayFrameType), value); - String matchString = (String)parameter; - - if (String.Equals(boundString, matchString)) - { - return Visibility.Visible; - } - else - { - return Visibility.Collapsed; - } - } - - public object ConvertBack(object value, Type targetType, object parameter, string language) - { - throw new NotImplementedException(); - } - } -} diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample.Lab8/Kinect2Sample/Kinect2Sample.csproj deleted file mode 100644 index 2409758..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/Kinect2Sample.csproj +++ /dev/null @@ -1,110 +0,0 @@ - - - - - Debug - AnyCPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F} - AppContainerExe - Properties - Kinect2Sample - Kinect2Sample - en-US - 8.1 - 12 - 512 - {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Kinect2Sample_TemporaryKey.pfx - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x64 - false - prompt - true - true - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x64 - false - prompt - true - - - - App.xaml - - - - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - Microsoft.Kinect.Face - - - Microsoft Visual C++ 2013 Runtime Package for Windows - - - WindowsPreview.Kinect - - - - - - - - Libraries\x64\KinectFaceStore.dll - - - - 12.0 - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx b/Kinect2Sample.Lab8/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx deleted file mode 100644 index 7cb3591..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Libraries/x64/KinectFaceStore.dll b/Kinect2Sample.Lab8/Kinect2Sample/Libraries/x64/KinectFaceStore.dll deleted file mode 100644 index 408b58a..0000000 Binary files a/Kinect2Sample.Lab8/Kinect2Sample/Libraries/x64/KinectFaceStore.dll and /dev/null differ diff --git a/Kinect2Sample.Lab8/Kinect2Sample/MainPage.xaml b/Kinect2Sample.Lab8/Kinect2Sample/MainPage.xaml deleted file mode 100644 index 58960c8..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/MainPage.xaml +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Kinect2Sample.Lab8/Kinect2Sample/MainPage.xaml.cs b/Kinect2Sample.Lab8/Kinect2Sample/MainPage.xaml.cs deleted file mode 100644 index 3c5d326..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/MainPage.xaml.cs +++ /dev/null @@ -1,918 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Media.Imaging; -using Windows.UI.Xaml.Navigation; -using WindowsPreview.Kinect; -using System.ComponentModel; -using Windows.Storage.Streams; -using System.Runtime.InteropServices; -using System.Diagnostics; -using Windows.UI.Xaml.Shapes; -using Windows.UI; -using KinectFace; -using Microsoft.Kinect.Face; - -namespace Kinect2Sample -{ - public enum DisplayFrameType - { - Infrared, - Color, - Depth, - BodyMask, - BodyJoints, - BackgroundRemoved, - FaceOnColor, - FaceOnInfrared - } - - public sealed partial class MainPage : Page, INotifyPropertyChanged - { - private const DisplayFrameType DEFAULT_DISPLAYFRAMETYPE = DisplayFrameType.Infrared; - - /// - /// The highest value that can be returned in the InfraredFrame. - /// It is cast to a float for readability in the visualization code. - /// - private const float InfraredSourceValueMaximum = (float)ushort.MaxValue; - - /// - /// Used to set the lower limit, post processing, of the - /// infrared data that we will render. - /// Increasing or decreasing this value sets a brightness - /// "wall" either closer or further away. - /// - private const float InfraredOutputValueMinimum = 0.01f; - - /// - /// The upper limit, post processing, of the - /// infrared data that will render. - /// - private const float InfraredOutputValueMaximum = 1.0f; - - /// - /// The InfraredSceneValueAverage value specifies the average infrared - /// value of the scene. This value was selected by analyzing the average - /// pixel intensity for a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneValueAverage = 0.08f; - - /// - /// The InfraredSceneStandardDeviations value specifies the number of - /// standard deviations to apply to InfraredSceneValueAverage. - /// This value was selected by analyzing data from a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneStandardDeviations = 3.0f; - - // Size of the RGB pixel in the bitmap - private const int BytesPerPixel = 4; - - private KinectSensor kinectSensor = null; - private string statusText = null; - private WriteableBitmap bitmap = null; - private FrameDescription currentFrameDescription; - private DisplayFrameType currentDisplayFrameType; - private MultiSourceFrameReader multiSourceFrameReader = null; - private CoordinateMapper coordinateMapper = null; - private BodiesManager bodiesManager = null; - - //Infrared Frame - private ushort[] infraredFrameData = null; - private byte[] infraredPixels = null; - - //Depth Frame - private ushort[] depthFrameData = null; - private byte[] depthPixels = null; - private ushort depthMax = 8000; - - //BodyMask Frames - private DepthSpacePoint[] colorMappedToDepthPoints = null; - - //Body Joints are drawn here - private Canvas drawingCanvas; - - //FaceManager library - private FaceManager faceManager; - private FaceFrameFeatures faceFrameFeatures; - - //Cat assets - private Image[] catEyeRightOpen, catEyeRightClosed, catEyeLeftOpen, catEyeLeftClosed, catNose; - - public event PropertyChangedEventHandler PropertyChanged; - public string StatusText - { - get { return this.statusText; } - set - { - if (this.statusText != value) - { - this.statusText = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); - } - } - } - } - - public FrameDescription CurrentFrameDescription - { - get { return this.currentFrameDescription; } - set - { - if (this.currentFrameDescription != value) - { - this.currentFrameDescription = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentFrameDescription")); - } - } - } - } - - public DisplayFrameType CurrentDisplayFrameType - { - get { return this.currentDisplayFrameType; } - set - { - if (this.currentDisplayFrameType != value) - { - this.currentDisplayFrameType = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentDisplayFrameType")); - } - } - } - } - - public ushort DepthMax - { - get { return this.depthMax; } - set - { - if (this.depthMax != value) - { - this.depthMax = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("DepthMax")); - } - } - } - } - - public MainPage() - { - // one sensor is currently supported - this.kinectSensor = KinectSensor.GetDefault(); - - this.coordinateMapper = this.kinectSensor.CoordinateMapper; - - this.multiSourceFrameReader = this.kinectSensor.OpenMultiSourceFrameReader(FrameSourceTypes.Infrared | FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.BodyIndex | FrameSourceTypes.Body); - - this.multiSourceFrameReader.MultiSourceFrameArrived += this.Reader_MultiSourceFrameArrived; - - // specify the required face frame results - // init with all the features so they are accessible later. - this.faceFrameFeatures = - FaceFrameFeatures.BoundingBoxInColorSpace - | FaceFrameFeatures.PointsInColorSpace - | FaceFrameFeatures.BoundingBoxInInfraredSpace - | FaceFrameFeatures.PointsInInfraredSpace - | FaceFrameFeatures.RotationOrientation - | FaceFrameFeatures.FaceEngagement - | FaceFrameFeatures.Glasses - | FaceFrameFeatures.Happy - | FaceFrameFeatures.LeftEyeClosed - | FaceFrameFeatures.RightEyeClosed - | FaceFrameFeatures.LookingAway - | FaceFrameFeatures.MouthMoved - | FaceFrameFeatures.MouthOpen; - - this.faceManager = new FaceManager(this.kinectSensor, this.faceFrameFeatures); - - // set IsAvailableChanged event notifier - this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; - - // use the window object as the view model in this simple example - this.DataContext = this; - - // open the sensor - this.kinectSensor.Open(); - - this.InitializeComponent(); - - // new - this.Loaded += MainPage_Loaded; - } - - void MainPage_Loaded(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DEFAULT_DISPLAYFRAMETYPE); - - SetupCatAssets(); - } - - private void SetupCatAssets() - { - ScaleTransform flipTransform = new ScaleTransform() { ScaleX = -1.0 }; - int bodyCount = kinectSensor.BodyFrameSource.BodyCount; - catEyeRightOpen = new Image[bodyCount]; - catEyeRightClosed = new Image[bodyCount]; - catEyeLeftOpen = new Image[bodyCount]; - catEyeLeftClosed = new Image[bodyCount]; - catNose = new Image[bodyCount]; - - for (int i = 0; i < kinectSensor.BodyFrameSource.BodyCount; i++) - { - catEyeRightOpen[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_open.png")), - Width = 30, - Height = 20, - RenderTransformOrigin = new Point(0.5, 0.5), - RenderTransform = flipTransform - }; - catEyeRightClosed[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_closed.png")), - Width = 30, - Height = 20, - RenderTransformOrigin = new Point(0.5, 0.5), - RenderTransform = flipTransform - }; - catEyeLeftOpen[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_open.png")), - Width = 30, - Height = 20 - }; - catEyeLeftClosed[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_closed.png")), - Width = 30, - Height = 20 - }; - catEyeLeftClosed[i].RenderTransformOrigin = new Point(0.5, 0.5); - catNose[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatNose.png")), - Width = 40, - Height = 25 - }; - } - } - - private void SetupCurrentDisplay(DisplayFrameType newDisplayFrameType) - { - CurrentDisplayFrameType = newDisplayFrameType; - // Frames used by more than one type are declared outside the switch - FrameDescription colorFrameDescription = null; - FrameDescription depthFrameDescription = null; - FrameDescription infraredFrameDescription = null; - // reset the display methods - FacePointsCanvas.Children.Clear(); - if (this.BodyJointsGrid != null) - { - this.BodyJointsGrid.Visibility = Visibility.Collapsed; - } - if (this.FrameDisplayImage != null) - { - this.FrameDisplayImage.Source = null; - } - switch (CurrentDisplayFrameType) - { - case DisplayFrameType.Infrared: - infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription; - this.CurrentFrameDescription = infraredFrameDescription; - // allocate space to put the pixels being received and converted - this.infraredFrameData = new ushort[infraredFrameDescription.Width * infraredFrameDescription.Height]; - this.infraredPixels = new byte[infraredFrameDescription.Width * infraredFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(infraredFrameDescription.Width, infraredFrameDescription.Height); - break; - - case DisplayFrameType.Color: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // create the bitmap to display - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.Depth: - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - this.CurrentFrameDescription = depthFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.depthPixels = new byte[depthFrameDescription.Width * depthFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(depthFrameDescription.Width, depthFrameDescription.Height); - break; - - case DisplayFrameType.BodyMask: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.BodyJoints: - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - // instantiate a new Canvas - this.drawingCanvas = new Canvas(); - // set the clip rectangle to prevent rendering outside the canvas - this.drawingCanvas.Clip = new RectangleGeometry(); - this.drawingCanvas.Clip.Rect = new Rect(0.0, 0.0, this.BodyJointsGrid.Width, this.BodyJointsGrid.Height); - this.drawingCanvas.Width = this.BodyJointsGrid.Width; - this.drawingCanvas.Height = this.BodyJointsGrid.Height; - // reset the body joints grid - this.BodyJointsGrid.Visibility = Visibility.Visible; - this.BodyJointsGrid.Children.Clear(); - // add canvas to DisplayGrid - this.BodyJointsGrid.Children.Add(this.drawingCanvas); - bodiesManager = new BodiesManager(this.coordinateMapper, this.drawingCanvas, this.kinectSensor.BodyFrameSource.BodyCount); - break; - - case DisplayFrameType.BackgroundRemoved: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - // Actual current frame is going to be a map of depth and color, choosing the larger to display(color) - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - case DisplayFrameType.FaceOnColor: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // create the bitmap to display - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - this.FacePointsCanvas.Width = colorFrameDescription.Width; - this.FacePointsCanvas.Height = colorFrameDescription.Height; - this.faceFrameFeatures = - FaceFrameFeatures.BoundingBoxInColorSpace - | FaceFrameFeatures.PointsInColorSpace - | FaceFrameFeatures.RotationOrientation - | FaceFrameFeatures.FaceEngagement - | FaceFrameFeatures.Glasses - | FaceFrameFeatures.Happy - | FaceFrameFeatures.LeftEyeClosed - | FaceFrameFeatures.RightEyeClosed - | FaceFrameFeatures.LookingAway - | FaceFrameFeatures.MouthMoved - | FaceFrameFeatures.MouthOpen; - break; - - case DisplayFrameType.FaceOnInfrared: - infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription; - this.CurrentFrameDescription = infraredFrameDescription; - // allocate space to put the pixels being received and converted - this.infraredFrameData = new ushort[infraredFrameDescription.Width * infraredFrameDescription.Height]; - this.infraredPixels = new byte[infraredFrameDescription.Width * infraredFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(infraredFrameDescription.Width, infraredFrameDescription.Height); - this.FacePointsCanvas.Width = infraredFrameDescription.Width; - this.FacePointsCanvas.Height = infraredFrameDescription.Height; - break; - - default: - break; - } - } - - private void Sensor_IsAvailableChanged(KinectSensor sender, IsAvailableChangedEventArgs args) - { - this.StatusText = this.kinectSensor.IsAvailable ? "Running" : "Not Available"; - } - - private void Reader_MultiSourceFrameArrived(MultiSourceFrameReader sender, MultiSourceFrameArrivedEventArgs e) - { - MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame(); - - // If the Frame has expired by the time we process this event, return. - if (multiSourceFrame == null) - { - return; - } - DepthFrame depthFrame = null; - ColorFrame colorFrame = null; - InfraredFrame infraredFrame = null; - BodyFrame bodyFrame = null; - BodyIndexFrame bodyIndexFrame = null; - IBuffer depthFrameDataBuffer = null; - IBuffer bodyIndexFrameData = null; - // Com interface for unsafe byte manipulation - IBufferByteAccess bufferByteAccess = null; - switch (CurrentDisplayFrameType) - { - case DisplayFrameType.Infrared: - using (infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame()) - { - ShowInfraredFrame(infraredFrame); - } - break; - case DisplayFrameType.Color: - using (colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame()) - { - ShowColorFrame(colorFrame); - } - break; - case DisplayFrameType.Depth: - using (depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame()) - { - ShowDepthFrame(depthFrame); - } - break; - case DisplayFrameType.BodyMask: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - bodyIndexFrame = multiSourceFrame.BodyIndexFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null) || (bodyIndexFrame == null)) - { - return; - } - - // Access the depth frame data directly via LockImageBuffer to avoid making a copy - depthFrameDataBuffer = depthFrame.LockImageBuffer(); - this.coordinateMapper.MapColorFrameToDepthSpaceUsingIBuffer(depthFrameDataBuffer, this.colorMappedToDepthPoints); - // Process Color - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - // Access the body index frame data directly via LockImageBuffer to avoid making a copy - bodyIndexFrameData = bodyIndexFrame.LockImageBuffer(); - ShowMappedBodyFrame(depthFrame.FrameDescription.Width, depthFrame.FrameDescription.Height, bodyIndexFrameData, bufferByteAccess); - } - finally - { - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - if (bodyIndexFrame != null) - { - bodyIndexFrame.Dispose(); - } - - if (depthFrameDataBuffer != null) - { - // We must force a release of the IBuffer in order to ensure that we have dropped all references to it. - System.Runtime.InteropServices.Marshal.ReleaseComObject(depthFrameDataBuffer); - } - if (bodyIndexFrameData != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bodyIndexFrameData); - } - if (bufferByteAccess != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bufferByteAccess); - } - - } - break; - case DisplayFrameType.BodyJoints: - using (bodyFrame = multiSourceFrame.BodyFrameReference.AcquireFrame()) - { - ShowBodyJoints(bodyFrame); - } - break; - case DisplayFrameType.BackgroundRemoved: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null)) - { - return; - } - depthFrame.CopyFrameDataToArray(depthFrameData); - this.coordinateMapper.MapColorFrameToDepthSpace(depthFrameData, this.colorMappedToDepthPoints); - // Process Color. - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - - ShowMappedColorBackgroundRemoved(colorMappedToDepthPoints, depthFrameData, depthFrame.FrameDescription); - } - finally - { - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - } - break; - case DisplayFrameType.FaceOnColor: - using (colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame()) - { - ShowColorFrame(colorFrame); - this.faceManager.DrawLatestFaceResults(this.FacePointsCanvas, this.faceFrameFeatures); - } - break; - case DisplayFrameType.FaceOnInfrared: - using (infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame()) - { - ShowInfraredFrame(infraredFrame); - DrawFaceOnInfrared(); - } - break; - default: - break; - } - } - - private void DrawFaceOnInfrared() - { - FacePointsCanvas.Children.Clear(); - FaceFrameResult[] results = faceManager.GetLatestFaceFrameResults(); - for (int i = 0; i < results.Count(); i++ ) - { - if (results[i] != null) - { - Point rightEyePoint = results[i].FacePointsInInfraredSpace[FacePointType.EyeRight]; - Point leftEyePoint = results[i].FacePointsInInfraredSpace[FacePointType.EyeLeft]; - Point nosePoint = results[i].FacePointsInInfraredSpace[FacePointType.Nose]; - bool rightEyeIsClosed = results[i].FaceProperties[FaceProperty.RightEyeClosed] == DetectionResult.Yes || - results[i].FaceProperties[FaceProperty.RightEyeClosed] == DetectionResult.Maybe; - bool leftEyeIsClosed = results[i].FaceProperties[FaceProperty.LeftEyeClosed] == DetectionResult.Yes || - results[i].FaceProperties[FaceProperty.LeftEyeClosed] == DetectionResult.Maybe; - - if (leftEyeIsClosed) - { - Canvas.SetLeft(catEyeLeftClosed[i], leftEyePoint.X - (catEyeLeftClosed[i].Width / 2)); - Canvas.SetTop(catEyeLeftClosed[i], leftEyePoint.Y - (catEyeLeftClosed[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeLeftClosed[i]); - } - else - { - Canvas.SetLeft(catEyeLeftOpen[i], leftEyePoint.X - (catEyeLeftOpen[i].Width / 2)); - Canvas.SetTop(catEyeLeftOpen[i], leftEyePoint.Y - (catEyeLeftOpen[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeLeftOpen[i]); - } - - if (rightEyeIsClosed) - { - Canvas.SetLeft(catEyeRightClosed[i], rightEyePoint.X - (catEyeRightClosed[i].Width / 2)); - Canvas.SetTop(catEyeRightClosed[i], rightEyePoint.Y - (catEyeRightClosed[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeRightClosed[i]); - } - else - { - Canvas.SetLeft(catEyeRightOpen[i], rightEyePoint.X - (catEyeRightOpen[i].Width / 2)); - Canvas.SetTop(catEyeRightOpen[i], rightEyePoint.Y - (catEyeRightOpen[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeRightOpen[i]); - } - - Canvas.SetLeft(catNose[i], nosePoint.X - (catNose[i].Width / 2)); - Canvas.SetTop(catNose[i], nosePoint.Y); - this.FacePointsCanvas.Children.Add(catNose[i]); - } - } - } - - unsafe private void ShowMappedColorBackgroundRemoved(DepthSpacePoint[] colorMappedToDepthPoints, ushort[] depthFrameData, FrameDescription frameDescription) - { - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - int depthWidth = frameDescription.Width; - int depthHeight = frameDescription.Height; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - for (int colorIndex = 0; colorIndex < this.colorMappedToDepthPoints.Length; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPoints[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPoints[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - if (depthFrameData[depthIndex] < DepthMax) - { - continue; - } - } - } - // no matching depth. zero out the pixel. - bitmapPixelsPointer[colorIndex] = 0; - } - } - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - - private void ShowBodyJoints(BodyFrame bodyFrame) - { - Body[] bodies = new Body[this.kinectSensor.BodyFrameSource.BodyCount]; - bool dataReceived = false; - if (bodyFrame != null) - { - bodyFrame.GetAndRefreshBodyData(bodies); - dataReceived = true; - } - - if (dataReceived) - { - this.bodiesManager.UpdateBodiesAndEdges(bodies); - } - } - - unsafe private void ShowMappedBodyFrame(int depthWidth, int depthHeight, IBuffer bodyIndexFrameData, IBufferByteAccess bodyIndexByteAccess) - { - bodyIndexByteAccess = (IBufferByteAccess)bodyIndexFrameData; - byte* bodyIndexBytes = null; - bodyIndexByteAccess.Buffer(out bodyIndexBytes); - - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = this.colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - int colorMappedLength = this.colorMappedToDepthPoints.Length; - for (int colorIndex = 0; colorIndex < colorMappedLength; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPointsPointer[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPointsPointer[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - // If we are tracking a body for the current pixel, do not zero out the pixel - if (bodyIndexBytes[depthIndex] != 0xff) - { - // this bodyIndexByte is good and is a body, loop again. - continue; - } - } - } - // this pixel does not correspond to a body so make it black and transparent - bitmapPixelsPointer[colorIndex] = 0; - } - } - - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - - } - - private void ShowDepthFrame(DepthFrame depthFrame) - { - bool depthFrameProcessed = false; - ushort minDepth = 0; - ushort maxDepth = 0; - - if (depthFrame != null) - { - FrameDescription depthFrameDescription = depthFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((depthFrameDescription.Width * depthFrameDescription.Height) - == this.infraredFrameData.Length) && - (depthFrameDescription.Width == this.bitmap.PixelWidth) && - (depthFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - depthFrame.CopyFrameDataToArray(this.depthFrameData); - - minDepth = depthFrame.DepthMinReliableDistance; - maxDepth = depthFrame.DepthMaxReliableDistance; - //maxDepth = 8000; - - depthFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (depthFrameProcessed) - { - ConvertDepthDataToPixels(minDepth, maxDepth); - RenderPixelArray(this.depthPixels); - } - } - - private void ConvertDepthDataToPixels(ushort minDepth, ushort maxDepth) - { - int colorPixelIndex = 0; - // Shape the depth to the range of a byte - int mapDepthToByte = maxDepth / 256; - - for (int i = 0; i < this.depthFrameData.Length; ++i) - { - // Get the depth for this pixel - ushort depth = this.depthFrameData[i]; - - // To convert to a byte, we're mapping the depth value to the byte range. - // Values outside the reliable depth range are mapped to 0 (black). - byte intensity = (byte)(depth >= minDepth && - depth <= maxDepth ? (depth / mapDepthToByte) : 0); - - this.depthPixels[colorPixelIndex++] = intensity; //Blue - this.depthPixels[colorPixelIndex++] = intensity; //Green - this.depthPixels[colorPixelIndex++] = intensity; //Red - this.depthPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void ShowColorFrame(ColorFrame colorFrame) - { - bool colorFrameProcessed = false; - - if (colorFrame != null) - { - FrameDescription colorFrameDescription = colorFrame.FrameDescription; - - // verify data and write the new color frame data to the Writeable bitmap - if ((colorFrameDescription.Width == this.bitmap.PixelWidth) && (colorFrameDescription.Height == this.bitmap.PixelHeight)) - { - if (colorFrame.RawColorImageFormat == ColorImageFormat.Bgra) - { - colorFrame.CopyRawFrameDataToBuffer(this.bitmap.PixelBuffer); - } - else - { - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - } - - colorFrameProcessed = true; - } - } - - if (colorFrameProcessed) - { - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - } - - private void ShowInfraredFrame(InfraredFrame infraredFrame) - { - bool infraredFrameProcessed = false; - - if (infraredFrame != null) - { - FrameDescription infraredFrameDescription = infraredFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((infraredFrameDescription.Width * infraredFrameDescription.Height) - == this.infraredFrameData.Length) && - (infraredFrameDescription.Width == this.bitmap.PixelWidth) && - (infraredFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - infraredFrame.CopyFrameDataToArray(this.infraredFrameData); - - infraredFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (infraredFrameProcessed) - { - this.ConvertInfraredDataToPixels(); - this.RenderPixelArray(this.infraredPixels); - } - } - - private void ConvertInfraredDataToPixels() - { - // Convert the infrared to RGB - int colorPixelIndex = 0; - for (int i = 0; i < this.infraredFrameData.Length; ++i) - { - // normalize the incoming infrared data (ushort) to a float ranging from - // [InfraredOutputValueMinimum, InfraredOutputValueMaximum] by - // 1. dividing the incoming value by the source maximum value - float intensityRatio = (float)this.infraredFrameData[i] / InfraredSourceValueMaximum; - - // 2. dividing by the (average scene value * standard deviations) - intensityRatio /= InfraredSceneValueAverage * InfraredSceneStandardDeviations; - - // 3. limiting the value to InfraredOutputValueMaximum - intensityRatio = Math.Min(InfraredOutputValueMaximum, intensityRatio); - - // 4. limiting the lower value InfraredOutputValueMinimum - intensityRatio = Math.Max(InfraredOutputValueMinimum, intensityRatio); - - // 5. converting the normalized value to a byte and using the result - // as the RGB components required by the image - byte intensity = (byte)(intensityRatio * 255.0f); - this.infraredPixels[colorPixelIndex++] = intensity; //Blue - this.infraredPixels[colorPixelIndex++] = intensity; //Green - this.infraredPixels[colorPixelIndex++] = intensity; //Red - this.infraredPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void RenderPixelArray(byte[] pixels) - { - pixels.CopyTo(this.bitmap.PixelBuffer); - this.bitmap.Invalidate(); - this.FrameDisplayImage.Source = this.bitmap; - } - - private void InfraredButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Infrared); - } - - private void ColorButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Color); - } - - private void DepthButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Depth); - } - - private void BodyMaskButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyMask); - } - - private void BodyJointsButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyJoints); - } - - private void BackgroundButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BackgroundRemoved); - } - - private void ColorFaceButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.FaceOnColor); - } - - private void InfraredFaceButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.FaceOnInfrared); - } - - [Guid("905a0fef-bc53-11df-8c49-001e4fc686da"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IBufferByteAccess - { - unsafe void Buffer(out byte* pByte); - } - } -} diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Package.appxmanifest b/Kinect2Sample.Lab8/Kinect2Sample/Package.appxmanifest deleted file mode 100644 index 297bc48..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/Package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Kinect2Sample - Jesse - Assets\StoreLogo.png - - - 6.3.0 - 6.3.0 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab8/Kinect2Sample/Properties/AssemblyInfo.cs b/Kinect2Sample.Lab8/Kinect2Sample/Properties/AssemblyInfo.cs deleted file mode 100644 index 991ad4a..0000000 --- a/Kinect2Sample.Lab8/Kinect2Sample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Kinect2Sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Kinect2Sample")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/Kinect2Sample.Lab9/Kinect2Sample.sln b/Kinect2Sample.Lab9/Kinect2Sample.sln deleted file mode 100644 index 1178479..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kinect2Sample", "Kinect2Sample\Kinect2Sample.csproj", "{10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Build.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Deploy.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.ActiveCfg = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Build.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Deploy.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.ActiveCfg = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Kinect2Sample.Lab9/Kinect2Sample/App.xaml b/Kinect2Sample.Lab9/Kinect2Sample/App.xaml deleted file mode 100644 index b34ea9d..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/App.xaml +++ /dev/null @@ -1,7 +0,0 @@ - - - diff --git a/Kinect2Sample.Lab9/Kinect2Sample/App.xaml.cs b/Kinect2Sample.Lab9/Kinect2Sample/App.xaml.cs deleted file mode 100644 index 1692c86..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/App.xaml.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 - -namespace Kinect2Sample -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = true; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - // Set the default language - rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/Background.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/Background.png deleted file mode 100644 index 44e6e19..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/Background.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatEye_left_closed.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatEye_left_closed.png deleted file mode 100644 index 32b7544..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatEye_left_closed.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatEye_left_open.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatEye_left_open.png deleted file mode 100644 index 62c7ac0..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatEye_left_open.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatNose.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatNose.png deleted file mode 100644 index 8732b28..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/CatNose.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/Logo.scale-100.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/Logo.scale-100.png deleted file mode 100644 index e26771c..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/Logo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/SmallLogo.scale-100.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/SmallLogo.scale-100.png deleted file mode 100644 index 1eb0d9d..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/SmallLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/SplashScreen.scale-100.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/SplashScreen.scale-100.png deleted file mode 100644 index c951e03..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/SplashScreen.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Assets/StoreLogo.scale-100.png b/Kinect2Sample.Lab9/Kinect2Sample/Assets/StoreLogo.scale-100.png deleted file mode 100644 index dcb6727..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Assets/StoreLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/BodiesManager.cs b/Kinect2Sample.Lab9/Kinect2Sample/BodiesManager.cs deleted file mode 100644 index ba728a6..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/BodiesManager.cs +++ /dev/null @@ -1,492 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Foundation; -using Windows.UI; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - public class BodiesManager - { - /// - /// Radius of drawn hand circles - /// - private const double HighConfidenceHandSize = 40; - - /// - /// Radius of drawn hand circles - /// - private const double LowConfidenceHandSize = 20; - - /// - /// Thickness of drawn joint lines - /// - private const double JointThickness = 8.0; - - /// - /// Thickness of seen bone lines - /// - private const double TrackedBoneThickness = 4.0; - - /// - /// Thickness of inferred joint lines - /// - private const double InferredBoneThickness = 1.0; - - /// - /// Thickness of clip edge rectangles - /// - private const double ClipBoundsThickness = 5; - - /// - /// Constant for clamping Z values of camera space points from being negative - /// - private const float InferredZPositionClamp = 0.1f; - - private CoordinateMapper coordinateMapper; - private Canvas drawingCanvas; - - private Rectangle LeftClipEdge; - private Rectangle RightClipEdge; - private Rectangle TopClipEdge; - private Rectangle BottomClipEdge; - - /// - /// List of BodyInfo objects for each potential body - /// - private BodyInfo[] bodyInfos; - - /// - /// List of colors for each body tracked - /// - private List bodyColors; - - private int BodyCount - { - set - { - if (value == 0) - { - this.bodyInfos = null; - return; - } - - // creates instances of BodyInfo objects for potential number of bodies - if (this.bodyInfos == null || this.bodyInfos.Length != value) - { - this.bodyInfos = new BodyInfo[value]; - - for (int bodyIndex = 0; bodyIndex < value; bodyIndex++) - { - this.bodyInfos[bodyIndex] = new BodyInfo(this.bodyColors[bodyIndex], JointThickness); - } - } - } - - get { return this.bodyInfos == null ? 0 : this.bodyInfos.Length; } - } - - /// - /// Maps bodies and joints to render them in a canvas. - /// - /// The current co-ordinate mapper from the Kinect Sensor - /// The canvas upon which the joints and bones are drawn - /// The amount of bodies concurrently drawable - public BodiesManager(CoordinateMapper coordMapper, Canvas drawableCanvas, int bodyCount) - { - this.coordinateMapper = coordMapper; - this.drawingCanvas = drawableCanvas; - // populate body colors, one for each BodyIndex - this.bodyColors = new List - { - Colors.Red, - Colors.Orange, - Colors.Green, - Colors.Blue, - Colors.Indigo, - Colors.Violet - }; - - // sets total number of possible tracked bodies - // create ellipses and lines for drawing bodies - this.BodyCount = bodyCount; - - PopulateVisualJoints(); - } - - /// - /// Instantiate new objects for joints, bone lines, and clipped edge rectangles - /// - private void PopulateVisualJoints() - { - // create clipped edges and set to collapsed initially - this.LeftClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.RightClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.TopClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.BottomClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - foreach (var bodyInfo in this.bodyInfos) - { - // add left and right hand ellipses of all bodies to canvas - this.drawingCanvas.Children.Add(bodyInfo.HandLeftEllipse); - this.drawingCanvas.Children.Add(bodyInfo.HandRightEllipse); - - // add joint ellipses of all bodies to canvas - foreach (var joint in bodyInfo.JointPoints) - { - this.drawingCanvas.Children.Add(joint.Value); - } - - // add bone lines of all bodies to canvas - foreach (var bone in bodyInfo.Bones) - { - this.drawingCanvas.Children.Add(bodyInfo.BoneLines[bone]); - } - } - - // add clipped edges rectanges to main canvas - this.drawingCanvas.Children.Add(this.LeftClipEdge); - this.drawingCanvas.Children.Add(this.RightClipEdge); - this.drawingCanvas.Children.Add(this.TopClipEdge); - this.drawingCanvas.Children.Add(this.BottomClipEdge); - - // position the clipped edges - Canvas.SetLeft(this.LeftClipEdge, 0); - Canvas.SetTop(this.LeftClipEdge, 0); - Canvas.SetLeft(this.RightClipEdge, this.drawingCanvas.Width - ClipBoundsThickness); - Canvas.SetTop(this.RightClipEdge, 0); - Canvas.SetLeft(this.TopClipEdge, 0); - Canvas.SetTop(this.TopClipEdge, 0); - Canvas.SetLeft(this.BottomClipEdge, 0); - Canvas.SetTop(this.BottomClipEdge, this.drawingCanvas.Height - ClipBoundsThickness); - } - - /// - /// Updates all elipses and lines representing joints and bones - /// with the latest tracked bodies. - /// - /// An array containing body data. - internal void UpdateBodiesAndEdges(Body[] bodies) - { - bool hasTrackedBody = false; - // iterate through each body - for (int bodyIndex = 0; bodyIndex < bodies.Length; bodyIndex++) - { - Body body = bodies[bodyIndex]; - - if (body.IsTracked) - { - // check if this body clips an edge - this.UpdateClippedEdges(body, hasTrackedBody); - - this.UpdateBody(body, bodyIndex); - - hasTrackedBody = true; - } - else - { - // collapse this body from canvas as it goes out of view - this.ClearBody(bodyIndex); - } - } - - if (!hasTrackedBody) - { - // clear clipped edges if no bodies are tracked - this.ClearClippedEdges(); - } - } - - /// - /// Update body data for each body that is tracked. - /// - /// body for getting joint info - /// index for body we are currently updating - internal void UpdateBody(Body body, int bodyIndex) - { - IReadOnlyDictionary joints = body.Joints; - var jointPointsInDepthSpace = new Dictionary(); - - var bodyInfo = this.bodyInfos[bodyIndex]; - - // update all joints - foreach (var jointType in body.Joints.Keys) - { - // sometimes the depth(Z) of an inferred joint may show as negative - // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity) - CameraSpacePoint position = body.Joints[jointType].Position; - if (position.Z < 0) - { - position.Z = InferredZPositionClamp; - } - - // map joint position to depth space - DepthSpacePoint depthSpacePoint = coordinateMapper.MapCameraPointToDepthSpace(position); - jointPointsInDepthSpace[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y); - - // modify the joint's visibility and location - this.UpdateJoint(bodyInfo.JointPoints[jointType], joints[jointType], jointPointsInDepthSpace[jointType]); - - // modify hand ellipse colors based on hand states - // modity hand ellipse sizes based on tracking confidences - if (jointType == JointType.HandRight) - { - this.UpdateHand(bodyInfo.HandRightEllipse, body.HandRightState, body.HandRightConfidence, jointPointsInDepthSpace[jointType]); - } - - if (jointType == JointType.HandLeft) - { - this.UpdateHand(bodyInfo.HandLeftEllipse, body.HandLeftState, body.HandLeftConfidence, jointPointsInDepthSpace[jointType]); - } - } - - // update all bones - foreach (var bone in bodyInfo.Bones) - { - this.UpdateBone(bodyInfo.BoneLines[bone], joints[bone.Item1], joints[bone.Item2], - jointPointsInDepthSpace[bone.Item1], - jointPointsInDepthSpace[bone.Item2]); - } - } - /// - /// Updates hand state ellipses depending on tracking state and it's confidence. - /// - /// ellipse representing handstate - /// open, closed, or lasso - /// confidence of handstate - /// location of handjoint - private void UpdateHand(Ellipse ellipse, HandState handState, TrackingConfidence trackingConfidence, Point point) - { - ellipse.Fill = new SolidColorBrush(this.HandStateToColor(handState)); - - // draw handstate ellipse based on tracking confidence - ellipse.Width = ellipse.Height = (trackingConfidence == TrackingConfidence.Low) ? LowConfidenceHandSize : HighConfidenceHandSize; - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - - // don't draw handstate if hand joints are not tracked - if (!Double.IsInfinity(point.X) && !Double.IsInfinity(point.Y)) - { - Canvas.SetLeft(ellipse, point.X - ellipse.Width / 2); - Canvas.SetTop(ellipse, point.Y - ellipse.Width / 2); - } - } - - /// - /// Update a joint. - /// - /// - /// - /// - private void UpdateJoint(Ellipse ellipse, Joint joint, Point point) - { - TrackingState trackingState = joint.TrackingState; - - // only draw if joint is tracked or inferred - if (trackingState != TrackingState.NotTracked) - { - if (trackingState == TrackingState.Tracked) - { - ellipse.Fill = new SolidColorBrush(Colors.Green); - } - else - { - // inferred joints are yellow - ellipse.Fill = new SolidColorBrush(Colors.Yellow); - } - - Canvas.SetLeft(ellipse, point.X - JointThickness / 2); - Canvas.SetTop(ellipse, point.Y - JointThickness / 2); - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else - { - ellipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Update a bone line. - /// - /// line representing a bone line - /// start joint of bone line - /// end joint of bone line - /// location of start joint - /// location of end joint - private void UpdateBone(Line line, Joint startJoint, Joint endJoint, Point startPoint, Point endPoint) - { - // don't draw if neither joints are tracked - if (startJoint.TrackingState == TrackingState.NotTracked || endJoint.TrackingState == TrackingState.NotTracked) - { - line.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - return; - } - - // all lines are inferred thickness unless both joints are tracked - line.StrokeThickness = InferredBoneThickness; - - if (startJoint.TrackingState == TrackingState.Tracked && - endJoint.TrackingState == TrackingState.Tracked) - { - line.StrokeThickness = TrackedBoneThickness; - } - - line.Visibility = Windows.UI.Xaml.Visibility.Visible; - - line.X1 = startPoint.X; - line.Y1 = startPoint.Y; - line.X2 = endPoint.X; - line.Y2 = endPoint.Y; - } - - /// - /// Draws indicators to show which edges are clipping body data. - /// - /// body to draw clipping information for - /// bool to determine if another body is triggering a clipped edge - private void UpdateClippedEdges(Body body, bool hasTrackedBody) - { - // BUG (waiting for confirmation): - // Clip dectection works differently for top and right edges compared to left and bottom edges - // due to the current joint confidence model. This is an ST issue. - // Joints become inferred immediately as they touch the left/bottom edges and clip detection triggers. - // Joints squish on the right/top edges and clip detection doesn't trigger until more joints of - // the body goes out of view (e.g all hand joints vs only handtip). - - FrameEdges clippedEdges = body.ClippedEdges; - - if (clippedEdges.HasFlag(FrameEdges.Left)) - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - // don't clear this edge if another body is triggering clipped edge - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Right)) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Top)) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Bottom)) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Select color of hand state - /// - /// - /// - private Color HandStateToColor(HandState handState) - { - switch (handState) - { - case HandState.Open: - return Colors.Green; - - case HandState.Closed: - return Colors.Red; - - case HandState.Lasso: - return Colors.Blue; - } - - return Colors.Transparent; - } - - /// - /// Collapse the body from the canvas. - /// - /// - private void ClearBody(int bodyIndex) - { - var bodyInfo = this.bodyInfos[bodyIndex]; - - // collapse all joint ellipses - foreach (var joint in bodyInfo.JointPoints) - { - joint.Value.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse all bone lines - foreach (var bone in bodyInfo.Bones) - { - bodyInfo.BoneLines[bone].Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse handstate ellipses - bodyInfo.HandLeftEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - bodyInfo.HandRightEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - /// - /// Clear all clipped edges. - /// - private void ClearClippedEdges() - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } -} diff --git a/Kinect2Sample.Lab9/Kinect2Sample/BodyInfo.cs b/Kinect2Sample.Lab9/Kinect2Sample/BodyInfo.cs deleted file mode 100644 index 2f03930..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/BodyInfo.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - /// - /// BodyInfo class that contains joint ellipses, handstate ellipses, lines for bones between two joints. - /// - public class BodyInfo - { - public bool Updated { get; set; } - - public Color BodyColor { get; set; } - - // ellipse representing left handstate - public Ellipse HandLeftEllipse { get; set; } - - // ellipse representing right handstate - public Ellipse HandRightEllipse { get; set; } - - // dictionary of all joints in a body - public Dictionary JointPoints { get; private set; } - - // definition of bones - public TupleList Bones { get; private set; } - - // collection of bones associated with the line object - public Dictionary, Line> BoneLines { get; private set; } - - public BodyInfo(Color bodyColor, double jointThickness) - { - this.BodyColor = bodyColor; - - // create hand state ellipses - this.HandLeftEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.HandRightEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - // a joint defined as a jointType with a point location in XY space represented by an ellipse - this.JointPoints = new Dictionary(); - - // pre-populate list of joints and set to non-visible initially - foreach (JointType jointType in Enum.GetValues(typeof(JointType))) - { - this.JointPoints.Add(jointType, new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed, - Fill = new SolidColorBrush(BodyColor), - Width = jointThickness, - Height = jointThickness - }); - } - - // collection of bones - this.BoneLines = new Dictionary, Line>(); - - // a bone defined as a line between two joints - this.Bones = new TupleList - { - // Torso - { JointType.Head, JointType.Neck }, - { JointType.Neck, JointType.SpineShoulder }, - { JointType.SpineShoulder, JointType.SpineMid }, - { JointType.SpineMid, JointType.SpineBase }, - { JointType.SpineShoulder, JointType.ShoulderRight }, - { JointType.SpineShoulder, JointType.ShoulderLeft }, - { JointType.SpineBase, JointType.HipRight }, - { JointType.SpineBase, JointType.HipLeft }, - - // Right Arm - { JointType.ShoulderRight, JointType.ElbowRight }, - { JointType.ElbowRight, JointType.WristRight }, - { JointType.WristRight, JointType.HandRight }, - { JointType.HandRight, JointType.HandTipRight }, - { JointType.WristRight, JointType.ThumbRight }, - - // Left Arm - { JointType.ShoulderLeft, JointType.ElbowLeft }, - { JointType.ElbowLeft, JointType.WristLeft }, - { JointType.WristLeft, JointType.HandLeft }, - { JointType.HandLeft, JointType.HandTipLeft }, - { JointType.WristLeft, JointType.ThumbLeft }, - - // Right Leg - { JointType.HipRight, JointType.KneeRight }, - { JointType.KneeRight, JointType.AnkleRight }, - { JointType.AnkleRight, JointType.FootRight }, - - // Left Leg - { JointType.HipLeft, JointType.KneeLeft }, - { JointType.KneeLeft, JointType.AnkleLeft }, - { JointType.AnkleLeft, JointType.FootLeft }, - }; - - // pre-populate list of bones that are non-visible initially - foreach (var bone in this.Bones) - { - this.BoneLines.Add(bone, new Line() - { - Stroke = new SolidColorBrush(BodyColor), - Visibility = Visibility.Collapsed - }); - } - } - } - - public class TupleList : List> - { - public void Add(T1 item, T2 item2) - { - this.Add(new Tuple(item, item2)); - } - } - -} diff --git a/Kinect2Sample.Lab9/Kinect2Sample/DisplayTypeToVisibilityConverter.cs b/Kinect2Sample.Lab9/Kinect2Sample/DisplayTypeToVisibilityConverter.cs deleted file mode 100644 index 1b2c5d0..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/DisplayTypeToVisibilityConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Data; - -namespace Kinect2Sample -{ - class DisplayTypeToVisibilityConverter :IValueConverter - { - public object Convert(object value, Type targetType, object parameter, string language) - { - String boundString = Enum.GetName(typeof(DisplayFrameType), value); - String matchString = (String)parameter; - - if (String.Equals(boundString, matchString)) - { - return Visibility.Visible; - } - else - { - return Visibility.Collapsed; - } - } - - public object ConvertBack(object value, Type targetType, object parameter, string language) - { - throw new NotImplementedException(); - } - } -} diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample.Lab9/Kinect2Sample/Kinect2Sample.csproj deleted file mode 100644 index 6f8d299..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/Kinect2Sample.csproj +++ /dev/null @@ -1,113 +0,0 @@ - - - - - Debug - AnyCPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F} - AppContainerExe - Properties - Kinect2Sample - Kinect2Sample - en-US - 8.1 - 12 - 512 - {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Kinect2Sample_TemporaryKey.pfx - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x64 - false - prompt - true - true - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x64 - false - prompt - true - - - - App.xaml - - - - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - Microsoft.Kinect.Face - - - Microsoft Visual C++ 2013 Runtime Package for Windows - - - WindowsPreview.Kinect - - - - - - - - Libraries\x64\DirectXSceneStore.winmd - - - Libraries\x64\KinectFaceStore.dll - - - - 12.0 - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx b/Kinect2Sample.Lab9/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx deleted file mode 100644 index 7cb3591..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.dll b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.dll deleted file mode 100644 index 2c91ab2..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.dll and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.pri b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.pri deleted file mode 100644 index bafa749..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.pri and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.winmd b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.winmd deleted file mode 100644 index 5f5cdda..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore.winmd and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/bounce.wav b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/bounce.wav deleted file mode 100644 index 8267695..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/bounce.wav and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellceiling.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellceiling.dds deleted file mode 100644 index dd24b59..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellceiling.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellfloor.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellfloor.dds deleted file mode 100644 index 790df24..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellfloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellwall.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellwall.dds deleted file mode 100644 index 7bfc4af..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/cellwall.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayceiling.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayceiling.dds deleted file mode 100644 index 6148ae3..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayceiling.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayfloor.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayfloor.dds deleted file mode 100644 index 22f11fa..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/dayfloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/daywall.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/daywall.dds deleted file mode 100644 index 6148ae3..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/daywall.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/hit.wav b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/hit.wav deleted file mode 100644 index f4a78ac..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/hit.wav and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/mediumTile-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/mediumTile-sdk.png deleted file mode 100644 index 1c9f68e..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/mediumTile-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/metal_texture.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/metal_texture.dds deleted file mode 100644 index af2e355..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/metal_texture.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightceiling.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightceiling.dds deleted file mode 100644 index 291a923..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightceiling.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightfloor.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightfloor.dds deleted file mode 100644 index 04e424b..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightfloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightwall.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightwall.dds deleted file mode 100644 index 291a923..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/nightwall.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/seafloor.dds b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/seafloor.dds deleted file mode 100644 index 3c8eed9..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/seafloor.dds and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-phone-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-phone-sdk.png deleted file mode 100644 index 4476cda..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-phone-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-windows-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-windows-sdk.png deleted file mode 100644 index e39b01f..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/smallTile-windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-phone-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-phone-sdk.png deleted file mode 100644 index 435f872..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-phone-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-windows-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-windows-sdk.png deleted file mode 100644 index e00df02..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/splash-windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/squareTile-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/squareTile-sdk.png deleted file mode 100644 index 2a8cf87..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/squareTile-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/storeLogo-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/storeLogo-sdk.png deleted file mode 100644 index 5c397de..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/storeLogo-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/tile-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/tile-sdk.png deleted file mode 100644 index f72683f..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/tile-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/windows-sdk.png b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/windows-sdk.png deleted file mode 100644 index 6726802..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/Assets/windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/GameUIStyles.xbf b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/GameUIStyles.xbf deleted file mode 100644 index faae63d..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/GameUIStyles.xbf and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/PixelShader.cso b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/PixelShader.cso deleted file mode 100644 index 96f56e3..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/PixelShader.cso and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/PixelShaderFlat.cso b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/PixelShaderFlat.cso deleted file mode 100644 index fc57594..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/PixelShaderFlat.cso and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/ScenePanel.xbf b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/ScenePanel.xbf deleted file mode 100644 index e75cb98..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/ScenePanel.xbf and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/VertexShader.cso b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/VertexShader.cso deleted file mode 100644 index c4b50be..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/VertexShader.cso and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/VertexShaderFlat.cso b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/VertexShaderFlat.cso deleted file mode 100644 index bfffc0f..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/DirectXSceneStore/VertexShaderFlat.cso and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/KinectFaceStore.dll b/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/KinectFaceStore.dll deleted file mode 100644 index 408b58a..0000000 Binary files a/Kinect2Sample.Lab9/Kinect2Sample/Libraries/x64/KinectFaceStore.dll and /dev/null differ diff --git a/Kinect2Sample.Lab9/Kinect2Sample/MainPage.xaml b/Kinect2Sample.Lab9/Kinect2Sample/MainPage.xaml deleted file mode 100644 index c2ce693..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/MainPage.xaml +++ /dev/null @@ -1,109 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Kinect2Sample.Lab9/Kinect2Sample/MainPage.xaml.cs b/Kinect2Sample.Lab9/Kinect2Sample/MainPage.xaml.cs deleted file mode 100644 index 7d609ec..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/MainPage.xaml.cs +++ /dev/null @@ -1,1004 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Media.Imaging; -using Windows.UI.Xaml.Navigation; -using WindowsPreview.Kinect; -using System.ComponentModel; -using Windows.Storage.Streams; -using System.Runtime.InteropServices; -using System.Diagnostics; -using Windows.UI.Xaml.Shapes; -using Windows.UI; -using KinectFace; -using Microsoft.Kinect.Face; - -namespace Kinect2Sample -{ - public enum DisplayFrameType - { - Infrared, - Color, - Depth, - BodyMask, - BodyJoints, - BackgroundRemoved, - FaceOnColor, - FaceOnInfrared, - FaceGame - } - - public sealed partial class MainPage : Page, INotifyPropertyChanged - { - private const DisplayFrameType DEFAULT_DISPLAYFRAMETYPE = DisplayFrameType.Infrared; - - private const double FACE_AIMING_ACCURACY= 1.0; - private const double FACE_AIMING_SENSITIVITY = 0.01; - - /// - /// The highest value that can be returned in the InfraredFrame. - /// It is cast to a float for readability in the visualization code. - /// - private const float InfraredSourceValueMaximum = (float)ushort.MaxValue; - - /// - /// Used to set the lower limit, post processing, of the - /// infrared data that we will render. - /// Increasing or decreasing this value sets a brightness - /// "wall" either closer or further away. - /// - private const float InfraredOutputValueMinimum = 0.01f; - - /// - /// The upper limit, post processing, of the - /// infrared data that will render. - /// - private const float InfraredOutputValueMaximum = 1.0f; - - /// - /// The InfraredSceneValueAverage value specifies the average infrared - /// value of the scene. This value was selected by analyzing the average - /// pixel intensity for a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneValueAverage = 0.08f; - - /// - /// The InfraredSceneStandardDeviations value specifies the number of - /// standard deviations to apply to InfraredSceneValueAverage. - /// This value was selected by analyzing data from a given scene. - /// This could be calculated at runtime to handle different IR conditions - /// of a scene (outside vs inside). - /// - private const float InfraredSceneStandardDeviations = 3.0f; - - // Size of the RGB pixel in the bitmap - private const int BytesPerPixel = 4; - - private KinectSensor kinectSensor = null; - private string statusText = null; - private WriteableBitmap bitmap = null; - private FrameDescription currentFrameDescription; - private DisplayFrameType currentDisplayFrameType; - private MultiSourceFrameReader multiSourceFrameReader = null; - private CoordinateMapper coordinateMapper = null; - private BodiesManager bodiesManager = null; - - //Infrared Frame - private ushort[] infraredFrameData = null; - private byte[] infraredPixels = null; - - //Depth Frame - private ushort[] depthFrameData = null; - private byte[] depthPixels = null; - private ushort depthMax = 8000; - - //BodyMask Frames - private DepthSpacePoint[] colorMappedToDepthPoints = null; - - //Body Joints are drawn here - private Canvas drawingCanvas; - - //FaceManager library - private FaceManager faceManager; - private FaceFrameFeatures faceFrameFeatures; - - //Cat assets - private Image[] catEyeRightOpen, catEyeRightClosed, catEyeLeftOpen, catEyeLeftClosed, catNose; - - //Face Orientation Shaping - private double prevPitch = 0.0f; - private double prevYaw = 0.0f; - - public event PropertyChangedEventHandler PropertyChanged; - public string StatusText - { - get { return this.statusText; } - set - { - if (this.statusText != value) - { - this.statusText = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); - } - } - } - } - - public FrameDescription CurrentFrameDescription - { - get { return this.currentFrameDescription; } - set - { - if (this.currentFrameDescription != value) - { - this.currentFrameDescription = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentFrameDescription")); - } - } - } - } - - public DisplayFrameType CurrentDisplayFrameType - { - get { return this.currentDisplayFrameType; } - set - { - if (this.currentDisplayFrameType != value) - { - this.currentDisplayFrameType = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("CurrentDisplayFrameType")); - } - } - } - } - - public ushort DepthMax - { - get { return this.depthMax; } - set - { - if (this.depthMax != value) - { - this.depthMax = value; - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs("DepthMax")); - } - } - } - } - - public MainPage() - { - // one sensor is currently supported - this.kinectSensor = KinectSensor.GetDefault(); - - this.coordinateMapper = this.kinectSensor.CoordinateMapper; - - this.multiSourceFrameReader = this.kinectSensor.OpenMultiSourceFrameReader(FrameSourceTypes.Infrared | FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.BodyIndex | FrameSourceTypes.Body); - - this.multiSourceFrameReader.MultiSourceFrameArrived += this.Reader_MultiSourceFrameArrived; - - // specify the required face frame results - // init with all the features so they are accessible later. - this.faceFrameFeatures = - FaceFrameFeatures.BoundingBoxInColorSpace - | FaceFrameFeatures.PointsInColorSpace - | FaceFrameFeatures.BoundingBoxInInfraredSpace - | FaceFrameFeatures.PointsInInfraredSpace - | FaceFrameFeatures.RotationOrientation - | FaceFrameFeatures.FaceEngagement - | FaceFrameFeatures.Glasses - | FaceFrameFeatures.Happy - | FaceFrameFeatures.LeftEyeClosed - | FaceFrameFeatures.RightEyeClosed - | FaceFrameFeatures.LookingAway - | FaceFrameFeatures.MouthMoved - | FaceFrameFeatures.MouthOpen; - - this.faceManager = new FaceManager(this.kinectSensor, this.faceFrameFeatures); - - // set IsAvailableChanged event notifier - this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; - - // use the window object as the view model in this simple example - this.DataContext = this; - - // open the sensor - this.kinectSensor.Open(); - - this.InitializeComponent(); - - // new - this.Loaded += MainPage_Loaded; - } - - void MainPage_Loaded(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DEFAULT_DISPLAYFRAMETYPE); - - SetupCatAssets(); - } - - private void SetupCatAssets() - { - ScaleTransform flipTransform = new ScaleTransform() { ScaleX = -1.0 }; - int bodyCount = kinectSensor.BodyFrameSource.BodyCount; - catEyeRightOpen = new Image[bodyCount]; - catEyeRightClosed = new Image[bodyCount]; - catEyeLeftOpen = new Image[bodyCount]; - catEyeLeftClosed = new Image[bodyCount]; - catNose = new Image[bodyCount]; - - for (int i = 0; i < kinectSensor.BodyFrameSource.BodyCount; i++) - { - catEyeRightOpen[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_open.png")), - Width = 30, - Height = 20, - RenderTransformOrigin = new Point(0.5, 0.5), - RenderTransform = flipTransform - }; - catEyeRightClosed[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_closed.png")), - Width = 30, - Height = 20, - RenderTransformOrigin = new Point(0.5, 0.5), - RenderTransform = flipTransform - }; - catEyeLeftOpen[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_open.png")), - Width = 30, - Height = 20 - }; - catEyeLeftClosed[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatEye_left_closed.png")), - Width = 30, - Height = 20 - }; - catEyeLeftClosed[i].RenderTransformOrigin = new Point(0.5, 0.5); - catNose[i] = new Image() - { - Source = new BitmapImage(new Uri(this.BaseUri, "Assets/CatNose.png")), - Width = 40, - Height = 25 - }; - } - } - - private void SetupCurrentDisplay(DisplayFrameType newDisplayFrameType) - { - CurrentDisplayFrameType = newDisplayFrameType; - // Frames used by more than one type are declared outside the switch - FrameDescription colorFrameDescription = null; - FrameDescription depthFrameDescription = null; - FrameDescription infraredFrameDescription = null; - // reset the display methods - FacePointsCanvas.Children.Clear(); - if (this.BodyJointsGrid != null) - { - this.BodyJointsGrid.Visibility = Visibility.Collapsed; - } - if (this.FrameDisplayImage != null) - { - this.FrameDisplayImage.Source = null; - } - switch (CurrentDisplayFrameType) - { - case DisplayFrameType.Infrared: - infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription; - this.CurrentFrameDescription = infraredFrameDescription; - // allocate space to put the pixels being received and converted - this.infraredFrameData = new ushort[infraredFrameDescription.Width * infraredFrameDescription.Height]; - this.infraredPixels = new byte[infraredFrameDescription.Width * infraredFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(infraredFrameDescription.Width, infraredFrameDescription.Height); - break; - - case DisplayFrameType.Color: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // create the bitmap to display - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.Depth: - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - this.CurrentFrameDescription = depthFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.depthPixels = new byte[depthFrameDescription.Width * depthFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(depthFrameDescription.Width, depthFrameDescription.Height); - break; - - case DisplayFrameType.BodyMask: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - - case DisplayFrameType.BodyJoints: - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - // instantiate a new Canvas - this.drawingCanvas = new Canvas(); - // set the clip rectangle to prevent rendering outside the canvas - this.drawingCanvas.Clip = new RectangleGeometry(); - this.drawingCanvas.Clip.Rect = new Rect(0.0, 0.0, this.BodyJointsGrid.Width, this.BodyJointsGrid.Height); - this.drawingCanvas.Width = this.BodyJointsGrid.Width; - this.drawingCanvas.Height = this.BodyJointsGrid.Height; - // reset the body joints grid - this.BodyJointsGrid.Visibility = Visibility.Visible; - this.BodyJointsGrid.Children.Clear(); - // add canvas to DisplayGrid - this.BodyJointsGrid.Children.Add(this.drawingCanvas); - bodiesManager = new BodiesManager(this.coordinateMapper, this.drawingCanvas, this.kinectSensor.BodyFrameSource.BodyCount); - break; - - case DisplayFrameType.BackgroundRemoved: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription; - // Actual current frame is going to be a map of depth and color, choosing the larger to display(color) - this.CurrentFrameDescription = colorFrameDescription; - // allocate space to put the pixels being received and converted - this.depthFrameData = new ushort[depthFrameDescription.Width * depthFrameDescription.Height]; - this.colorMappedToDepthPoints = new DepthSpacePoint[colorFrameDescription.Width * colorFrameDescription.Height]; - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - break; - case DisplayFrameType.FaceOnColor: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - // create the bitmap to display - this.bitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height); - this.FacePointsCanvas.Width = colorFrameDescription.Width; - this.FacePointsCanvas.Height = colorFrameDescription.Height; - this.faceFrameFeatures = - FaceFrameFeatures.BoundingBoxInColorSpace - | FaceFrameFeatures.PointsInColorSpace - | FaceFrameFeatures.RotationOrientation - | FaceFrameFeatures.FaceEngagement - | FaceFrameFeatures.Glasses - | FaceFrameFeatures.Happy - | FaceFrameFeatures.LeftEyeClosed - | FaceFrameFeatures.RightEyeClosed - | FaceFrameFeatures.LookingAway - | FaceFrameFeatures.MouthMoved - | FaceFrameFeatures.MouthOpen; - break; - - case DisplayFrameType.FaceOnInfrared: - infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription; - this.CurrentFrameDescription = infraredFrameDescription; - // allocate space to put the pixels being received and converted - this.infraredFrameData = new ushort[infraredFrameDescription.Width * infraredFrameDescription.Height]; - this.infraredPixels = new byte[infraredFrameDescription.Width * infraredFrameDescription.Height * BytesPerPixel]; - this.bitmap = new WriteableBitmap(infraredFrameDescription.Width, infraredFrameDescription.Height); - this.FacePointsCanvas.Width = infraredFrameDescription.Width; - this.FacePointsCanvas.Height = infraredFrameDescription.Height; - break; - - case DisplayFrameType.FaceGame: - colorFrameDescription = this.kinectSensor.ColorFrameSource.FrameDescription; - this.CurrentFrameDescription = colorFrameDescription; - this.FacePointsCanvas.Width = colorFrameDescription.Width; - this.FacePointsCanvas.Height = colorFrameDescription.Height; - break; - - default: - break; - } - } - - private void Sensor_IsAvailableChanged(KinectSensor sender, IsAvailableChangedEventArgs args) - { - this.StatusText = this.kinectSensor.IsAvailable ? "Running" : "Not Available"; - } - - private void Reader_MultiSourceFrameArrived(MultiSourceFrameReader sender, MultiSourceFrameArrivedEventArgs e) - { - MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame(); - - // If the Frame has expired by the time we process this event, return. - if (multiSourceFrame == null) - { - return; - } - DepthFrame depthFrame = null; - ColorFrame colorFrame = null; - InfraredFrame infraredFrame = null; - BodyFrame bodyFrame = null; - BodyIndexFrame bodyIndexFrame = null; - IBuffer depthFrameDataBuffer = null; - IBuffer bodyIndexFrameData = null; - // Com interface for unsafe byte manipulation - IBufferByteAccess bufferByteAccess = null; - switch (CurrentDisplayFrameType) - { - case DisplayFrameType.Infrared: - using (infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame()) - { - ShowInfraredFrame(infraredFrame); - } - break; - case DisplayFrameType.Color: - using (colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame()) - { - ShowColorFrame(colorFrame); - } - break; - case DisplayFrameType.Depth: - using (depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame()) - { - ShowDepthFrame(depthFrame); - } - break; - case DisplayFrameType.BodyMask: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - bodyIndexFrame = multiSourceFrame.BodyIndexFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null) || (bodyIndexFrame == null)) - { - return; - } - - // Access the depth frame data directly via LockImageBuffer to avoid making a copy - depthFrameDataBuffer = depthFrame.LockImageBuffer(); - this.coordinateMapper.MapColorFrameToDepthSpaceUsingIBuffer(depthFrameDataBuffer, this.colorMappedToDepthPoints); - // Process Color - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - // Access the body index frame data directly via LockImageBuffer to avoid making a copy - bodyIndexFrameData = bodyIndexFrame.LockImageBuffer(); - ShowMappedBodyFrame(depthFrame.FrameDescription.Width, depthFrame.FrameDescription.Height, bodyIndexFrameData, bufferByteAccess); - } - finally - { - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - if (bodyIndexFrame != null) - { - bodyIndexFrame.Dispose(); - } - - if (depthFrameDataBuffer != null) - { - // We must force a release of the IBuffer in order to ensure that we have dropped all references to it. - System.Runtime.InteropServices.Marshal.ReleaseComObject(depthFrameDataBuffer); - } - if (bodyIndexFrameData != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bodyIndexFrameData); - } - if (bufferByteAccess != null) - { - System.Runtime.InteropServices.Marshal.ReleaseComObject(bufferByteAccess); - } - - } - break; - case DisplayFrameType.BodyJoints: - using (bodyFrame = multiSourceFrame.BodyFrameReference.AcquireFrame()) - { - ShowBodyJoints(bodyFrame); - } - break; - case DisplayFrameType.BackgroundRemoved: - // Put in a try catch to utilise finally() and clean up frames - try - { - depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); - colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); - if ((depthFrame == null) || (colorFrame == null)) - { - return; - } - depthFrame.CopyFrameDataToArray(depthFrameData); - this.coordinateMapper.MapColorFrameToDepthSpace(depthFrameData, this.colorMappedToDepthPoints); - // Process Color. - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - - ShowMappedColorBackgroundRemoved(colorMappedToDepthPoints, depthFrameData, depthFrame.FrameDescription); - } - finally - { - if (depthFrame != null) - { - depthFrame.Dispose(); - } - if (colorFrame != null) - { - colorFrame.Dispose(); - } - } - break; - case DisplayFrameType.FaceOnColor: - using (colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame()) - { - ShowColorFrame(colorFrame); - this.faceManager.DrawLatestFaceResults(this.FacePointsCanvas, this.faceFrameFeatures); - } - break; - case DisplayFrameType.FaceOnInfrared: - using (infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame()) - { - ShowInfraredFrame(infraredFrame); - DrawFaceOnInfrared(); - } - break; - case DisplayFrameType.FaceGame: - FaceGameLookUpdate(); - break; - default: - break; - } - } - - private void FaceGameLookUpdate() - { - this.FacePointsCanvas.Children.Clear(); - FaceFrameResult[] results = faceManager.GetLatestFaceFrameResults(); - for (int i = 0; i < results.Count(); i++) - { - if (results[i] != null) - { - foreach (KeyValuePair facePointKVP in - results[i].FacePointsInColorSpace) - { - if (facePointKVP.Value.X == 0.0 || facePointKVP.Value.Y == 0.0) - { - break; - } - Size ellipseSize = new Size(10, 10); - Ellipse ellipse = new Ellipse(); - ellipse.Width = ellipseSize.Width; - ellipse.Height = ellipseSize.Height; - ellipse.Fill = new SolidColorBrush(Colors.Red); - Canvas.SetLeft(ellipse, facePointKVP.Value.X - (ellipseSize.Width / 2)); - Canvas.SetTop(ellipse, facePointKVP.Value.Y - (ellipseSize.Height / 2)); - this.FacePointsCanvas.Children.Add(ellipse); - } - - double pitch, roll, yaw = 0; - - ExtractFaceRotationInDegrees(results[i].FaceRotationQuaternion, out pitch, out yaw, out roll); - - double pitchDiff = Math.Abs(pitch - prevPitch); - double yawDiff = Math.Abs(yaw - prevYaw); - if (pitchDiff > FACE_AIMING_ACCURACY || - yawDiff > FACE_AIMING_ACCURACY) - { - this.DXScenePanel.SetYawPitch( - -(float)(yaw * FACE_AIMING_SENSITIVITY), - (float)(pitch * FACE_AIMING_SENSITIVITY)); - prevPitch = pitch; - prevYaw = yaw; - } - - if (results[i].FaceProperties[FaceProperty.MouthOpen] == DetectionResult.Yes) - { - this.DXScenePanel.Fire(); - } - break; - } - } - } - - private void DrawFaceOnInfrared() - { - FacePointsCanvas.Children.Clear(); - FaceFrameResult[] results = faceManager.GetLatestFaceFrameResults(); - for (int i = 0; i < results.Count(); i++) - { - if (results[i] != null) - { - Point rightEyePoint = results[i].FacePointsInInfraredSpace[FacePointType.EyeRight]; - Point leftEyePoint = results[i].FacePointsInInfraredSpace[FacePointType.EyeLeft]; - Point nosePoint = results[i].FacePointsInInfraredSpace[FacePointType.Nose]; - bool rightEyeIsClosed = results[i].FaceProperties[FaceProperty.RightEyeClosed] == DetectionResult.Yes || - results[i].FaceProperties[FaceProperty.RightEyeClosed] == DetectionResult.Maybe; - bool leftEyeIsClosed = results[i].FaceProperties[FaceProperty.LeftEyeClosed] == DetectionResult.Yes || - results[i].FaceProperties[FaceProperty.LeftEyeClosed] == DetectionResult.Maybe; - - if (leftEyeIsClosed) - { - Canvas.SetLeft(catEyeLeftClosed[i], leftEyePoint.X - (catEyeLeftClosed[i].Width / 2)); - Canvas.SetTop(catEyeLeftClosed[i], leftEyePoint.Y - (catEyeLeftClosed[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeLeftClosed[i]); - } - else - { - Canvas.SetLeft(catEyeLeftOpen[i], leftEyePoint.X - (catEyeLeftOpen[i].Width / 2)); - Canvas.SetTop(catEyeLeftOpen[i], leftEyePoint.Y - (catEyeLeftOpen[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeLeftOpen[i]); - } - - if (rightEyeIsClosed) - { - Canvas.SetLeft(catEyeRightClosed[i], rightEyePoint.X - (catEyeRightClosed[i].Width / 2)); - Canvas.SetTop(catEyeRightClosed[i], rightEyePoint.Y - (catEyeRightClosed[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeRightClosed[i]); - } - else - { - Canvas.SetLeft(catEyeRightOpen[i], rightEyePoint.X - (catEyeRightOpen[i].Width / 2)); - Canvas.SetTop(catEyeRightOpen[i], rightEyePoint.Y - (catEyeRightOpen[i].Height / 2)); - this.FacePointsCanvas.Children.Add(catEyeRightOpen[i]); - } - - Canvas.SetLeft(catNose[i], nosePoint.X - (catNose[i].Width / 2)); - Canvas.SetTop(catNose[i], nosePoint.Y); - this.FacePointsCanvas.Children.Add(catNose[i]); - } - } - } - - unsafe private void ShowMappedColorBackgroundRemoved(DepthSpacePoint[] colorMappedToDepthPoints, ushort[] depthFrameData, FrameDescription frameDescription) - { - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - int depthWidth = frameDescription.Width; - int depthHeight = frameDescription.Height; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - for (int colorIndex = 0; colorIndex < this.colorMappedToDepthPoints.Length; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPoints[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPoints[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - if (depthFrameData[depthIndex] < DepthMax) - { - continue; - } - } - } - // no matching depth. zero out the pixel. - bitmapPixelsPointer[colorIndex] = 0; - } - } - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - - private void ShowBodyJoints(BodyFrame bodyFrame) - { - Body[] bodies = new Body[this.kinectSensor.BodyFrameSource.BodyCount]; - bool dataReceived = false; - if (bodyFrame != null) - { - bodyFrame.GetAndRefreshBodyData(bodies); - dataReceived = true; - } - - if (dataReceived) - { - this.bodiesManager.UpdateBodiesAndEdges(bodies); - } - } - - unsafe private void ShowMappedBodyFrame(int depthWidth, int depthHeight, IBuffer bodyIndexFrameData, IBufferByteAccess bodyIndexByteAccess) - { - bodyIndexByteAccess = (IBufferByteAccess)bodyIndexFrameData; - byte* bodyIndexBytes = null; - bodyIndexByteAccess.Buffer(out bodyIndexBytes); - - fixed (DepthSpacePoint* colorMappedToDepthPointsPointer = this.colorMappedToDepthPoints) - { - IBufferByteAccess bitmapBackBufferByteAccess = (IBufferByteAccess)this.bitmap.PixelBuffer; - - byte* bitmapBackBufferBytes = null; - bitmapBackBufferByteAccess.Buffer(out bitmapBackBufferBytes); - - // Treat the color data as 4-byte pixels - uint* bitmapPixelsPointer = (uint*)bitmapBackBufferBytes; - - // Loop over each row and column of the color image - // Zero out any pixels that don't correspond to a body index - int colorMappedLength = this.colorMappedToDepthPoints.Length; - for (int colorIndex = 0; colorIndex < colorMappedLength; ++colorIndex) - { - float colorMappedToDepthX = colorMappedToDepthPointsPointer[colorIndex].X; - float colorMappedToDepthY = colorMappedToDepthPointsPointer[colorIndex].Y; - - // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. - if (!float.IsNegativeInfinity(colorMappedToDepthX) && - !float.IsNegativeInfinity(colorMappedToDepthY)) - { - // Make sure the depth pixel maps to a valid point in color space - int depthX = (int)(colorMappedToDepthX + 0.5f); - int depthY = (int)(colorMappedToDepthY + 0.5f); - - // If the point is not valid, there is no body index there. - if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) - { - int depthIndex = (depthY * depthWidth) + depthX; - - // If we are tracking a body for the current pixel, do not zero out the pixel - if (bodyIndexBytes[depthIndex] != 0xff) - { - // this bodyIndexByte is good and is a body, loop again. - continue; - } - } - } - // this pixel does not correspond to a body so make it black and transparent - bitmapPixelsPointer[colorIndex] = 0; - } - } - - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - - } - - private void ShowDepthFrame(DepthFrame depthFrame) - { - bool depthFrameProcessed = false; - ushort minDepth = 0; - ushort maxDepth = 0; - - if (depthFrame != null) - { - FrameDescription depthFrameDescription = depthFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((depthFrameDescription.Width * depthFrameDescription.Height) - == this.infraredFrameData.Length) && - (depthFrameDescription.Width == this.bitmap.PixelWidth) && - (depthFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - depthFrame.CopyFrameDataToArray(this.depthFrameData); - - minDepth = depthFrame.DepthMinReliableDistance; - maxDepth = depthFrame.DepthMaxReliableDistance; - //maxDepth = 8000; - - depthFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (depthFrameProcessed) - { - ConvertDepthDataToPixels(minDepth, maxDepth); - RenderPixelArray(this.depthPixels); - } - } - - private void ConvertDepthDataToPixels(ushort minDepth, ushort maxDepth) - { - int colorPixelIndex = 0; - // Shape the depth to the range of a byte - int mapDepthToByte = maxDepth / 256; - - for (int i = 0; i < this.depthFrameData.Length; ++i) - { - // Get the depth for this pixel - ushort depth = this.depthFrameData[i]; - - // To convert to a byte, we're mapping the depth value to the byte range. - // Values outside the reliable depth range are mapped to 0 (black). - byte intensity = (byte)(depth >= minDepth && - depth <= maxDepth ? (depth / mapDepthToByte) : 0); - - this.depthPixels[colorPixelIndex++] = intensity; //Blue - this.depthPixels[colorPixelIndex++] = intensity; //Green - this.depthPixels[colorPixelIndex++] = intensity; //Red - this.depthPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void ShowColorFrame(ColorFrame colorFrame) - { - bool colorFrameProcessed = false; - - if (colorFrame != null) - { - FrameDescription colorFrameDescription = colorFrame.FrameDescription; - - // verify data and write the new color frame data to the Writeable bitmap - if ((colorFrameDescription.Width == this.bitmap.PixelWidth) && (colorFrameDescription.Height == this.bitmap.PixelHeight)) - { - if (colorFrame.RawColorImageFormat == ColorImageFormat.Bgra) - { - colorFrame.CopyRawFrameDataToBuffer(this.bitmap.PixelBuffer); - } - else - { - colorFrame.CopyConvertedFrameDataToBuffer(this.bitmap.PixelBuffer, ColorImageFormat.Bgra); - } - - colorFrameProcessed = true; - } - } - - if (colorFrameProcessed) - { - this.bitmap.Invalidate(); - FrameDisplayImage.Source = this.bitmap; - } - } - - private void ShowInfraredFrame(InfraredFrame infraredFrame) - { - bool infraredFrameProcessed = false; - - if (infraredFrame != null) - { - FrameDescription infraredFrameDescription = infraredFrame.FrameDescription; - - // verify data and write the new infrared frame data to the display bitmap - if (((infraredFrameDescription.Width * infraredFrameDescription.Height) - == this.infraredFrameData.Length) && - (infraredFrameDescription.Width == this.bitmap.PixelWidth) && - (infraredFrameDescription.Height == this.bitmap.PixelHeight)) - { - // Copy the pixel data from the image to a temporary array - infraredFrame.CopyFrameDataToArray(this.infraredFrameData); - - infraredFrameProcessed = true; - } - } - - // we got a frame, convert and render - if (infraredFrameProcessed) - { - this.ConvertInfraredDataToPixels(); - this.RenderPixelArray(this.infraredPixels); - } - } - - private void ConvertInfraredDataToPixels() - { - // Convert the infrared to RGB - int colorPixelIndex = 0; - for (int i = 0; i < this.infraredFrameData.Length; ++i) - { - // normalize the incoming infrared data (ushort) to a float ranging from - // [InfraredOutputValueMinimum, InfraredOutputValueMaximum] by - // 1. dividing the incoming value by the source maximum value - float intensityRatio = (float)this.infraredFrameData[i] / InfraredSourceValueMaximum; - - // 2. dividing by the (average scene value * standard deviations) - intensityRatio /= InfraredSceneValueAverage * InfraredSceneStandardDeviations; - - // 3. limiting the value to InfraredOutputValueMaximum - intensityRatio = Math.Min(InfraredOutputValueMaximum, intensityRatio); - - // 4. limiting the lower value InfraredOutputValueMinimum - intensityRatio = Math.Max(InfraredOutputValueMinimum, intensityRatio); - - // 5. converting the normalized value to a byte and using the result - // as the RGB components required by the image - byte intensity = (byte)(intensityRatio * 255.0f); - this.infraredPixels[colorPixelIndex++] = intensity; //Blue - this.infraredPixels[colorPixelIndex++] = intensity; //Green - this.infraredPixels[colorPixelIndex++] = intensity; //Red - this.infraredPixels[colorPixelIndex++] = 255; //Alpha - } - } - - private void RenderPixelArray(byte[] pixels) - { - pixels.CopyTo(this.bitmap.PixelBuffer); - this.bitmap.Invalidate(); - this.FrameDisplayImage.Source = this.bitmap; - } - - private static void ExtractFaceRotationInDegrees(Vector4 rotQuaternion, out double pitch, out double yaw, out double roll) - { - double x = rotQuaternion.X; - double y = rotQuaternion.Y; - double z = rotQuaternion.Z; - double w = rotQuaternion.W; - - // convert face rotation quaternion to Euler angles in degrees - pitch = Math.Atan2(2 * ((y * z) + (w * x)), (w * w) - (x * x) - (y * y) + (z * z)) / Math.PI * 180.0; - yaw = Math.Asin(2 * ((w * y) - (x * z))) / Math.PI * 180.0; - roll = Math.Atan2(2 * ((x * y) + (w * z)), (w * w) + (x * x) - (y * y) - (z * z)) / Math.PI * 180.0; - } - - private void InfraredButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Infrared); - } - - private void ColorButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Color); - } - - private void DepthButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.Depth); - } - - private void BodyMaskButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyMask); - } - - private void BodyJointsButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BodyJoints); - } - - private void BackgroundButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.BackgroundRemoved); - } - - private void ColorFaceButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.FaceOnColor); - } - - private void InfraredFaceButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.FaceOnInfrared); - } - - [Guid("905a0fef-bc53-11df-8c49-001e4fc686da"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IBufferByteAccess - { - unsafe void Buffer(out byte* pByte); - } - - private void FaceGameButton_Click(object sender, RoutedEventArgs e) - { - SetupCurrentDisplay(DisplayFrameType.FaceGame); - } - } -} diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Package.appxmanifest b/Kinect2Sample.Lab9/Kinect2Sample/Package.appxmanifest deleted file mode 100644 index 297bc48..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/Package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Kinect2Sample - Jesse - Assets\StoreLogo.png - - - 6.3.0 - 6.3.0 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Kinect2Sample.Lab9/Kinect2Sample/Properties/AssemblyInfo.cs b/Kinect2Sample.Lab9/Kinect2Sample/Properties/AssemblyInfo.cs deleted file mode 100644 index 991ad4a..0000000 --- a/Kinect2Sample.Lab9/Kinect2Sample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Kinect2Sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Kinect2Sample")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/Kinect2Sample.Lab10/Kinect2Sample.sln b/Kinect2Sample.sln similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample.sln rename to Kinect2Sample.sln diff --git a/Kinect2Sample.Lab10/Kinect2Sample/App.xaml b/Kinect2Sample/App.xaml similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/App.xaml rename to Kinect2Sample/App.xaml diff --git a/Kinect2Sample.Lab10/Kinect2Sample/App.xaml.cs b/Kinect2Sample/App.xaml.cs similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/App.xaml.cs rename to Kinect2Sample/App.xaml.cs diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Assets/Background.png b/Kinect2Sample/Assets/Background.png similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/Assets/Background.png rename to Kinect2Sample/Assets/Background.png diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Assets/CatEye_left_closed.png b/Kinect2Sample/Assets/CatEye_left_closed.png similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/Assets/CatEye_left_closed.png rename to Kinect2Sample/Assets/CatEye_left_closed.png diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Assets/CatEye_left_open.png b/Kinect2Sample/Assets/CatEye_left_open.png similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/Assets/CatEye_left_open.png rename to Kinect2Sample/Assets/CatEye_left_open.png diff --git a/Kinect2Sample.Lab10/Kinect2Sample/Assets/CatNose.png b/Kinect2Sample/Assets/CatNose.png similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/Assets/CatNose.png rename to Kinect2Sample/Assets/CatNose.png diff --git a/Kinect2Sample.Lab1/Kinect2Sample/Assets/Logo.scale-100.png b/Kinect2Sample/Assets/Logo.scale-100.png similarity index 100% rename from Kinect2Sample.Lab1/Kinect2Sample/Assets/Logo.scale-100.png rename to Kinect2Sample/Assets/Logo.scale-100.png diff --git a/Kinect2Sample.Lab1/Kinect2Sample/Assets/SmallLogo.scale-100.png b/Kinect2Sample/Assets/SmallLogo.scale-100.png similarity index 100% rename from Kinect2Sample.Lab1/Kinect2Sample/Assets/SmallLogo.scale-100.png rename to Kinect2Sample/Assets/SmallLogo.scale-100.png diff --git a/Kinect2Sample.Lab1/Kinect2Sample/Assets/SplashScreen.scale-100.png b/Kinect2Sample/Assets/SplashScreen.scale-100.png similarity index 100% rename from Kinect2Sample.Lab1/Kinect2Sample/Assets/SplashScreen.scale-100.png rename to Kinect2Sample/Assets/SplashScreen.scale-100.png diff --git a/Kinect2Sample.Lab1/Kinect2Sample/Assets/StoreLogo.scale-100.png b/Kinect2Sample/Assets/StoreLogo.scale-100.png similarity index 100% rename from Kinect2Sample.Lab1/Kinect2Sample/Assets/StoreLogo.scale-100.png rename to Kinect2Sample/Assets/StoreLogo.scale-100.png diff --git a/Kinect2Sample.Lab10/Kinect2Sample/BodiesManager.cs b/Kinect2Sample/BodiesManager.cs similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/BodiesManager.cs rename to Kinect2Sample/BodiesManager.cs diff --git a/Kinect2Sample.Lab10/Kinect2Sample/BodyInfo.cs b/Kinect2Sample/BodyInfo.cs similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/BodyInfo.cs rename to Kinect2Sample/BodyInfo.cs diff --git a/Kinect2Sample.Lab12/Kinect2Sample/Database/HandsAboveHead.gbd b/Kinect2Sample/Database/HandsAboveHead.gbd similarity index 100% rename from Kinect2Sample.Lab12/Kinect2Sample/Database/HandsAboveHead.gbd rename to Kinect2Sample/Database/HandsAboveHead.gbd diff --git a/Kinect2Sample.Lab10/Kinect2Sample/DisplayTypeToVisibilityConverter.cs b/Kinect2Sample/DisplayTypeToVisibilityConverter.cs similarity index 100% rename from Kinect2Sample.Lab10/Kinect2Sample/DisplayTypeToVisibilityConverter.cs rename to Kinect2Sample/DisplayTypeToVisibilityConverter.cs diff --git a/Kinect2Sample.Lab12/Kinect2Sample/GestureDetector.cs b/Kinect2Sample/GestureDetector.cs similarity index 100% rename from Kinect2Sample.Lab12/Kinect2Sample/GestureDetector.cs rename to Kinect2Sample/GestureDetector.cs diff --git a/Kinect2Sample.Lab12/Kinect2Sample/GestureResultView.cs b/Kinect2Sample/GestureResultView.cs similarity index 100% rename from Kinect2Sample.Lab12/Kinect2Sample/GestureResultView.cs rename to Kinect2Sample/GestureResultView.cs diff --git a/Kinect2Sample.Lab12/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample/Kinect2Sample.csproj similarity index 100% rename from Kinect2Sample.Lab12/Kinect2Sample/Kinect2Sample.csproj rename to Kinect2Sample/Kinect2Sample.csproj diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample.sln b/Kinect2Sample/Kinect2Sample/Kinect2Sample.sln deleted file mode 100644 index 1c09add..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample.sln +++ /dev/null @@ -1,64 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kinect2Sample", "Kinect2Sample\Kinect2Sample.csproj", "{10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|Mixed Platforms = Release|Mixed Platforms - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|ARM.ActiveCfg = Debug|ARM - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|ARM.Build.0 = Debug|ARM - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|ARM.Deploy.0 = Debug|ARM - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Mixed Platforms.Deploy.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Win32.ActiveCfg = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Win32.Build.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|Win32.Deploy.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.ActiveCfg = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Build.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x64.Deploy.0 = Debug|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.ActiveCfg = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Build.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Debug|x86.Deploy.0 = Debug|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Any CPU.Build.0 = Release|Any CPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Any CPU.Deploy.0 = Release|Any CPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|ARM.ActiveCfg = Release|ARM - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|ARM.Build.0 = Release|ARM - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|ARM.Deploy.0 = Release|ARM - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Mixed Platforms.Build.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Mixed Platforms.Deploy.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Win32.ActiveCfg = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Win32.Build.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|Win32.Deploy.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.ActiveCfg = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Build.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x64.Deploy.0 = Release|x64 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.ActiveCfg = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Build.0 = Release|x86 - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F}.Release|x86.Deploy.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/App.xaml b/Kinect2Sample/Kinect2Sample/Kinect2Sample/App.xaml deleted file mode 100644 index b1a6ab8..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/App.xaml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/App.xaml.cs b/Kinect2Sample/Kinect2Sample/Kinect2Sample/App.xaml.cs deleted file mode 100644 index 4cbd95e..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/App.xaml.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; -using Microsoft.Kinect.Xaml.Controls; - -// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 - -namespace Kinect2Sample -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Gets the app level KinectRegion element, which is created in App.xaml.cs - /// - public KinectRegion KinectRegion { get; private set; } - - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = true; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - // Set the default language - rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Create a CursorLayer that listens to KinectPointerPoints/GestureRecognizers - // and works with the affected controls. - KinectRegion = new Microsoft.Kinect.Xaml.Controls.KinectRegion(); - KinectRegion.Content = rootFrame; - - // Place the frame in the current Window, with a Kinect cursor layer + user viewer control - Window.Current.Content = KinectRegion; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/Background.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/Background.png deleted file mode 100644 index 44e6e19..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/Background.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatEye_left_closed.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatEye_left_closed.png deleted file mode 100644 index 32b7544..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatEye_left_closed.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatEye_left_open.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatEye_left_open.png deleted file mode 100644 index 62c7ac0..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatEye_left_open.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatNose.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatNose.png deleted file mode 100644 index 8732b28..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/CatNose.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/Logo.scale-100.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/Logo.scale-100.png deleted file mode 100644 index e26771c..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/Logo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/SmallLogo.scale-100.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/SmallLogo.scale-100.png deleted file mode 100644 index 1eb0d9d..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/SmallLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/SplashScreen.scale-100.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/SplashScreen.scale-100.png deleted file mode 100644 index c951e03..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/SplashScreen.scale-100.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/StoreLogo.scale-100.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/StoreLogo.scale-100.png deleted file mode 100644 index dcb6727..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Assets/StoreLogo.scale-100.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/BodiesManager.cs b/Kinect2Sample/Kinect2Sample/Kinect2Sample/BodiesManager.cs deleted file mode 100644 index 8c00502..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/BodiesManager.cs +++ /dev/null @@ -1,492 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Foundation; -using Windows.UI; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - public class BodiesManager - { - /// - /// Radius of drawn hand circles - /// - private const double HighConfidenceHandSize = 40; - - /// - /// Radius of drawn hand circles - /// - private const double LowConfidenceHandSize = 20; - - /// - /// Thickness of drawn joint lines - /// - private const double JointThickness = 8.0; - - /// - /// Thickness of seen bone lines - /// - private const double TrackedBoneThickness = 4.0; - - /// - /// Thickness of inferred joint lines - /// - private const double InferredBoneThickness = 1.0; - - /// - /// Thickness of clip edge rectangles - /// - private const double ClipBoundsThickness = 5; - - /// - /// Constant for clamping Z values of camera space points from being negative - /// - private const float InferredZPositionClamp = 0.1f; - - private CoordinateMapper coordinateMapper; - private Canvas drawingCanvas; - - private Rectangle LeftClipEdge; - private Rectangle RightClipEdge; - private Rectangle TopClipEdge; - private Rectangle BottomClipEdge; - - /// - /// List of BodyInfo objects for each potential body - /// - private BodyInfo[] bodyInfos; - - /// - /// List of colors for each body tracked - /// - private List bodyColors; - - private int BodyCount - { - set - { - if (value == 0) - { - this.bodyInfos = null; - return; - } - - // creates instances of BodyInfo objects for potential number of bodies - if (this.bodyInfos == null || this.bodyInfos.Length != value) - { - this.bodyInfos = new BodyInfo[value]; - - for (int bodyIndex = 0; bodyIndex < value; bodyIndex++) - { - this.bodyInfos[bodyIndex] = new BodyInfo(this.bodyColors[bodyIndex], JointThickness); - } - } - } - - get { return this.bodyInfos == null ? 0 : this.bodyInfos.Length; } - } - - /// - /// Maps bodies and joints to render them in a canvas. - /// - /// The current co-ordinate mapper from the Kinect Sensor - /// The canvas upon which the joints and bones are drawn - /// The amount of bodies concurrently drawable - public BodiesManager(CoordinateMapper coordMapper, Canvas drawableCanvas, int bodyCount) - { - this.coordinateMapper = coordMapper; - this.drawingCanvas = drawableCanvas; - // populate body colors, one for each BodyIndex - this.bodyColors = new List - { - Colors.Red, - Colors.Orange, - Colors.Green, - Colors.Blue, - Colors.Indigo, - Colors.Violet - }; - - // sets total number of possible tracked bodies - // create ellipses and lines for drawing bodies - this.BodyCount = bodyCount; - - PopulateVisualJoints(); - } - - /// - /// Instantiate new objects for joints, bone lines, and clipped edge rectangles - /// - private void PopulateVisualJoints() - { - // create clipped edges and set to collapsed initially - this.LeftClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.RightClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = ClipBoundsThickness, - Height = this.drawingCanvas.Height, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.TopClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.BottomClipEdge = new Rectangle() - { - Fill = new SolidColorBrush(Colors.Red), - Width = this.drawingCanvas.Width, - Height = ClipBoundsThickness, - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - foreach (var bodyInfo in this.bodyInfos) - { - // add left and right hand ellipses of all bodies to canvas - this.drawingCanvas.Children.Add(bodyInfo.HandLeftEllipse); - this.drawingCanvas.Children.Add(bodyInfo.HandRightEllipse); - - // add joint ellipses of all bodies to canvas - foreach (var joint in bodyInfo.JointPoints) - { - this.drawingCanvas.Children.Add(joint.Value); - } - - // add bone lines of all bodies to canvas - foreach (var bone in bodyInfo.Bones) - { - this.drawingCanvas.Children.Add(bodyInfo.BoneLines[bone]); - } - } - - // add clipped edges rectanges to main canvas - this.drawingCanvas.Children.Add(this.LeftClipEdge); - this.drawingCanvas.Children.Add(this.RightClipEdge); - this.drawingCanvas.Children.Add(this.TopClipEdge); - this.drawingCanvas.Children.Add(this.BottomClipEdge); - - // position the clipped edges - Canvas.SetLeft(this.LeftClipEdge, 0); - Canvas.SetTop(this.LeftClipEdge, 0); - Canvas.SetLeft(this.RightClipEdge, this.drawingCanvas.Width - ClipBoundsThickness); - Canvas.SetTop(this.RightClipEdge, 0); - Canvas.SetLeft(this.TopClipEdge, 0); - Canvas.SetTop(this.TopClipEdge, 0); - Canvas.SetLeft(this.BottomClipEdge, 0); - Canvas.SetTop(this.BottomClipEdge, this.drawingCanvas.Height - ClipBoundsThickness); - } - - /// - /// Updates all elipses and lines representing joints and bones - /// with the latest tracked bodies. - /// - /// An array containing body data. - internal void UpdateBodiesAndEdges(Body[] bodies) - { - bool hasTrackedBody = false; - // iterate through each body - for (int bodyIndex = 0; bodyIndex < bodies.Length; bodyIndex++) - { - Body body = bodies[bodyIndex]; - - if (body.IsTracked) - { - // check if this body clips an edge - this.UpdateClippedEdges(body, hasTrackedBody); - - this.UpdateBody(body, bodyIndex); - - hasTrackedBody = true; - } - else - { - // collapse this body from canvas as it goes out of view - this.ClearBody(bodyIndex); - } - } - - if (!hasTrackedBody) - { - // clear clipped edges if no bodies are tracked - this.ClearClippedEdges(); - } - } - - /// - /// Update body data for each body that is tracked. - /// - /// body for getting joint info - /// index for body we are currently updating - internal void UpdateBody(Body body, int bodyIndex) - { - IReadOnlyDictionary joints = body.Joints; - var jointPointsInDepthSpace = new Dictionary(); - - var bodyInfo = this.bodyInfos[bodyIndex]; - - // update all joints - foreach (var jointType in body.Joints.Keys) - { - // sometimes the depth(Z) of an inferred joint may show as negative - // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity) - CameraSpacePoint position = body.Joints[jointType].Position; - if (position.Z < 0) - { - position.Z = InferredZPositionClamp; - } - - // map joint position to depth space - DepthSpacePoint depthSpacePoint = coordinateMapper.MapCameraPointToDepthSpace(position); - jointPointsInDepthSpace[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y); - - // modify the joint's visibility and location - this.UpdateJoint(bodyInfo.JointPoints[jointType], joints[jointType], jointPointsInDepthSpace[jointType]); - - // modify hand ellipse colors based on hand states - // modity hand ellipse sizes based on tracking confidences - if (jointType == JointType.HandRight) - { - this.UpdateHand(bodyInfo.HandRightEllipse, body.HandRightState, body.HandRightConfidence, jointPointsInDepthSpace[jointType]); - } - - if (jointType == JointType.HandLeft) - { - this.UpdateHand(bodyInfo.HandLeftEllipse, body.HandLeftState, body.HandLeftConfidence, jointPointsInDepthSpace[jointType]); - } - } - - // update all bones - foreach (var bone in bodyInfo.Bones) - { - this.UpdateBone(bodyInfo.BoneLines[bone], joints[bone.Item1], joints[bone.Item2], - jointPointsInDepthSpace[bone.Item1], - jointPointsInDepthSpace[bone.Item2]); - } - } - /// - /// Updates hand state ellipses depending on tracking state and it's confidence. - /// - /// ellipse representing handstate - /// open, closed, or lasso - /// confidence of handstate - /// location of handjoint - private void UpdateHand(Ellipse ellipse, HandState handState, TrackingConfidence trackingConfidence, Point point) - { - ellipse.Fill = new SolidColorBrush(this.HandStateToColor(handState)); - - // draw handstate ellipse based on tracking confidence - ellipse.Width = ellipse.Height = (trackingConfidence == TrackingConfidence.Low) ? LowConfidenceHandSize : HighConfidenceHandSize; - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - - // don't draw handstate if hand joints are not tracked - if (!Double.IsInfinity(point.X) && !Double.IsInfinity(point.Y)) - { - Canvas.SetLeft(ellipse, point.X - ellipse.Width / 2); - Canvas.SetTop(ellipse, point.Y - ellipse.Width / 2); - } - } - - /// - /// Update a joint. - /// - /// - /// - /// - private void UpdateJoint(Ellipse ellipse, Joint joint, Point point) - { - TrackingState trackingState = joint.TrackingState; - - // only draw if joint is tracked or inferred - if (trackingState != TrackingState.NotTracked) - { - if (trackingState == TrackingState.Tracked) - { - ellipse.Fill = new SolidColorBrush(Colors.Green); - } - else - { - // inferred joints are yellow - ellipse.Fill = new SolidColorBrush(Colors.Yellow); - } - - Canvas.SetLeft(ellipse, point.X - JointThickness / 2); - Canvas.SetTop(ellipse, point.Y - JointThickness / 2); - - ellipse.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else - { - ellipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Update a bone line. - /// - /// line representing a bone line - /// start joint of bone line - /// end joint of bone line - /// location of start joint - /// location of end joint - private void UpdateBone(Line line, Joint startJoint, Joint endJoint, Point startPoint, Point endPoint) - { - // don't draw if neither joints are tracked - if (startJoint.TrackingState == TrackingState.NotTracked || endJoint.TrackingState == TrackingState.NotTracked) - { - line.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - return; - } - - // all lines are inferred thickness unless both joints are tracked - line.StrokeThickness = InferredBoneThickness; - - if (startJoint.TrackingState == TrackingState.Tracked && - endJoint.TrackingState == TrackingState.Tracked) - { - line.StrokeThickness = TrackedBoneThickness; - } - - line.Visibility = Windows.UI.Xaml.Visibility.Visible; - - line.X1 = startPoint.X; - line.Y1 = startPoint.Y; - line.X2 = endPoint.X; - line.Y2 = endPoint.Y; - } - - /// - /// Draws indicators to show which edges are clipping body data. - /// - /// body to draw clipping information for - /// bool to determine if another body is triggering a clipped edge - private void UpdateClippedEdges(Body body, bool hasTrackedBody) - { - // BUG (waiting for confirmation): - // Clip dectection works differently for top and right edges compared to left and bottom edges - // due to the current joint confidence model. This is an ST issue. - // Joints become inferred immediately as they touch the left/bottom edges and clip detection triggers. - // Joints squish on the right/top edges and clip detection doesn't trigger until more joints of - // the body goes out of view (e.g all hand joints vs only handtip). - - FrameEdges clippedEdges = body.ClippedEdges; - - if (clippedEdges.HasFlag(FrameEdges.Left)) - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - // don't clear this edge if another body is triggering clipped edge - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Right)) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Top)) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - if (clippedEdges.HasFlag(FrameEdges.Bottom)) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Visible; - } - else if (!hasTrackedBody) - { - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } - - /// - /// Select color of hand state - /// - /// - /// - private Color HandStateToColor(HandState handState) - { - switch (handState) - { - case HandState.Open: - return Colors.Green; - - case HandState.Closed: - return Colors.Red; - - case HandState.Lasso: - return Colors.Blue; - } - - return Colors.Transparent; - } - - /// - /// Collapse the body from the canvas. - /// - /// - private void ClearBody(int bodyIndex) - { - var bodyInfo = this.bodyInfos[bodyIndex]; - - // collapse all joint ellipses - foreach (var joint in bodyInfo.JointPoints) - { - joint.Value.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse all bone lines - foreach (var bone in bodyInfo.Bones) - { - bodyInfo.BoneLines[bone].Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - // collapse handstate ellipses - bodyInfo.HandLeftEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - bodyInfo.HandRightEllipse.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - - /// - /// Clear all clipped edges. - /// - private void ClearClippedEdges() - { - this.LeftClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.RightClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.TopClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - - this.BottomClipEdge.Visibility = Windows.UI.Xaml.Visibility.Collapsed; - } - } -} diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/BodyInfo.cs b/Kinect2Sample/Kinect2Sample/Kinect2Sample/BodyInfo.cs deleted file mode 100644 index 2f03930..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/BodyInfo.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using WindowsPreview.Kinect; - -namespace Kinect2Sample -{ - /// - /// BodyInfo class that contains joint ellipses, handstate ellipses, lines for bones between two joints. - /// - public class BodyInfo - { - public bool Updated { get; set; } - - public Color BodyColor { get; set; } - - // ellipse representing left handstate - public Ellipse HandLeftEllipse { get; set; } - - // ellipse representing right handstate - public Ellipse HandRightEllipse { get; set; } - - // dictionary of all joints in a body - public Dictionary JointPoints { get; private set; } - - // definition of bones - public TupleList Bones { get; private set; } - - // collection of bones associated with the line object - public Dictionary, Line> BoneLines { get; private set; } - - public BodyInfo(Color bodyColor, double jointThickness) - { - this.BodyColor = bodyColor; - - // create hand state ellipses - this.HandLeftEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - this.HandRightEllipse = new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed - }; - - // a joint defined as a jointType with a point location in XY space represented by an ellipse - this.JointPoints = new Dictionary(); - - // pre-populate list of joints and set to non-visible initially - foreach (JointType jointType in Enum.GetValues(typeof(JointType))) - { - this.JointPoints.Add(jointType, new Ellipse() - { - Visibility = Windows.UI.Xaml.Visibility.Collapsed, - Fill = new SolidColorBrush(BodyColor), - Width = jointThickness, - Height = jointThickness - }); - } - - // collection of bones - this.BoneLines = new Dictionary, Line>(); - - // a bone defined as a line between two joints - this.Bones = new TupleList - { - // Torso - { JointType.Head, JointType.Neck }, - { JointType.Neck, JointType.SpineShoulder }, - { JointType.SpineShoulder, JointType.SpineMid }, - { JointType.SpineMid, JointType.SpineBase }, - { JointType.SpineShoulder, JointType.ShoulderRight }, - { JointType.SpineShoulder, JointType.ShoulderLeft }, - { JointType.SpineBase, JointType.HipRight }, - { JointType.SpineBase, JointType.HipLeft }, - - // Right Arm - { JointType.ShoulderRight, JointType.ElbowRight }, - { JointType.ElbowRight, JointType.WristRight }, - { JointType.WristRight, JointType.HandRight }, - { JointType.HandRight, JointType.HandTipRight }, - { JointType.WristRight, JointType.ThumbRight }, - - // Left Arm - { JointType.ShoulderLeft, JointType.ElbowLeft }, - { JointType.ElbowLeft, JointType.WristLeft }, - { JointType.WristLeft, JointType.HandLeft }, - { JointType.HandLeft, JointType.HandTipLeft }, - { JointType.WristLeft, JointType.ThumbLeft }, - - // Right Leg - { JointType.HipRight, JointType.KneeRight }, - { JointType.KneeRight, JointType.AnkleRight }, - { JointType.AnkleRight, JointType.FootRight }, - - // Left Leg - { JointType.HipLeft, JointType.KneeLeft }, - { JointType.KneeLeft, JointType.AnkleLeft }, - { JointType.AnkleLeft, JointType.FootLeft }, - }; - - // pre-populate list of bones that are non-visible initially - foreach (var bone in this.Bones) - { - this.BoneLines.Add(bone, new Line() - { - Stroke = new SolidColorBrush(BodyColor), - Visibility = Visibility.Collapsed - }); - } - } - } - - public class TupleList : List> - { - public void Add(T1 item, T2 item2) - { - this.Add(new Tuple(item, item2)); - } - } - -} diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Database/HandsAboveHead.gbd b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Database/HandsAboveHead.gbd deleted file mode 100644 index 6533db9..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Database/HandsAboveHead.gbd and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/DisplayTypeToVisibilityConverter.cs b/Kinect2Sample/Kinect2Sample/Kinect2Sample/DisplayTypeToVisibilityConverter.cs deleted file mode 100644 index 1b2c5d0..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/DisplayTypeToVisibilityConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Data; - -namespace Kinect2Sample -{ - class DisplayTypeToVisibilityConverter :IValueConverter - { - public object Convert(object value, Type targetType, object parameter, string language) - { - String boundString = Enum.GetName(typeof(DisplayFrameType), value); - String matchString = (String)parameter; - - if (String.Equals(boundString, matchString)) - { - return Visibility.Visible; - } - else - { - return Visibility.Collapsed; - } - } - - public object ConvertBack(object value, Type targetType, object parameter, string language) - { - throw new NotImplementedException(); - } - } -} diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/GestureDetector.cs b/Kinect2Sample/Kinect2Sample/Kinect2Sample/GestureDetector.cs deleted file mode 100644 index 75bdc0c..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/GestureDetector.cs +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -//------------------------------------------------------------------------------ - -namespace Kinect2Sample -{ - using System; - using System.Collections.Generic; - using Microsoft.Kinect; - using Microsoft.Kinect.VisualGestureBuilder; - using WindowsPreview.Kinect; - using Windows.UI.Xaml; - using WindowsPreview.Data; - - /// - /// Gesture Detector class which listens for VisualGestureBuilderFrame events from the service - /// and updates the associated GestureResultView object with the latest results for the gesture - /// - public class GestureDetector : IDisposable - { - //public RoutedEventHandler GestureRecognized { get; set; } - - //important lab 13 - /// Path to the gesture database that was trained with VGB - private readonly string gestureDatabase = @"Database\HandsAboveHead.gbd"; - - //important lab 13 - /// Name of the discrete gesture in the database that we want to track - private readonly string handsAboveHeadGestureName = "HandsAboveHead"; - - /// Gesture frame source which should be tied to a body tracking ID - private VisualGestureBuilderFrameSource vgbFrameSource = null; - - /// Gesture frame reader which will handle gesture events coming from the sensor - private VisualGestureBuilderFrameReader vgbFrameReader = null; - - /// - /// Initializes a new instance of the GestureDetector class along with the gesture frame source and reader - /// - /// Active sensor to initialize the VisualGestureBuilderFrameSource object with - /// GestureResultView object to store gesture results of a single body to - public GestureDetector(KinectSensor kinectSensor, GestureResultView gestureResultView) - { - if (kinectSensor == null) - { - throw new ArgumentNullException("kinectSensor"); - } - - if (gestureResultView == null) - { - throw new ArgumentNullException("gestureResultView"); - } - - this.GestureResultView = gestureResultView; - - // create the vgb source. The associated body tracking ID will be set when a valid body frame arrives from the sensor. - this.vgbFrameSource = new VisualGestureBuilderFrameSource(kinectSensor, 0); - this.vgbFrameSource.TrackingIdLost += this.Source_TrackingIdLost; - - // open the reader for the vgb frames - this.vgbFrameReader = this.vgbFrameSource.OpenReader(); - if (this.vgbFrameReader != null) - { - this.vgbFrameReader.IsPaused = true; - this.vgbFrameReader.FrameArrived += this.Reader_GestureFrameArrived; - } - - // load the 'Seated' gesture from the gesture database - using (VisualGestureBuilderDatabase database = new VisualGestureBuilderDatabase(this.gestureDatabase)) - { - // we could load all available gestures in the database with a call to vgbFrameSource.AddGestures(database.AvailableGestures), - // but for this program, we only want to track one discrete gesture from the database, so we'll load it by name - //foreach (Gesture gesture in database.AvailableGestures) - //{ - // if (gesture.Name.Equals(this.seatedGestureName)) - // { - // this.vgbFrameSource.AddGesture(gesture); - // } - //} - - // we could load all available gestures in the database with a call to vgbFrameSource.AddGestures(database.AvailableGestures), - // but for this program, we only want to track one discrete gesture from the database, so we'll load it by name - foreach (Gesture gesture in database.AvailableGestures) - { - if (gesture.Name.Equals(this.handsAboveHeadGestureName)) - { - this.vgbFrameSource.AddGesture(gesture); - } - } - } - } - - /// Gets the GestureResultView object which stores the detector results for display in the UI - public GestureResultView GestureResultView { get; private set; } - - /// - /// Gets or sets the body tracking ID associated with the current detector - /// The tracking ID can change whenever a body comes in/out of scope - /// - public ulong TrackingId - { - get - { - return this.vgbFrameSource.TrackingId; - } - - set - { - if (this.vgbFrameSource.TrackingId != value) - { - this.vgbFrameSource.TrackingId = value; - } - } - } - - /// - /// Gets or sets a value indicating whether or not the detector is currently paused - /// If the body tracking ID associated with the detector is not valid, then the detector should be paused - /// - public bool IsPaused - { - get - { - return this.vgbFrameReader.IsPaused; - } - - set - { - if (this.vgbFrameReader.IsPaused != value) - { - this.vgbFrameReader.IsPaused = value; - } - } - } - - public bool GestureRecognized - { - get - { - return this.GestureRecognized; - } - - set - { - if (this.GestureRecognized != value) - { - this.GestureRecognized = value; - } - } - } - - /// - /// Disposes all unmanaged resources for the class - /// - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes the VisualGestureBuilderFrameSource and VisualGestureBuilderFrameReader objects - /// - /// True if Dispose was called directly, false if the GC handles the disposing - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - if (this.vgbFrameReader != null) - { - this.vgbFrameReader.FrameArrived -= this.Reader_GestureFrameArrived; - this.vgbFrameReader.Dispose(); - this.vgbFrameReader = null; - } - - if (this.vgbFrameSource != null) - { - this.vgbFrameSource.TrackingIdLost -= this.Source_TrackingIdLost; - this.vgbFrameSource.Dispose(); - this.vgbFrameSource = null; - } - } - } - - /// - /// Handles gesture detection results arriving from the sensor for the associated body tracking Id - /// - /// object sending the event - /// event arguments - private void Reader_GestureFrameArrived(object sender, VisualGestureBuilderFrameArrivedEventArgs e) - { - VisualGestureBuilderFrameReference frameReference = e.FrameReference; - using (VisualGestureBuilderFrame frame = frameReference.AcquireFrame()) - { - if (frame != null) - { - // get the discrete gesture results which arrived with the latest frame - IReadOnlyDictionary discreteResults = frame.DiscreteGestureResults; - - if (discreteResults != null) - { - // we only have one gesture in this source object, but you can get multiple gestures - foreach (Gesture gesture in this.vgbFrameSource.Gestures) - { - //if (gesture.Name.Equals(this.seatedGestureName) && gesture.GestureType == GestureType.Discrete) - //{ - // DiscreteGestureResult result = null; - // discreteResults.TryGetValue(gesture, out result); - - // if (result != null) - // { - // // update the GestureResultView object with new gesture result values - // this.GestureResultView.UpdateGestureResult(true, result.Detected, result.Confidence); - // } - //} - - if (gesture.Name.Equals(this.handsAboveHeadGestureName) && gesture.GestureType == GestureType.Discrete) - { - DiscreteGestureResult result = null; - discreteResults.TryGetValue(gesture, out result); - - if (result != null) - { - // update the GestureResultView object with new gesture result values - this.GestureResultView.UpdateGestureResult(true, result.Detected, result.Confidence); - } - } - } - } - } - } - } - - /// - /// Handles the TrackingIdLost event for the VisualGestureBuilderSource object - /// - /// object sending the event - /// event arguments - private void Source_TrackingIdLost(object sender, TrackingIdLostEventArgs e) - { - // update the GestureResultView object to show the 'Not Tracked' image in the UI - this.GestureResultView.UpdateGestureResult(false, false, 0.0f); - } - } -} diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/GestureResultView.cs b/Kinect2Sample/Kinect2Sample/Kinect2Sample/GestureResultView.cs deleted file mode 100644 index c44407a..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/GestureResultView.cs +++ /dev/null @@ -1,181 +0,0 @@ -//------------------------------------------------------------------------------ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -//------------------------------------------------------------------------------ - -namespace Kinect2Sample -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Runtime.CompilerServices; - using Windows.Graphics.Display; - using Windows.Graphics.Imaging; - using Windows.Storage; - using Windows.Storage.Pickers; - using Windows.UI.Xaml; - using Windows.UI.Xaml.Media; - using Windows.UI.Xaml.Media.Imaging; - - /// - /// Stores discrete gesture results for the GestureDetector. - /// Properties are stored/updated for display in the UI. - /// - public sealed class GestureResultView : INotifyPropertyChanged - { - /// The body index (0-5) associated with the current gesture detector - private int bodyIndex = 0; - - /// Current confidence value reported by the discrete gesture - private float confidence = 0.0f; - - /// True, if the discrete gesture is currently being detected - private bool detected = false; - - /// True, if the body is currently being tracked - private bool isTracked = false; - - /// - /// Initializes a new instance of the GestureResultView class and sets initial property values - /// - /// Body Index associated with the current gesture detector - /// True, if the body is currently tracked - /// True, if the gesture is currently detected for the associated body - /// Confidence value for detection of the 'Seated' gesture - public GestureResultView(int bodyIndex, bool isTracked, bool detected, float confidence) - { - this.BodyIndex = bodyIndex; - this.IsTracked = isTracked; - this.Detected = detected; - this.Confidence = confidence; - } - - /// - /// INotifyPropertyChangedPropertyChanged event to allow window controls to bind to changeable data - /// - public event PropertyChangedEventHandler PropertyChanged; - - /// - /// Gets the body index associated with the current gesture detector result - /// - public int BodyIndex - { - get - { - return this.bodyIndex; - } - - private set - { - if (this.bodyIndex != value) - { - this.bodyIndex = value; - this.NotifyPropertyChanged(); - } - } - } - - /// - /// Gets a value indicating whether or not the body associated with the gesture detector is currently being tracked - /// - public bool IsTracked - { - get - { - return this.isTracked; - } - - private set - { - if (this.IsTracked != value) - { - this.isTracked = value; - this.NotifyPropertyChanged(); - } - } - } - - /// - /// Gets a value indicating whether or not the discrete gesture has been detected - /// - public bool Detected - { - get - { - return this.detected; - } - - private set - { - if (this.detected != value) - { - this.detected = value; - this.NotifyPropertyChanged(); - } - } - } - - /// - /// Gets a float value which indicates the detector's confidence that the gesture is occurring for the associated body - /// - public float Confidence - { - get - { - return this.confidence; - } - - private set - { - if (this.confidence != value) - { - this.confidence = value; - this.NotifyPropertyChanged(); - } - } - } - - /// - /// Updates the values associated with the discrete gesture detection result - /// - /// True, if the body associated with the GestureResultView object is still being tracked - /// True, if the discrete gesture is currently detected for the associated body - /// Confidence value for detection of the discrete gesture - public void UpdateGestureResult(bool isBodyTrackingIdValid, bool isGestureDetected, float detectionConfidence) - { - this.IsTracked = isBodyTrackingIdValid; - this.Confidence = 0.0f; - - if (!this.IsTracked) - { - this.Detected = false; - } - else - { - this.Detected = isGestureDetected; - - if (this.Detected) - { - this.Confidence = detectionConfidence; - } - else - { - - } - } - } - - /// - /// Notifies UI that a property has changed - /// - /// Name of property that has changed - private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } - } -} diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Kinect2Sample.csproj b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Kinect2Sample.csproj deleted file mode 100644 index fb80d29..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Kinect2Sample.csproj +++ /dev/null @@ -1,198 +0,0 @@ - - - - - Debug - AnyCPU - {10FF1E4E-A8B9-46C6-A0C3-C7BADF94941F} - AppContainerExe - Properties - Kinect2Sample - Kinect2Sample - en-US - 8.1 - 12 - 512 - {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Kinect2Sample_TemporaryKey.pfx - - - x86 - true - full - false - bin\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - prompt - 4 - - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x86 - false - prompt - true - - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - ARM - false - prompt - true - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x64 - false - prompt - true - true - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x64 - false - prompt - true - true - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_APP - ;2008 - full - x86 - false - prompt - true - true - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_APP - true - ;2008 - pdbonly - x86 - false - prompt - true - true - - - - App.xaml - - - - - - - - MainPage.xaml - - - - - - Designer - - - Always - - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - Microsoft.Kinect.Face - - - Microsoft.Kinect.Toolkit.Input - - - Microsoft.Kinect.VisualGestureBuilder - - - Microsoft.Kinect.Xaml.Controls - - - Microsoft Visual C++ 2013 Runtime Package for Windows - - - WindowsPreview.Kinect - - - - - False - Libraries\DirectXSceneStore.winmd - - - False - Libraries\KinectFaceStore.dll - - - - 12.0 - - - - \ No newline at end of file diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx deleted file mode 100644 index 7cb3591..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Kinect2Sample_TemporaryKey.pfx and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/KinectRegionStyles.xaml b/Kinect2Sample/Kinect2Sample/Kinect2Sample/KinectRegionStyles.xaml deleted file mode 100644 index fbd0ec9..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/KinectRegionStyles.xaml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - - - - diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.dll b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.dll deleted file mode 100644 index 2c91ab2..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.dll and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.pri b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.pri deleted file mode 100644 index bafa749..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.pri and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.winmd b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.winmd deleted file mode 100644 index 5f5cdda..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore.winmd and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/bounce.wav b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/bounce.wav deleted file mode 100644 index 8267695..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/bounce.wav and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellceiling.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellceiling.dds deleted file mode 100644 index dd24b59..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellceiling.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellfloor.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellfloor.dds deleted file mode 100644 index 790df24..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellfloor.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellwall.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellwall.dds deleted file mode 100644 index 7bfc4af..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/cellwall.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/dayceiling.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/dayceiling.dds deleted file mode 100644 index 6148ae3..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/dayceiling.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/dayfloor.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/dayfloor.dds deleted file mode 100644 index 22f11fa..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/dayfloor.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/daywall.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/daywall.dds deleted file mode 100644 index 6148ae3..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/daywall.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/hit.wav b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/hit.wav deleted file mode 100644 index f4a78ac..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/hit.wav and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/mediumTile-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/mediumTile-sdk.png deleted file mode 100644 index 1c9f68e..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/mediumTile-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/metal_texture.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/metal_texture.dds deleted file mode 100644 index af2e355..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/metal_texture.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightceiling.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightceiling.dds deleted file mode 100644 index 291a923..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightceiling.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightfloor.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightfloor.dds deleted file mode 100644 index 04e424b..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightfloor.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightwall.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightwall.dds deleted file mode 100644 index 291a923..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/nightwall.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/seafloor.dds b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/seafloor.dds deleted file mode 100644 index 3c8eed9..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/seafloor.dds and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/smallTile-phone-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/smallTile-phone-sdk.png deleted file mode 100644 index 4476cda..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/smallTile-phone-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/smallTile-windows-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/smallTile-windows-sdk.png deleted file mode 100644 index e39b01f..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/smallTile-windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/splash-phone-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/splash-phone-sdk.png deleted file mode 100644 index 435f872..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/splash-phone-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/splash-windows-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/splash-windows-sdk.png deleted file mode 100644 index e00df02..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/splash-windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/squareTile-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/squareTile-sdk.png deleted file mode 100644 index 2a8cf87..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/squareTile-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/storeLogo-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/storeLogo-sdk.png deleted file mode 100644 index 5c397de..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/storeLogo-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/tile-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/tile-sdk.png deleted file mode 100644 index f72683f..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/tile-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/windows-sdk.png b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/windows-sdk.png deleted file mode 100644 index 6726802..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/Assets/windows-sdk.png and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/GameUIStyles.xbf b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/GameUIStyles.xbf deleted file mode 100644 index faae63d..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/GameUIStyles.xbf and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/PixelShader.cso b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/PixelShader.cso deleted file mode 100644 index 96f56e3..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/PixelShader.cso and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/PixelShaderFlat.cso b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/PixelShaderFlat.cso deleted file mode 100644 index fc57594..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/PixelShaderFlat.cso and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/ScenePanel.xbf b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/ScenePanel.xbf deleted file mode 100644 index e75cb98..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/ScenePanel.xbf and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/VertexShader.cso b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/VertexShader.cso deleted file mode 100644 index c4b50be..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/VertexShader.cso and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/VertexShaderFlat.cso b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/VertexShaderFlat.cso deleted file mode 100644 index bfffc0f..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/DirectXSceneStore/VertexShaderFlat.cso and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/KinectFaceStore.dll b/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/KinectFaceStore.dll deleted file mode 100644 index 5b9dd2e..0000000 Binary files a/Kinect2Sample/Kinect2Sample/Kinect2Sample/Libraries/KinectFaceStore.dll and /dev/null differ diff --git a/Kinect2Sample/Kinect2Sample/Kinect2Sample/MainPage.xaml b/Kinect2Sample/Kinect2Sample/Kinect2Sample/MainPage.xaml deleted file mode 100644 index a1b7adf..0000000 --- a/Kinect2Sample/Kinect2Sample/Kinect2Sample/MainPage.xaml +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -