21 Commits

Author SHA1 Message Date
3e3620d925 Patch - Update 2024-09-29 18:19:49 +02:00
c9ece7b9b9 ajout des fichier obj forcer 2024-09-29 17:57:16 +02:00
97e4a62f20 obj gitignore 2024-09-29 17:52:25 +02:00
64ae50814f Mise à jour des inclusions de fichiers OBJ
Les fichiers OBJ dans `enginecustom.vcxproj` ont été modifiés pour être inclus en tant que `CopyFileToFolders` au lieu de `Object`, avec le type de fichier spécifié comme `Document`. Les filtres correspondants dans `enginecustom.vcxproj.filters` ont également été mis à jour pour refléter ce changement, en maintenant le filtre `Assets\Model\OBJ` pour chaque fichier OBJ.
2024-09-29 17:43:56 +02:00
9f3b4c4f1a Archi update 2024-09-29 17:39:22 +02:00
0ce02071bb gitignore 2024-09-29 17:30:38 +02:00
48624a2135 gitignore 2024-09-29 17:28:55 +02:00
fa2544d596 MAJOR UPDATE - ARCHITECTURE 2024-09-29 17:27:30 +02:00
68e460c5df Major Update - Texture Change 2024-09-29 13:57:26 +02:00
bbbea117c3 MAJOR UPDATE - REWORK TEXTURE
-support texture tga retirer

+support texture format standard ajouter
2024-09-29 13:24:18 +02:00
c4b4ef83e3 hummm 2024-09-28 22:03:35 +02:00
6e6db2cf87 Project Name - Update 2024-09-28 20:24:39 +02:00
b45707c620 Patch - Rename Project 2024-09-28 20:23:19 +02:00
e20a2aa365 MAJOR UPDATE - BROKEN
- New way of loading Texture
2024-09-28 20:16:44 +02:00
CatChow0
6a8172ab1f Merge pull request #2 from CatChow0/Cel-Shading
Cel shading
2024-09-27 14:36:44 +02:00
1e6ea97fd0 MONKEYYYY 2024-09-26 21:55:33 +02:00
002edb6651 FIX DEBUG VS 2024-09-26 20:51:39 +02:00
30b41922d9 Cel shade c'est mieux mais ALED 2024-09-26 11:30:26 +02:00
71403c614d Cel shading Update 2024-09-25 12:40:02 +02:00
CatChow0
1b8b25ce2a Update README.md 2024-09-24 12:24:57 +02:00
eea4518a0a Cel Shading [WIP]
+ Cel shading shader
+ Shader Manager window
2024-09-24 12:16:22 +02:00
87 changed files with 11629 additions and 321 deletions

6
.gitignore vendored
View File

@@ -12,11 +12,7 @@
*.obj *.obj
# Don't ignore 3d model in OBJ # Don't ignore 3d model in OBJ
!enginecustom/monke.obj !enginecustom/assets/Model/OBJ/*.obj
!enginecustom/isosphere.obj
!enginecustom/cone.obj
!enginecustom/vaisseau.obj
!enginecustom/86.obj
# Precompiled Headers # Precompiled Headers
*.gch *.gch

View File

@@ -1,8 +1,8 @@
# Khaotic Engine - C++ Custom Engine # Khaotic Engine Reborn - C++ Custom Engine
Khaotic Engine est un moteur de rendu fait en **C++** réalisé par une petite équipe dans le but d'apprendre à utiliser les API de rendu (OpenGL,DirectX 11/12 et Vulkan). Khaotic Engine Reborn reprend comme base le moteur Khaotic Engine pour lui ajouter plus de fonctionalité.
Ce moteur est basé sur **DirectX11** utilise **ImGui** et **Boost** avec une couche d'abstraction pour permetre son usage avec d'autres API. Ce moteur est basé sur **DirectX11** utilise **ImGui** avec une couche d'abstraction pour permetre son usage avec d'autres API.
--- ---
@@ -31,77 +31,23 @@ This **DirectX11** based engine uses **ImGui** with an abstraction layer to enab
## Shaders list: ## Nouvauté Aporté par Khaotic Engine Reborn
**SHADER** :
- **Diffuse Lighting** - Cel Shading
- **Ambiant Lighting**
- **Specular Lighting**
- **Light Shader**
- **Light Map Shader**
- **Alpha Mapping**
- **Normal Mapping**
- **Specular Mapping**
- **Clipping Planes**
- **Texture Translation**
- **Transparency**
- **Water**
- **Refraction**
- *Reflection (cassé / broken)*
*Plus de shaders seront disponibles dans le futur*
---
*More shaders will be added in the future*
## ImGui:
*Cette partie du moteur est encore en développement, d'autres fonctionnalitées seront ajoutées dans le futur*
La librairie ImGui est utilisée afin d'intéragir avec les éléments du moteur comme les objets.
### Fonctionnalitées:
- Importer des objets 3D sous format **.obj**
- Ajout d'un cube à la scène
- Modifier les propriétées d'un objet (Position, Rotation, Taille)
- Modifier les objets présents dans la scène
- Création d'un terrain
- Modifier les propriétées des lumières (Position, Couleur RVB)
----
*This part of the engine is still in development, other features will be added in the future*
ImGui is used to allow interaction between the user and the objects in the scene.
### Features:
- Import 3D objects with the **.obj** format
- Can add a cube to the scene
- Edit an object properties (Position, Rotation, Scale)
- Edit objects in the current scene
- Terrain generation
- Edit lights properties (Position, RGB Color)
**Interface Graphique** :
- Shader Manager
## Demo : ## Demo :
[![Demo Video](https://img.youtube.com/vi/qCOCTyB_97c/0.jpg)](https://www.youtube.com/watch?v=qCOCTyB_97c) [![Demo Video](https://img.youtube.com/vi/qCOCTyB_97c/0.jpg)](https://www.youtube.com/watch?v=qCOCTyB_97c)
## Bug Report :
Vous pouvez signalez les problèmes en ouvrant un ticket dans [Issues](https://github.com/GamingCampus-AdrienBourgois/khaotic-engine/issues)
----
You can report bugs with the program by creating a ticket in [Issues](https://github.com/GamingCampus-AdrienBourgois/khaotic-engine/issues)
## Engine Build by : ## Engine Build by :
[](https://github.com/GamingCampus-AdrienBourgois/khaotic-engine?tab=readme-ov-file#engine-build-by-) **Moteur D'origine** :
- [@CatChow0](https://github.com/CatChow0) - [@CatChow0](https://github.com/CatChow0)
- [@miragefr0st](https://github.com/miragefr0st) - [@miragefr0st](https://github.com/miragefr0st)
@@ -113,6 +59,6 @@ You can report bugs with the program by creating a ticket in [Issues](https://gi
- [@sutabasuto](https://github.com/sutabasuto) - [@sutabasuto](https://github.com/sutabasuto)
**Moteur Reborn** :
- [@CatChow0](https://github.com/CatChow0)

View File

@@ -0,0 +1,410 @@
#include "CelShadingShader.h"
#include <iostream>
CelShadingShader::CelShadingShader()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_matrixBuffer = 0;
m_sampleState = 0;
m_lightBuffer = 0;
}
CelShadingShader::CelShadingShader(const CelShadingShader& other)
{
}
CelShadingShader::~CelShadingShader()
{
}
bool CelShadingShader::Initialize(ID3D11Device* device, HWND hwnd)
{
Logger::Get().Log("Initializing CelShadingShader", __FILE__, __LINE__, Logger::LogLevel::Initialize);
bool result;
wchar_t vsFilename[128];
wchar_t psFilename[128];
int error;
// Set the filename of the vertex shader.
error = wcscpy_s(vsFilename, 128, L"celshading.vs");
if (error != 0)
{
Logger::Get().Log("Failed to set the filename of the vertex shader", __FILE__, __LINE__);
return false;
}
// Set the filename of the pixel shader.
error = wcscpy_s(psFilename, 128, L"celshading.ps");
if (error != 0)
{
Logger::Get().Log("Failed to set the filename of the pixel shader", __FILE__, __LINE__);
return false;
}
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, vsFilename, psFilename);
if (!result)
{
Logger::Get().Log("Failed to initialize the vertex and pixel shaders", __FILE__, __LINE__);
return false;
}
Logger::Get().Log("Successfully initialized CelShadingShader", __FILE__, __LINE__, Logger::LogLevel::Initialize);
return true;
}
void CelShadingShader::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
}
bool CelShadingShader::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
ID3D11ShaderResourceView* texture, XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor, XMFLOAT3 lightPosition)
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, lightDirection, diffuseColor, lightPosition);
if (!result)
{
Logger::Get().Log("CelShading Error", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
}
bool CelShadingShader::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
HRESULT result;
ID3D10Blob* errorMessage = nullptr;
ID3D10Blob* vertexShaderBuffer = nullptr;
ID3D10Blob* pixelShaderBuffer = nullptr;
D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC lightBufferDesc;
// Compile the vertex shader code.
result = D3DCompileFromFile(vsFilename, nullptr, nullptr, "CelShadingVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have written something to the error message.
if (errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
}
// If there was nothing in the error message then it simply could not find the shader file itself.
else
{
MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
}
return false;
}
// Compile the pixel shader code.
result = D3DCompileFromFile(psFilename, nullptr, nullptr, "CelShadingPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have written something to the error message.
if (errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
}
// If there was nothing in the error message then it simply could not find the file itself.
else
{
MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
}
return false;
}
// Create the vertex shader from the buffer.
result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), nullptr, &m_vertexShader);
if (FAILED(result))
{
return false;
}
// Create the pixel shader from the buffer.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), nullptr, &m_pixelShader);
if (FAILED(result))
{
return false;
}
// Create the vertex input layout description.
// This setup needs to match the VertexType structure in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "NORMAL";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;
polygonLayout[2].SemanticName = "TEXCOORD";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT;
polygonLayout[2].InputSlot = 0;
polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;
// Get a count of the elements in the layout.
numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// Create the vertex input layout.
result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout);
if (FAILED(result))
{
return false;
}
// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
vertexShaderBuffer->Release();
vertexShaderBuffer = nullptr;
pixelShaderBuffer->Release();
pixelShaderBuffer = nullptr;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&matrixBufferDesc, nullptr, &m_matrixBuffer);
if (FAILED(result))
{
return false;
}
// Create a texture sampler state description.
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
if (FAILED(result))
{
return false;
}
// Setup the description of the light dynamic constant buffer that is in the pixel shader.
lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightBufferDesc.ByteWidth = sizeof(LightBufferType);
lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightBufferDesc.MiscFlags = 0;
lightBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
result = device->CreateBuffer(&lightBufferDesc, nullptr, &m_lightBuffer);
if (FAILED(result))
{
return false;
}
return true;
}
void CelShadingShader::ShutdownShader()
{
// Release the light constant buffer.
if (m_lightBuffer)
{
m_lightBuffer->Release();
m_lightBuffer = nullptr;
}
// Release the sampler state.
if (m_sampleState)
{
m_sampleState->Release();
m_sampleState = nullptr;
}
// Release the matrix constant buffer.
if (m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = nullptr;
}
// Release the layout.
if (m_layout)
{
m_layout->Release();
m_layout = nullptr;
}
// Release the pixel shader.
if (m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = nullptr;
}
// Release the vertex shader.
if (m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = nullptr;
}
}
void CelShadingShader::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned long bufferSize, i;
std::ofstream fout;
// Get a pointer to the error message text buffer.
compileErrors = (char*)(errorMessage->GetBufferPointer());
// Get the length of the message.
bufferSize = errorMessage->GetBufferSize();
// Open a file to write the error message to.
fout.open("shader-error.txt");
// Write out the error message.
for (i = 0; i < bufferSize; i++)
{
fout << compileErrors[i];
}
// Close the file.
fout.close();
// Release the error message.
errorMessage->Release();
errorMessage = nullptr;
// Pop a message up on the screen to notify the user to check the text file for compile errors.
MessageBox(hwnd, L"Error compiling shader. Check shader-error.txt for message.", shaderFilename, MB_OK);
}
bool CelShadingShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
ID3D11ShaderResourceView* texture, XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor, XMFLOAT3 lightPosition)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBufferType* dataPtr;
LightBufferType* dataPtr2;
unsigned int bufferNumber;
// Transpose the matrices to prepare them for the shader.
worldMatrix = XMMatrixTranspose(worldMatrix);
viewMatrix = XMMatrixTranspose(viewMatrix);
projectionMatrix = XMMatrixTranspose(projectionMatrix);
// Lock the constant buffer so it can be written to.
result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr = (MatrixBufferType*)mappedResource.pData;
// Copy the matrices into the constant buffer.
dataPtr->world = worldMatrix;
dataPtr->view = viewMatrix;
dataPtr->projection = projectionMatrix;
// Unlock the constant buffer.
deviceContext->Unmap(m_matrixBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 0;
// Finally set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
// Lock the light constant buffer so it can be written to.
result = deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr2 = (LightBufferType*)mappedResource.pData;
// Copy the lighting variables into the constant buffer.
dataPtr2->diffuseColor = diffuseColor;
dataPtr2->lightDirection = lightDirection;
dataPtr2->lightPosition = lightPosition;
dataPtr2->constantAttenuation = 0.5f; // Set your attenuation values here
dataPtr2->linearAttenuation = 0.1f;
dataPtr2->quadraticAttenuation = 0.01f;
// Unlock the constant buffer.
deviceContext->Unmap(m_lightBuffer, 0);
// Set the position of the light constant buffer in the pixel shader.
bufferNumber = 0;
// Finally set the light constant buffer in the pixel shader with the updated values.
deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer);
// Set shader texture resource in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &texture);
return true;
}
void CelShadingShader::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
// Set the vertex input layout.
deviceContext->IASetInputLayout(m_layout);
// Set the vertex and pixel shaders that will be used to render this triangle.
deviceContext->VSSetShader(m_vertexShader, nullptr, 0);
deviceContext->PSSetShader(m_pixelShader, nullptr, 0);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
}

View File

@@ -0,0 +1,68 @@
#ifndef _CELSHADINGSHADER_H_
#define _CELSHADINGSHADER_H_
//////////////
// INCLUDES //
//////////////
#include "Logger.h"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <fstream>
using namespace DirectX;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Class name: CelShadingShader
////////////////////////////////////////////////////////////////////////////////
class CelShadingShader
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
struct LightBufferType
{
XMFLOAT4 diffuseColor;
XMFLOAT3 lightDirection;
float padding; // Padding to ensure the structure is a multiple of 16 bytes.
XMFLOAT3 lightPosition; // Add light position
float padding2; // Padding to ensure the structure is a multiple of 16 bytes.
float constantAttenuation;
float linearAttenuation;
float quadraticAttenuation;
float padding3; // Padding to ensure the structure is a multiple of 16 bytes.
};
public:
CelShadingShader();
CelShadingShader(const CelShadingShader&);
~CelShadingShader();
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT3, XMFLOAT4, XMFLOAT3);
private:
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT3, XMFLOAT4, XMFLOAT3);
void RenderShader(ID3D11DeviceContext*, int);
private:
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11Buffer* m_matrixBuffer;
ID3D11SamplerState* m_sampleState;
ID3D11Buffer* m_lightBuffer;
};
#endif

View File

@@ -329,7 +329,7 @@ void SpriteClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
bool SpriteClass::LoadTextures(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename) bool SpriteClass::LoadTextures(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
{ {
std::string textureFilename; std::string textureFilename(256, '0');
std::ifstream fin; std::ifstream fin;
int i, j; int i, j;
char input; char input;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

View File

@@ -51,7 +51,6 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
char spriteFilename[128]; char spriteFilename[128];
char fpsString[32]; char fpsString[32];
bool result; bool result;
std::vector<std::string> Filename;
m_screenWidth = screenWidth; m_screenWidth = screenWidth;
m_screenHeight = screenHeight; m_screenHeight = screenHeight;
@@ -127,6 +126,7 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
// Set the sprite info file we will be using. // Set the sprite info file we will be using.
//
strcpy_s(spriteFilename, "sprite_data_01.txt"); strcpy_s(spriteFilename, "sprite_data_01.txt");
// Create and initialize the sprite object. // Create and initialize the sprite object.
@@ -159,7 +159,7 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
} }
// Set the file name of the bitmap file. // Set the file name of the bitmap file.
strcpy_s(bitmapFilename, "stone01.tga"); strcpy_s(bitmapFilename, "assets/Texture/stone01.tga");
// Create and initialize the bitmap object. // Create and initialize the bitmap object.
m_Bitmap = new BitmapClass; m_Bitmap = new BitmapClass;
@@ -172,20 +172,29 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
} }
// Set the file name of the model. // Set the file name of the model.
strcpy_s(modelFilename, "cube.txt"); strcpy_s(modelFilename, "assets/Model/TXT/cube.txt");
// Set the file name of the textures. // Charger les textures
Filename.push_back("stone01.tga"); std::vector<std::wstring> textureFilenames = {
Filename.push_back("normal01.tga"); L"assets/Texture/stone01.png"
Filename.push_back("spec02.tga"); };
Filename.push_back("alpha01.tga");
Filename.push_back("light01.tga"); for (const auto& textureFilename : textureFilenames)
Filename.push_back("moss01.tga"); {
ID3D11ShaderResourceView* texture = nullptr;
result = DirectX::CreateWICTextureFromFile(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), textureFilename.c_str(), nullptr, &texture);
if (FAILED(result))
{
Logger::Get().Log("Failed to load texture: " + std::string(textureFilename.begin(), textureFilename.end()), __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
textures.push_back(texture);
}
// Create and initialize the model object. // Create and initialize the model object.
m_Model = new ModelClass; m_Model = new ModelClass;
result = m_Model->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, Filename); result = m_Model->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textures);
if (!result) if (!result)
{ {
Logger::Get().Log("Could not initialize the model object", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Could not initialize the model object", __FILE__, __LINE__, Logger::LogLevel::Error);
@@ -265,15 +274,31 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
m_ModelList = new ModelListClass; m_ModelList = new ModelListClass;
m_ModelList->Initialize(25); m_ModelList->Initialize(25);
// Set the file names of the bath model. // Charger les textures initiales pour m_BathModel
strcpy_s(modelFilename, "bath.txt"); std::vector<std::wstring> bathTextures = {
// replace first element with the new filename L"assets/Texture/marble01.png"
Filename[0] = "marble01.tga"; };
textures.clear();
for (const auto& textureFilename : bathTextures)
{
ID3D11ShaderResourceView* texture = nullptr;
result = DirectX::CreateWICTextureFromFile(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), textureFilename.c_str(), nullptr, &texture);
if (FAILED(result))
{
Logger::Get().Log("Failed to load texture: " + std::string(textureFilename.begin(), textureFilename.end()), __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
textures.push_back(texture);
}
// Set the file name of the bath model.
strcpy_s(modelFilename, "assets/Model/TXT/bath.txt");
// Create and initialize the bath model object. // Create and initialize the bath model object.
m_BathModel = new ModelClass; m_BathModel = new ModelClass;
result = m_BathModel->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, Filename); result = m_BathModel->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textures);
if (!result) if (!result)
{ {
MessageBox(hwnd, L"Could not initialize the bath model object.", L"Error", MB_OK); MessageBox(hwnd, L"Could not initialize the bath model object.", L"Error", MB_OK);
@@ -281,14 +306,29 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
} }
// Set the file names of the water model. // Set the file names of the water model.
strcpy_s(modelFilename, "water.txt"); strcpy_s(modelFilename, "assets/Model/TXT/water.txt");
// replace first element with the new filename // replace first element with the new filename
Filename[1] = "water01.tga"; std::vector<std::wstring> waterTextures = {
L"assets/Texture/water01.png"
};
textures.clear();
for (const auto& textureFilename : waterTextures)
{
ID3D11ShaderResourceView* texture = nullptr;
result = DirectX::CreateWICTextureFromFile(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), textureFilename.c_str(), nullptr, &texture);
if (FAILED(result))
{
Logger::Get().Log("Failed to load texture: " + std::string(textureFilename.begin(), textureFilename.end()), __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
textures.push_back(texture);
}
// Create and initialize the water model object. // Create and initialize the water model object.
m_WaterModel = new ModelClass; m_WaterModel = new ModelClass;
result = m_WaterModel->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, Filename); result = m_WaterModel->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textures);
if (!result) if (!result)
{ {
MessageBox(hwnd, L"Could not initialize the water model object.", L"Error", MB_OK); MessageBox(hwnd, L"Could not initialize the water model object.", L"Error", MB_OK);
@@ -355,6 +395,7 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
Logger::Get().Log("Could not initialize the fps string", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Could not initialize the fps string", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
} }
} }
catch (const std::exception& e) catch (const std::exception& e)
{ {
@@ -1006,6 +1047,12 @@ bool ApplicationClass::Render(float rotation, float x, float y, float z, float t
ambientColor[i] = m_Lights[i]->GetPosition(); ambientColor[i] = m_Lights[i]->GetPosition();
} }
//Add the 3 first value of the first light position to the TrueLightPosition XMFLOAT3
positionX = lightPosition[0].x;
positionY = lightPosition[0].y;
positionZ = lightPosition[0].z;
XMFLOAT3 TrueLightPosition = XMFLOAT3(positionX, positionY, positionZ);
scaleMatrix = XMMatrixScaling(0.5f, 0.5f, 0.5f); // Build the scaling matrix. scaleMatrix = XMMatrixScaling(0.5f, 0.5f, 0.5f); // Build the scaling matrix.
rotateMatrix = XMMatrixRotationY(rotation); // Build the rotation matrix. rotateMatrix = XMMatrixRotationY(rotation); // Build the rotation matrix.
translateMatrix = XMMatrixTranslation(x, y, z); // Build the translation matrix. translateMatrix = XMMatrixTranslation(x, y, z); // Build the translation matrix.
@@ -1040,21 +1087,28 @@ bool ApplicationClass::Render(float rotation, float x, float y, float z, float t
cube->Render(m_Direct3D->GetDeviceContext()); cube->Render(m_Direct3D->GetDeviceContext());
// render the texture using the texture shader.
result = m_ShaderManager->RenderTextureShader(m_Direct3D->GetDeviceContext(), cube->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, cube->GetTexture(0)); if (!m_enableCelShading) {
if (!result) result = m_ShaderManager->RenderlightShader(m_Direct3D->GetDeviceContext(), cube->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, cube->GetTexture(0),
{ diffuseColor, lightPosition, ambientColor);
Logger::Get().Log("Could not render the cube model using the texture shader", __FILE__, __LINE__, Logger::LogLevel::Error); if (!result)
return false; {
Logger::Get().Log("Could not render the cube model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
} }
result = m_ShaderManager->RenderlightShader(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, cube->GetTexture(0), // Render cel shading globally to the scene using the cel shader if the checkbox is checked.
diffuseColor, lightPosition,ambientColor); if (m_enableCelShading) {
if (!result) result = m_ShaderManager->RenderCelShadingShader(m_Direct3D->GetDeviceContext(), cube->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, cube->GetTexture(0),
{ m_Lights[0]->GetDirection(), m_Lights[0]->GetDiffuseColor(), TrueLightPosition);
Logger::Get().Log("Could not render the cube model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error); if (!result)
return false; {
Logger::Get().Log("Could not render the model using the cel shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
} }
} }
for (auto& object : m_object) for (auto& object : m_object)
@@ -1072,21 +1126,26 @@ bool ApplicationClass::Render(float rotation, float x, float y, float z, float t
object->Render(m_Direct3D->GetDeviceContext()); object->Render(m_Direct3D->GetDeviceContext());
// render the texture using the texture shader. if (!m_enableCelShading) {
result = m_ShaderManager->RenderTextureShader(m_Direct3D->GetDeviceContext(), object->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, object->GetTexture(0)); result = m_ShaderManager->RenderlightShader(m_Direct3D->GetDeviceContext(), object->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, object->GetTexture(0),
if (!result) diffuseColor, lightPosition, ambientColor);
{
Logger::Get().Log("Could not render the cube model using the texture shader", __FILE__, __LINE__, Logger::LogLevel::Error); if (!result)
return false; {
Logger::Get().Log("Could not render the object model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
} }
result = m_ShaderManager->RenderlightShader(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture(0), // Render cel shading globally to the scene using the cel shader if the checkbox is checked.
diffuseColor, lightPosition, ambientColor); if (m_enableCelShading) {
result = m_ShaderManager->RenderCelShadingShader(m_Direct3D->GetDeviceContext(), object->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, object->GetTexture(0),
if (!result) m_Lights[0]->GetDirection(), m_Lights[0]->GetDiffuseColor(), TrueLightPosition);
{ if (!result)
Logger::Get().Log("Could not render the object model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error); {
return false; Logger::Get().Log("Could not render the model using the cel shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
} }
} }
@@ -1102,14 +1161,33 @@ bool ApplicationClass::Render(float rotation, float x, float y, float z, float t
worldMatrix = XMMatrixMultiply(srMatrix, translateMatrix); worldMatrix = XMMatrixMultiply(srMatrix, translateMatrix);
chunk->Render(m_Direct3D->GetDeviceContext()); chunk->Render(m_Direct3D->GetDeviceContext());
if (!m_enableCelShading) {
if (chunk->GetTexture(0) == nullptr)
{
Logger::Get().Log("Could not render the terrain model using the light shader, texture is null", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
result = m_ShaderManager->RenderlightShader(m_Direct3D->GetDeviceContext(), chunk->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, chunk->GetTexture(5), result = m_ShaderManager->RenderSpecMapShader(m_Direct3D->GetDeviceContext(), chunk->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix,
diffuseColor, lightPosition, ambientColor); chunk->GetTexture(0), chunk->GetTexture(1), chunk->GetTexture(2), m_Lights[0]->GetDirection(), m_Lights[0]->GetDiffuseColor(),
m_Camera->GetPosition(), m_Lights[0]->GetSpecularColor(), m_Lights[0]->GetSpecularPower());
if (!result) if (!result)
{ {
Logger::Get().Log("Could not render the terrain model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Could not render the terrain model using the light shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
}
}
// Render cel shading globally to the scene using the cel shader if the checkbox is checked.
if (m_enableCelShading) {
result = m_ShaderManager->RenderCelShadingShader(m_Direct3D->GetDeviceContext(), chunk->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, chunk->GetTexture(0),
m_Lights[0]->GetDirection(), m_Lights[0]->GetDiffuseColor(), TrueLightPosition);
if (!result)
{
Logger::Get().Log("Could not render the model using the cel shader", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
} }
} }
@@ -1120,8 +1198,8 @@ bool ApplicationClass::Render(float rotation, float x, float y, float z, float t
m_BathModel->Render(m_Direct3D->GetDeviceContext()); m_BathModel->Render(m_Direct3D->GetDeviceContext());
// Render the bath model using the light shader. // Render the bath model using the light shader.
result = m_ShaderManager->RenderTextureShader(m_Direct3D->GetDeviceContext(), m_BathModel->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, result = m_ShaderManager->RenderlightShader(m_Direct3D->GetDeviceContext(), m_BathModel->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix,
m_BathModel->GetTexture(0)); m_BathModel->GetTexture(0), diffuseColor, lightPosition, ambientColor);
if (!result) if (!result)
{ {
return false; return false;
@@ -1491,7 +1569,7 @@ void ApplicationClass::GenerateTerrain()
Logger::Get().Log("Generating terrain", __FILE__, __LINE__); Logger::Get().Log("Generating terrain", __FILE__, __LINE__);
char modelFilename[128]; char modelFilename[128];
std::vector<string> Filename; bool result;
XMMATRIX scaleMatrix; XMMATRIX scaleMatrix;
float scaleX, scaleY, scaleZ; float scaleX, scaleY, scaleZ;
@@ -1503,25 +1581,56 @@ void ApplicationClass::GenerateTerrain()
scaleMatrix = XMMatrixScaling(scaleX, scaleY, scaleZ); scaleMatrix = XMMatrixScaling(scaleX, scaleY, scaleZ);
// Set the file name of the model. // Set the file name of the model.
strcpy_s(modelFilename, "plane.txt"); strcpy_s(modelFilename, "assets/Model/TXT/plane.txt");
Filename.push_back("stone01.tga"); // Liste des fichiers de texture
Filename.push_back("normal01.tga"); std::vector<std::wstring> terrainTexture = {
Filename.push_back("spec02.tga"); L"assets/Texture/Bricks2K.png",
Filename.push_back("alpha01.tga"); L"assets/Texture/BricksNRM2K.png",
Filename.push_back("light01.tga"); L"assets/Texture/BricksGLOSS2K.png"
Filename.push_back("moss01.tga"); };
textures.clear();
for (const auto& textureFilename : terrainTexture)
{
ID3D11ShaderResourceView* texture = nullptr;
HRESULT result = DirectX::CreateWICTextureFromFile(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), textureFilename.c_str(), nullptr, &texture);
if (FAILED(result))
{
// Utiliser _com_error pour obtenir des informations d<>taill<6C>es sur l'erreur
_com_error err(result);
LPCTSTR errMsg = err.ErrorMessage();
//convertie errMessage en std::wstring
std::wstring ws(errMsg);
std::string str(ws.begin(), ws.end());
Logger::Get().Log("Failed to load texture: " + std::string(textureFilename.begin(), textureFilename.end()) +
"\nError: " + std::to_string(result) +
"\nDescription: " + str,
__FILE__, __LINE__, Logger::LogLevel::Error);
return ; // Assurez-vous de retourner false ou de g<>rer l'erreur de mani<6E>re appropri<72>e
}
textures.push_back(texture);
// log success message
Logger::Get().Log("Texture loaded: " + std::string(textureFilename.begin(), textureFilename.end()), __FILE__, __LINE__, Logger::LogLevel::Initialize);
}
std::filesystem::path p(modelFilename); std::filesystem::path p(modelFilename);
std::string filenameWithoutExtension = p.stem().string(); std::string filenameWithoutExtension = p.stem().string();
// for loop to generate terrain chunks for a 10x10 grid // for loop to generate terrain chunks for a 10x10 grid
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
for (int j = 0; j < 10; j++) for (int j = 0; j < 10; j++)
{ {
Object* newTerrain = new Object(); Object* newTerrain = new Object();
newTerrain->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, Filename); newTerrain->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textures);
newTerrain->SetScaleMatrix(scaleMatrix); newTerrain->SetScaleMatrix(scaleMatrix);
@@ -1543,6 +1652,7 @@ void ApplicationClass::AddKobject(WCHAR* filepath)
char modelFilename[128]; char modelFilename[128];
vector<string> Filename; vector<string> Filename;
bool result;
filesystem::path p(filepath); filesystem::path p(filepath);
string filename = p.stem().string(); string filename = p.stem().string();
@@ -1551,16 +1661,28 @@ void ApplicationClass::AddKobject(WCHAR* filepath)
wcstombs_s(&convertedChars, modelFilename, sizeof(modelFilename), filepath, _TRUNCATE); wcstombs_s(&convertedChars, modelFilename, sizeof(modelFilename), filepath, _TRUNCATE);
// Set the name of the texture file that we will be loading. /// Liste des fichiers de texture
Filename.push_back("stone01.tga"); std::vector<std::wstring> kobjTexture = {
Filename.push_back("normal01.tga"); L"assets/Texture/moss01.png"
Filename.push_back("spec02.tga"); };
Filename.push_back("alpha01.tga");
Filename.push_back("light01.tga");
Filename.push_back("moss01.tga"); textures.clear();
for (const auto& textureFilename : kobjTexture)
{
ID3D11ShaderResourceView* texture = nullptr;
result = DirectX::CreateWICTextureFromFile(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), textureFilename.c_str(), nullptr, &texture);
if (FAILED(result))
{
Logger::Get().Log("Failed to load texture: " + std::string(textureFilename.begin(), textureFilename.end()), __FILE__, __LINE__, Logger::LogLevel::Error);
return;
}
textures.push_back(texture);
}
Object* newObject = new Object(); Object* newObject = new Object();
newObject->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, Filename); newObject->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textures);
newObject->SetMass(1.0f); newObject->SetMass(1.0f);
newObject->SetTranslateMatrix(XMMatrixTranslation(0.0f, 50.0f, 0.0f)); newObject->SetTranslateMatrix(XMMatrixTranslation(0.0f, 50.0f, 0.0f));
newObject->SetName(filename); newObject->SetName(filename);
@@ -1577,23 +1699,34 @@ void ApplicationClass::AddCube()
Logger::Get().Log("Adding cube", __FILE__, __LINE__); Logger::Get().Log("Adding cube", __FILE__, __LINE__);
char modelFilename[128]; char modelFilename[128];
vector<string> Filename; bool result;
// Set the file name of the model. // Set the file name of the model.
strcpy_s(modelFilename, "cube.txt"); strcpy_s(modelFilename, "assets/Model/TXT/cube.txt");
// Set the name of the texture file that we will be loading. // Liste des fichiers de texture
Filename.push_back("stone01.tga"); std::vector<std::wstring> cubeTexture = {
Filename.push_back("normal01.tga"); L"assets/Texture/Bricks2K.png"
Filename.push_back("spec02.tga"); };
Filename.push_back("alpha01.tga");
Filename.push_back("light01.tga");
Filename.push_back("moss01.tga"); textures.clear();
for (const auto& textureFilename : cubeTexture)
{
ID3D11ShaderResourceView* texture = nullptr;
result = DirectX::CreateWICTextureFromFile(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), textureFilename.c_str(), nullptr, &texture);
if (FAILED(result))
{
Logger::Get().Log("Failed to load texture: " + std::string(textureFilename.begin(), textureFilename.end()), __FILE__, __LINE__, Logger::LogLevel::Error);
return;
}
textures.push_back(texture);
}
static int cubeCount = 0; static int cubeCount = 0;
float position = cubeCount * 2.0f; float position = cubeCount * 2.0f;
Object* newCube = new Object(); Object* newCube = new Object();
newCube->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, Filename); newCube->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textures);
newCube->SetTranslateMatrix(XMMatrixTranslation(position, 0.0f, 0.0f)); newCube->SetTranslateMatrix(XMMatrixTranslation(position, 0.0f, 0.0f));

View File

@@ -30,6 +30,9 @@
#include "reflectionshaderclass.h" #include "reflectionshaderclass.h"
#include "physics.h" #include "physics.h"
#include <WICTextureLoader.h>
#include <comdef.h> // Pour _com_error
///////////// /////////////
// GLOBALS // // GLOBALS //
@@ -83,6 +86,10 @@ public:
bool GetShouldQuit() const { return m_ShouldQuit; }; bool GetShouldQuit() const { return m_ShouldQuit; };
void SetShouldQuit(bool shouldQuit) { m_ShouldQuit = shouldQuit; }; void SetShouldQuit(bool shouldQuit) { m_ShouldQuit = shouldQuit; };
void SetCelShading(bool enable) { m_enableCelShading = enable; };
std::vector<ID3D11ShaderResourceView*> textures;
private: private:
bool Render(float, float, float, float, float); bool Render(float, float, float, float, float);
bool UpdateMouseStrings(int, int, bool); bool UpdateMouseStrings(int, int, bool);
@@ -134,6 +141,9 @@ private :
std::vector<LightClass*> m_Lights; std::vector<LightClass*> m_Lights;
int m_numLights; int m_numLights;
XMFLOAT3 TrueLightPosition;
ModelClass* m_LightModel;
// ----------------------------------- // // ----------------------------------- //
// ------------- SHADERS ------------- // // ------------- SHADERS ------------- //
// ----------------------------------- // // ----------------------------------- //
@@ -142,6 +152,8 @@ private :
FontShaderClass* m_FontShader; FontShaderClass* m_FontShader;
BitmapClass* m_Bitmap; BitmapClass* m_Bitmap;
SpriteClass* m_Sprite; SpriteClass* m_Sprite;
bool m_enableCelShading;
// ----------------------------------- // // ----------------------------------- //
// ------------ VARIABLES ------------ // // ------------ VARIABLES ------------ //

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 588 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 599 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 917 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 934 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

View File

@@ -0,0 +1,87 @@
cbuffer LightBuffer
{
float4 diffuseColor;
float3 lightDirection;
float padding; // Padding to ensure the structure is a multiple of 16 bytes.
float3 lightPosition; // Add light position
float padding2; // Padding to ensure the structure is a multiple of 16 bytes.
float constantAttenuation;
float linearAttenuation;
float quadraticAttenuation;
float padding3; // Padding to ensure the structure is a multiple of 16 bytes.
};
Texture2D shaderTexture;
SamplerState SampleType;
struct PixelInputType
{
float4 position : SV_POSITION;
float3 normal : NORMAL;
float2 tex : TEXCOORD0;
float3 worldPos : TEXCOORD1; // Add world position
};
float4 CelShadingPixelShader(PixelInputType input) : SV_TARGET
{
float4 textureColor;
float lightIntensity;
float4 finalColor;
// Sample the pixel color from the texture.
textureColor = shaderTexture.Sample(SampleType, input.tex);
float3 normal = normalize(input.normal);
// Calculate the light vector from the light position to the world position
float3 lightVector = normalize(lightPosition - input.worldPos);
// Calculate the light intensity based on the light direction.
float directionalLightIntensity = saturate(dot(normal, normalize(lightDirection)));
// Calculate the light intensity based on the light position.
float positionalLightIntensity = saturate(dot(normal, lightVector));
// Combine the directional and positional light intensities.
lightIntensity = max(directionalLightIntensity, positionalLightIntensity);
// Calculate the distance from the light to the fragment.
float distance = length(lightPosition - input.worldPos);
// Apply an attenuation factor based on the distance.
float attenuation = 1.0f / (constantAttenuation + linearAttenuation * distance + quadraticAttenuation * distance * distance);
// Combine the light intensity with the attenuation factor.
lightIntensity *= attenuation;
// Apply a step function to create the cel shading effect.
if (lightIntensity > 0.75f)
{
lightIntensity = 1.0f; // Brightest level
}
else if (lightIntensity > 0.5f)
{
lightIntensity = 0.7f; // Mid-bright level
}
else if (lightIntensity > 0.25f)
{
lightIntensity = 0.4f; // Mid-dark level
}
else
{
lightIntensity = 0.1f; // Darkest level
}
// Simple shadow calculation: if the fragment is behind the light source, it is in shadow.
float3 toLight = normalize(lightPosition - input.worldPos);
float shadow = saturate(dot(normal, toLight));
if (shadow < 0.1f)
{
lightIntensity *= 0.5f; // Darken the fragment if it is in shadow
}
// Calculate the final color by combining the texture color with the light intensity and diffuse color.
finalColor = textureColor * diffuseColor * lightIntensity;
return finalColor;
}

View File

@@ -0,0 +1,45 @@
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};
struct VertexInputType
{
float4 position : POSITION;
float3 normal : NORMAL;
float2 tex : TEXCOORD0;
};
struct PixelInputType
{
float4 position : SV_POSITION;
float3 normal : NORMAL;
float2 tex : TEXCOORD0;
float3 worldPos : TEXCOORD1; // Add world position
};
PixelInputType CelShadingVertexShader(VertexInputType input)
{
PixelInputType output;
// Change the position vector to be 4 units for proper matrix calculations.
input.position.w = 1.0f;
// Calculate the position of the vertex against the world, view, and projection matrices.
float4 worldPosition = mul(input.position, worldMatrix);
output.position = mul(worldPosition, viewMatrix);
output.position = mul(output.position, projectionMatrix);
// Pass the normal to the pixel shader
output.normal = mul((float3x3)worldMatrix, input.normal);
// Pass the world position to the pixel shader
output.worldPos = worldPosition.xyz;
// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
return output;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

View File

@@ -22,7 +22,13 @@
<ClCompile Include="alphamapshaderclass.cpp" /> <ClCompile Include="alphamapshaderclass.cpp" />
<ClCompile Include="applicationclass.cpp" /> <ClCompile Include="applicationclass.cpp" />
<ClCompile Include="bitmapclass.cpp" /> <ClCompile Include="bitmapclass.cpp" />
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\DDSTextureLoader.cpp" />
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\DirectXHelpers.cpp" />
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\pch.cpp" />
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\SimpleMath.cpp" />
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\WICTextureLoader.cpp" />
<ClCompile Include="Cameraclass.cpp" /> <ClCompile Include="Cameraclass.cpp" />
<ClCompile Include="CelShadingShader.cpp" />
<ClCompile Include="Colorshaderclass.cpp" /> <ClCompile Include="Colorshaderclass.cpp" />
<ClCompile Include="d3dclass.cpp" /> <ClCompile Include="d3dclass.cpp" />
<ClCompile Include="imguiManager.cpp" /> <ClCompile Include="imguiManager.cpp" />
@@ -69,7 +75,13 @@
<ClInclude Include="alphamapshaderclass.h" /> <ClInclude Include="alphamapshaderclass.h" />
<ClInclude Include="applicationclass.h" /> <ClInclude Include="applicationclass.h" />
<ClInclude Include="bitmapclass.h" /> <ClInclude Include="bitmapclass.h" />
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\CMO.h" />
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\DDS.h" />
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\LoaderHelpers.h" />
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\pch.h" />
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\PlatformHelpers.h" />
<ClInclude Include="Cameraclass.h" /> <ClInclude Include="Cameraclass.h" />
<ClInclude Include="CelShadingShader.h" />
<ClInclude Include="Colorshaderclass.h" /> <ClInclude Include="Colorshaderclass.h" />
<ClInclude Include="d3dclass.h" /> <ClInclude Include="d3dclass.h" />
<ClInclude Include="imguiManager.h" /> <ClInclude Include="imguiManager.h" />
@@ -154,6 +166,12 @@
<CopyFileToFolders Include="..\KhaoticDemo\water.ps"> <CopyFileToFolders Include="..\KhaoticDemo\water.ps">
<FileType>Document</FileType> <FileType>Document</FileType>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="celshading.ps">
<FileType>Document</FileType>
</CopyFileToFolders>
<CopyFileToFolders Include="celshading.vs">
<FileType>Document</FileType>
</CopyFileToFolders>
<None Include="packages.config" /> <None Include="packages.config" />
<CopyFileToFolders Include="reflection.ps"> <CopyFileToFolders Include="reflection.ps">
<FileType>Document</FileType> <FileType>Document</FileType>
@@ -206,34 +224,35 @@
</CopyFileToFolders> </CopyFileToFolders>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<CopyFileToFolders Include="alpha01.tga" />
<Image Include="dirt01.tga" />
<CopyFileToFolders Include="font01.tga" /> <CopyFileToFolders Include="font01.tga" />
<Image Include="assets\Texture\alpha01.png" />
<Image Include="assets\Texture\Bricks2K.png" />
<Image Include="assets\Texture\BricksGLOSS2K.png" />
<Image Include="assets\Texture\BricksNRM2K.png" />
<Image Include="assets\Texture\dirt01.png" />
<Image Include="assets\Texture\font01.png" />
<Image Include="assets\Texture\ground01.png" />
<Image Include="assets\Texture\light01.png" />
<Image Include="assets\Texture\marble01.png" />
<Image Include="assets\Texture\moss01.png" />
<Image Include="assets\Texture\normal01.png" />
<Image Include="assets\Texture\spec02.png" />
<Image Include="assets\Texture\sprite01.png" />
<Image Include="assets\Texture\sprite02.png" />
<Image Include="assets\Texture\sprite03.png" />
<Image Include="assets\Texture\sprite04.png" />
<Image Include="assets\Texture\stone01.png" />
<Image Include="assets\Texture\wall.png" />
<Image Include="assets\Texture\wall01.png" />
<Image Include="assets\Texture\water01.png" />
<Image Include="KhaoticIcon.ico" /> <Image Include="KhaoticIcon.ico" />
<CopyFileToFolders Include="light01.tga" />
<CopyFileToFolders Include="moss01.tga" />
<CopyFileToFolders Include="normal01.tga" />
<CopyFileToFolders Include="marble01.tga" />
<Image Include="papier.tga" />
<CopyFileToFolders Include="spec02.tga" />
<CopyFileToFolders Include="sprite01.tga" /> <CopyFileToFolders Include="sprite01.tga" />
<CopyFileToFolders Include="sprite02.tga" /> <CopyFileToFolders Include="sprite02.tga" />
<CopyFileToFolders Include="sprite03.tga" /> <CopyFileToFolders Include="sprite03.tga" />
<CopyFileToFolders Include="sprite04.tga" /> <CopyFileToFolders Include="sprite04.tga" />
<CopyFileToFolders Include="stone01.tga" />
<CopyFileToFolders Include="wall.tga" />
<CopyFileToFolders Include="water01.tga" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<CopyFileToFolders Include="cube.txt" />
<CopyFileToFolders Include="font01.txt" /> <CopyFileToFolders Include="font01.txt" />
<CopyFileToFolders Include="plane.txt" />
<CopyFileToFolders Include="bath.txt" />
<Text Include="chunk.txt" />
<Text Include="sphere.txt" />
<CopyFileToFolders Include="sprite_data_01.txt" />
<Text Include="square.txt" />
<CopyFileToFolders Include="water.txt" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<CopyFileToFolders Include="translate.ps"> <CopyFileToFolders Include="translate.ps">
@@ -249,29 +268,41 @@
<ResourceCompile Include="resources.rc" /> <ResourceCompile Include="resources.rc" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<CopyFileToFolders Include="cone.obj"> <CopyFileToFolders Include="assets\Model\OBJ\86.obj">
<FileType>Document</FileType> <FileType>Document</FileType>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="isosphere.obj"> <CopyFileToFolders Include="assets\Model\OBJ\cone.obj">
<FileType>Document</FileType> <FileType>Document</FileType>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="monke.obj"> <CopyFileToFolders Include="assets\Model\OBJ\isosphere.obj">
<FileType>Document</FileType> <FileType>Document</FileType>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="vaisseau.obj"> <CopyFileToFolders Include="assets\Model\OBJ\monke.obj">
<FileType>Document</FileType>
</CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\OBJ\vaisseau.obj">
<FileType>Document</FileType> <FileType>Document</FileType>
</CopyFileToFolders> </CopyFileToFolders>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<CopyFileToFolders Include="86.obj"> <CopyFileToFolders Include="assets\Model\TXT\bath.txt" />
<FileType>Document</FileType> <CopyFileToFolders Include="assets\Model\TXT\chunk.txt">
<FileType>Text</FileType>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\TXT\cube.txt" />
<CopyFileToFolders Include="assets\Model\TXT\ground.txt" />
<CopyFileToFolders Include="assets\Model\TXT\plane.txt" />
<CopyFileToFolders Include="assets\Model\TXT\sphere.txt" />
<CopyFileToFolders Include="assets\Model\TXT\square.txt" />
<CopyFileToFolders Include="assets\Model\TXT\wall.txt" />
<CopyFileToFolders Include="assets\Model\TXT\water.txt" />
</ItemGroup> </ItemGroup>
<PropertyGroup Label="Globals"> <PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion> <VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword> <Keyword>Win32Proj</Keyword>
<ProjectGuid>{92cf56c4-76bb-40d4-8fe5-36c15f5f127a}</ProjectGuid> <ProjectGuid>{92cf56c4-76bb-40d4-8fe5-36c15f5f127a}</ProjectGuid>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>KhaoticCore</ProjectName>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
@@ -352,7 +383,7 @@
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)enginecustom\include\backends;$(SolutionDir)enginecustom\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(SolutionDir)enginecustom\include\backends;$(SolutionDir)enginecustom\include\Inc;$(SolutionDir)enginecustom\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<LanguageStandard>stdcpp17</LanguageStandard> <LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile> </ClCompile>
<Link> <Link>
@@ -369,7 +400,7 @@
<PreprocessorDefinitions>NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard> <LanguageStandard>stdcpp17</LanguageStandard>
<AdditionalIncludeDirectories>$(SolutionDir)enginecustom\include\backends;$(SolutionDir)enginecustom\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(SolutionDir)enginecustom\include\backends;$(SolutionDir)enginecustom\include\Inc;$(SolutionDir)enginecustom\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Windows</SubSystem> <SubSystem>Windows</SubSystem>

View File

@@ -31,6 +31,24 @@
<Filter Include="Assets"> <Filter Include="Assets">
<UniqueIdentifier>{2978535b-193d-4876-83be-1c3c4470db62}</UniqueIdentifier> <UniqueIdentifier>{2978535b-193d-4876-83be-1c3c4470db62}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="Fichiers sources\DirectX Tool Kit">
<UniqueIdentifier>{3bfbc604-3b39-4e49-bee2-b942fc5dce8c}</UniqueIdentifier>
</Filter>
<Filter Include="Fichiers d%27en-tête\DirectX Tool Kit">
<UniqueIdentifier>{d710c862-b37d-4ad5-aa92-2456f9745881}</UniqueIdentifier>
</Filter>
<Filter Include="Assets\Texture">
<UniqueIdentifier>{4873a73d-d11c-4d40-b847-b6d7fef4b23d}</UniqueIdentifier>
</Filter>
<Filter Include="Assets\Model">
<UniqueIdentifier>{3f3824c5-8a66-4f02-9845-1a9538336592}</UniqueIdentifier>
</Filter>
<Filter Include="Assets\Model\OBJ">
<UniqueIdentifier>{22651df1-90a4-4a19-8b97-5147b27d975a}</UniqueIdentifier>
</Filter>
<Filter Include="Assets\Model\TXT">
<UniqueIdentifier>{f67d85e0-106e-47a1-bb9c-a5ea9111509a}</UniqueIdentifier>
</Filter>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="Main.cpp"> <ClCompile Include="Main.cpp">
@@ -171,6 +189,24 @@
<ClCompile Include="normalmapshaderclass.cpp"> <ClCompile Include="normalmapshaderclass.cpp">
<Filter>Fichiers sources</Filter> <Filter>Fichiers sources</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="CelShadingShader.cpp">
<Filter>Fichiers sources</Filter>
</ClCompile>
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\DDSTextureLoader.cpp">
<Filter>Fichiers sources\DirectX Tool Kit</Filter>
</ClCompile>
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\DirectXHelpers.cpp">
<Filter>Fichiers sources\DirectX Tool Kit</Filter>
</ClCompile>
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\pch.cpp">
<Filter>Fichiers sources\DirectX Tool Kit</Filter>
</ClCompile>
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\SimpleMath.cpp">
<Filter>Fichiers sources\DirectX Tool Kit</Filter>
</ClCompile>
<ClCompile Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\WICTextureLoader.cpp">
<Filter>Fichiers sources\DirectX Tool Kit</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="systemclass.h"> <ClInclude Include="systemclass.h">
@@ -317,32 +353,93 @@
<ClInclude Include="physics.h"> <ClInclude Include="physics.h">
<Filter>Fichiers d%27en-tête</Filter> <Filter>Fichiers d%27en-tête</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="CelShadingShader.h">
<Filter>Fichiers d%27en-tête</Filter>
</ClInclude>
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\PlatformHelpers.h">
<Filter>Fichiers d%27en-tête\DirectX Tool Kit</Filter>
</ClInclude>
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\pch.h">
<Filter>Fichiers d%27en-tête\DirectX Tool Kit</Filter>
</ClInclude>
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\LoaderHelpers.h">
<Filter>Fichiers d%27en-tête\DirectX Tool Kit</Filter>
</ClInclude>
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\DDS.h">
<Filter>Fichiers d%27en-tête\DirectX Tool Kit</Filter>
</ClInclude>
<ClInclude Include="C:\Users\Bacon\Downloads\DirectXTK-main\DirectXTK-main\Src\CMO.h">
<Filter>Fichiers d%27en-tête\DirectX Tool Kit</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Image Include="papier.tga">
<Filter>assets</Filter>
</Image>
<Image Include="dirt01.tga">
<Filter>assets</Filter>
</Image>
<Image Include="KhaoticIcon.ico"> <Image Include="KhaoticIcon.ico">
<Filter>Assets</Filter> <Filter>Assets</Filter>
</Image> </Image>
<Image Include="assets\Texture\BricksGLOSS2K.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\BricksNRM2K.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\alpha01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\Bricks2K.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\dirt01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\font01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\ground01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\light01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\marble01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\moss01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\normal01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\spec02.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\sprite01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\sprite02.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\sprite03.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\sprite04.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\stone01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\wall.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\wall01.png">
<Filter>Assets\Texture</Filter>
</Image>
<Image Include="assets\Texture\water01.png">
<Filter>Assets\Texture</Filter>
</Image>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Text Include="sphere.txt">
<Filter>Assets</Filter>
</Text>
<Text Include="square.txt">
<Filter>assets</Filter>
</Text>
<Text Include="chunk.txt">
<Filter>Assets</Filter>
</Text>
</ItemGroup>
<ItemGroup> <ItemGroup>
<ResourceCompile Include="resources.rc"> <ResourceCompile Include="resources.rc">
<Filter>Fichiers de ressources</Filter> <Filter>Fichiers de ressources</Filter>
@@ -367,39 +464,12 @@
<CopyFileToFolders Include="font01.tga"> <CopyFileToFolders Include="font01.tga">
<Filter>fonts</Filter> <Filter>fonts</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="stone01.tga">
<Filter>assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="cube.txt">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="plane.txt">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="alpha01.tga">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="light01.tga">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="moss01.tga">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="normal01.tga">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="spec02.tga">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="sprite01.tga"> <CopyFileToFolders Include="sprite01.tga">
<Filter>Assets</Filter> <Filter>Assets</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="sprite02.tga"> <CopyFileToFolders Include="sprite02.tga">
<Filter>Assets</Filter> <Filter>Assets</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="sprite_data_01.txt">
<Filter>Assets</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="sprite03.tga"> <CopyFileToFolders Include="sprite03.tga">
<Filter>Assets</Filter> <Filter>Assets</Filter>
</CopyFileToFolders> </CopyFileToFolders>
@@ -478,35 +548,53 @@
<CopyFileToFolders Include="water.vs"> <CopyFileToFolders Include="water.vs">
<Filter>shader</Filter> <Filter>shader</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="wall.tga"> <CopyFileToFolders Include="celshading.vs">
<Filter>assets</Filter> <Filter>shader</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="water01.tga"> <CopyFileToFolders Include="celshading.ps">
<Filter>Assets</Filter> <Filter>shader</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="bath.txt"> <CopyFileToFolders Include="assets\Model\TXT\bath.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="marble01.tga"> <CopyFileToFolders Include="assets\Model\TXT\chunk.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="water.txt"> <CopyFileToFolders Include="assets\Model\TXT\cube.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="isosphere.obj"> <CopyFileToFolders Include="assets\Model\TXT\ground.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="cone.obj"> <CopyFileToFolders Include="assets\Model\TXT\plane.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="monke.obj"> <CopyFileToFolders Include="assets\Model\TXT\sphere.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="vaisseau.obj"> <CopyFileToFolders Include="assets\Model\TXT\square.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders> </CopyFileToFolders>
<CopyFileToFolders Include="86.obj"> <CopyFileToFolders Include="assets\Model\TXT\wall.txt">
<Filter>Assets</Filter> <Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\TXT\water.txt">
<Filter>Assets\Model\TXT</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\OBJ\vaisseau.obj">
<Filter>Assets\Model\OBJ</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\OBJ\monke.obj">
<Filter>Assets\Model\OBJ</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\OBJ\isosphere.obj">
<Filter>Assets\Model\OBJ</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\OBJ\cone.obj">
<Filter>Assets\Model\OBJ</Filter>
</CopyFileToFolders>
<CopyFileToFolders Include="assets\Model\OBJ\86.obj">
<Filter>Assets\Model\OBJ</Filter>
</CopyFileToFolders> </CopyFileToFolders>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -3,18 +3,22 @@ Pos=60,60
Size=400,400 Size=400,400
[Window][Khaotic Engine] [Window][Khaotic Engine]
Pos=429,57 Pos=1128,39
Size=392,218 Size=392,273
[Window][Objects] [Window][Objects]
Pos=39,222 Pos=934,36
Size=589,294 Size=457,294
[Window][Terrain] [Window][Terrain]
Pos=60,60 Pos=60,60
Size=342,82 Size=342,82
[Window][Light] [Window][Light]
Pos=95,296 Pos=1551,17
Size=345,230 Size=358,535
[Window][Shader Manager]
Pos=34,253
Size=172,284

View File

@@ -111,6 +111,17 @@ void imguiManager::WidgetAddObject(ApplicationClass* app)
} }
} }
void imguiManager::WidgetShaderWindow(ApplicationClass* app)
{
ImGui::Begin("Shader Manager");
// Checkbox for toggling cel shading globally in the application class by calling the SetCelShading function in the application class when the checkbox state changes
ImGui::Checkbox("Enable Cel Shading", &m_EnableCelShading);
app->SetCelShading(m_EnableCelShading);
ImGui::End();
}
void imguiManager::WidgetObjectWindow(ApplicationClass* app) void imguiManager::WidgetObjectWindow(ApplicationClass* app)
{ {
ImGui::Begin("Objects", &showObjectWindow); ImGui::Begin("Objects", &showObjectWindow);
@@ -194,7 +205,7 @@ void imguiManager::WidgetObjectWindow(ApplicationClass* app)
ofn.lpstrFile = szFile; ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0'; ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile); ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"Texture\0*.tga\0"; ofn.lpstrFilter = L"Texture\0*.png\0";
ofn.nFilterIndex = 1; ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL; ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0; ofn.nMaxFileTitle = 0;
@@ -300,6 +311,11 @@ bool imguiManager::ImGuiWidgetRenderer(ApplicationClass* app)
showLightWindow = true; showLightWindow = true;
} }
if (ImGui::Button("Open Shader Window"))
{
showShaderWindow = true;
}
ImGui::End(); ImGui::End();
// Show windows if their corresponding variables are true // Show windows if their corresponding variables are true
@@ -318,6 +334,11 @@ bool imguiManager::ImGuiWidgetRenderer(ApplicationClass* app)
WidgetLightWindow(app); WidgetLightWindow(app);
} }
if (showShaderWindow)
{
WidgetShaderWindow(app);
}
//render imgui //render imgui
Render(); Render();
@@ -352,7 +373,6 @@ void imguiManager::WidgetLightWindow(ApplicationClass* app)
app->SetLightColor(index, XMVectorSet(col[0], col[1], col[2], 0.0f)); app->SetLightColor(index, XMVectorSet(col[0], col[1], col[2], 0.0f));
} }
ImGui::Separator();
} }
index++; index++;
}; };

View File

@@ -31,13 +31,19 @@ public:
void WidgetObjectWindow(ApplicationClass* app); void WidgetObjectWindow(ApplicationClass* app);
void WidgetTerrainWindow(ApplicationClass* app); void WidgetTerrainWindow(ApplicationClass* app);
void WidgetLightWindow(ApplicationClass* app); void WidgetLightWindow(ApplicationClass* app);
void WidgetShaderWindow(ApplicationClass* app);
bool ImGuiWidgetRenderer(ApplicationClass* app); bool ImGuiWidgetRenderer(ApplicationClass* app);
// Shader toggles
bool m_EnableCelShading;
private : private :
bool showObjectWindow = false; bool showObjectWindow = false;
bool showTerrainWindow = false; bool showTerrainWindow = false;
bool showLightWindow = false; bool showLightWindow = false;
bool showShaderWindow = false;
private: private:
ImGuiIO* io; ImGuiIO* io;

View File

@@ -0,0 +1,832 @@
//--------------------------------------------------------------------------------------
// File: Audio.h
//
// DirectXTK for Audio header
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <objbase.h>
#include <mmreg.h>
#include <Audioclient.h>
#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX)
#include <xma2defs.h>
#ifdef _MSC_VER
#pragma comment(lib,"acphal.lib")
#endif
#endif
#ifndef XAUDIO2_HELPER_FUNCTIONS
#define XAUDIO2_HELPER_FUNCTIONS
#endif
#if defined(USING_XAUDIO2_REDIST) || (_WIN32_WINNT >= 0x0A00 /*_WIN32_WINNT_WIN10*/) || defined(_XBOX_ONE)
#define USING_XAUDIO2_9
#elif (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/)
#define USING_XAUDIO2_8
#elif (_WIN32_WINNT >= 0x0601 /*_WIN32_WINNT_WIN7*/)
#error Windows 7 SP1 requires the XAudio2Redist NuGet package https://aka.ms/xaudio2redist
#else
#error DirectX Tool Kit for Audio not supported on this platform
#endif
#include <xaudio2.h>
#include <xaudio2fx.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4619 4616 5246)
#endif
#include <x3daudio.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <xapofx.h>
#if !defined(USING_XAUDIO2_REDIST) && defined(_MSC_VER)
#if defined(USING_XAUDIO2_8) && defined(NTDDI_WIN10) && !defined(_M_IX86)
// The xaudio2_8.lib in the Windows 10 SDK for x86 is incorrectly annotated as __cdecl instead of __stdcall, so avoid using it in this case.
#pragma comment(lib,"xaudio2_8.lib")
#else
#pragma comment(lib,"xaudio2.lib")
#endif
#endif
#include <DirectXMath.h>
namespace DirectX
{
class SoundEffectInstance;
class SoundStreamInstance;
//----------------------------------------------------------------------------------
struct AudioStatistics
{
size_t playingOneShots; // Number of one-shot sounds currently playing
size_t playingInstances; // Number of sound effect instances currently playing
size_t allocatedInstances; // Number of SoundEffectInstance allocated
size_t allocatedVoices; // Number of XAudio2 voices allocated (standard, 3D, one-shots, and idle one-shots)
size_t allocatedVoices3d; // Number of XAudio2 voices allocated for 3D
size_t allocatedVoicesOneShot; // Number of XAudio2 voices allocated for one-shot sounds
size_t allocatedVoicesIdle; // Number of XAudio2 voices allocated for one-shot sounds but not currently in use
size_t audioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks
#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX)
size_t xmaAudioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks allocated with ApuAlloc
#endif
size_t streamingBytes; // Total size of streaming buffers (in bytes) in streaming WaveBanks
};
//----------------------------------------------------------------------------------
class IVoiceNotify
{
public:
virtual ~IVoiceNotify() = default;
IVoiceNotify(const IVoiceNotify&) = delete;
IVoiceNotify& operator=(const IVoiceNotify&) = delete;
IVoiceNotify(IVoiceNotify&&) = default;
IVoiceNotify& operator=(IVoiceNotify&&) = default;
virtual void __cdecl OnBufferEnd() = 0;
// Notfication that a voice buffer has finished
// Note this is called from XAudio2's worker thread, so it should perform very minimal and thread-safe operations
virtual void __cdecl OnCriticalError() = 0;
// Notification that the audio engine encountered a critical error
virtual void __cdecl OnReset() = 0;
// Notification of an audio engine reset
virtual void __cdecl OnUpdate() = 0;
// Notification of an audio engine per-frame update (opt-in)
virtual void __cdecl OnDestroyEngine() noexcept = 0;
// Notification that the audio engine is being destroyed
virtual void __cdecl OnTrim() = 0;
// Notification of a request to trim the voice pool
virtual void __cdecl GatherStatistics(AudioStatistics& stats) const = 0;
// Contribute to statistics request
virtual void __cdecl OnDestroyParent() noexcept = 0;
// Optional notification used by some objects
protected:
IVoiceNotify() = default;
};
//----------------------------------------------------------------------------------
enum AUDIO_ENGINE_FLAGS : uint32_t
{
AudioEngine_Default = 0x0,
AudioEngine_EnvironmentalReverb = 0x1,
AudioEngine_ReverbUseFilters = 0x2,
AudioEngine_UseMasteringLimiter = 0x4,
AudioEngine_Debug = 0x10000,
AudioEngine_ThrowOnNoAudioHW = 0x20000,
AudioEngine_DisableVoiceReuse = 0x40000,
};
enum SOUND_EFFECT_INSTANCE_FLAGS : uint32_t
{
SoundEffectInstance_Default = 0x0,
SoundEffectInstance_Use3D = 0x1,
SoundEffectInstance_ReverbUseFilters = 0x2,
SoundEffectInstance_NoSetPitch = 0x4,
SoundEffectInstance_UseRedirectLFE = 0x10000,
};
enum AUDIO_ENGINE_REVERB : unsigned int
{
Reverb_Off,
Reverb_Default,
Reverb_Generic,
Reverb_Forest,
Reverb_PaddedCell,
Reverb_Room,
Reverb_Bathroom,
Reverb_LivingRoom,
Reverb_StoneRoom,
Reverb_Auditorium,
Reverb_ConcertHall,
Reverb_Cave,
Reverb_Arena,
Reverb_Hangar,
Reverb_CarpetedHallway,
Reverb_Hallway,
Reverb_StoneCorridor,
Reverb_Alley,
Reverb_City,
Reverb_Mountains,
Reverb_Quarry,
Reverb_Plain,
Reverb_ParkingLot,
Reverb_SewerPipe,
Reverb_Underwater,
Reverb_SmallRoom,
Reverb_MediumRoom,
Reverb_LargeRoom,
Reverb_MediumHall,
Reverb_LargeHall,
Reverb_Plate,
Reverb_MAX
};
enum SoundState
{
STOPPED = 0,
PLAYING,
PAUSED
};
//----------------------------------------------------------------------------------
class AudioEngine
{
public:
explicit AudioEngine(
AUDIO_ENGINE_FLAGS flags = AudioEngine_Default,
_In_opt_ const WAVEFORMATEX* wfx = nullptr,
_In_opt_z_ const wchar_t* deviceId = nullptr,
AUDIO_STREAM_CATEGORY category = AudioCategory_GameEffects) noexcept(false);
AudioEngine(AudioEngine&&) noexcept;
AudioEngine& operator= (AudioEngine&&) noexcept;
AudioEngine(AudioEngine const&) = delete;
AudioEngine& operator= (AudioEngine const&) = delete;
virtual ~AudioEngine();
bool __cdecl Update();
// Performs per-frame processing for the audio engine, returns false if in 'silent mode'
bool __cdecl Reset(_In_opt_ const WAVEFORMATEX* wfx = nullptr, _In_opt_z_ const wchar_t* deviceId = nullptr);
// Reset audio engine from critical error/silent mode using a new device; can also 'migrate' the graph
// Returns true if succesfully reset, false if in 'silent mode' due to no default device
// Note: One shots are lost, all SoundEffectInstances are in the STOPPED state after successful reset
void __cdecl Suspend() noexcept;
void __cdecl Resume();
// Suspend/resumes audio processing (i.e. global pause/resume)
float __cdecl GetMasterVolume() const noexcept;
void __cdecl SetMasterVolume(float volume);
// Master volume property for all sounds
void __cdecl SetReverb(AUDIO_ENGINE_REVERB reverb);
void __cdecl SetReverb(_In_opt_ const XAUDIO2FX_REVERB_PARAMETERS* native);
// Sets environmental reverb for 3D positional audio (if active)
void __cdecl SetMasteringLimit(int release, int loudness);
// Sets the mastering volume limiter properties (if active)
AudioStatistics __cdecl GetStatistics() const;
// Gathers audio engine statistics
WAVEFORMATEXTENSIBLE __cdecl GetOutputFormat() const noexcept;
// Returns the format of the audio output device associated with the mastering voice.
uint32_t __cdecl GetChannelMask() const noexcept;
// Returns the output channel mask
int __cdecl GetOutputSampleRate() const noexcept;
// Returns the sample rate going into the mastering voice
unsigned int __cdecl GetOutputChannels() const noexcept;
// Returns the number of channels going into the mastering voice
bool __cdecl IsAudioDevicePresent() const noexcept;
// Returns true if the audio graph is operating normally, false if in 'silent mode'
bool __cdecl IsCriticalError() const noexcept;
// Returns true if the audio graph is halted due to a critical error (which also places the engine into 'silent mode')
// Voice pool management.
void __cdecl SetDefaultSampleRate(int sampleRate);
// Sample rate for voices in the reuse pool (defaults to 44100)
void __cdecl SetMaxVoicePool(size_t maxOneShots, size_t maxInstances);
// Maximum number of voices to allocate for one-shots and instances
// Note: one-shots over this limit are ignored; too many instance voices throws an exception
void __cdecl TrimVoicePool();
// Releases any currently unused voices
// Internal-use functions
void __cdecl AllocateVoice(_In_ const WAVEFORMATEX* wfx,
SOUND_EFFECT_INSTANCE_FLAGS flags, bool oneshot, _Outptr_result_maybenull_ IXAudio2SourceVoice** voice);
void __cdecl DestroyVoice(_In_ IXAudio2SourceVoice* voice) noexcept;
// Should only be called for instance voices, not one-shots
void __cdecl RegisterNotify(_In_ IVoiceNotify* notify, bool usesUpdate);
void __cdecl UnregisterNotify(_In_ IVoiceNotify* notify, bool usesOneShots, bool usesUpdate);
// XAudio2 interface access
IXAudio2* __cdecl GetInterface() const noexcept;
IXAudio2MasteringVoice* __cdecl GetMasterVoice() const noexcept;
IXAudio2SubmixVoice* __cdecl GetReverbVoice() const noexcept;
X3DAUDIO_HANDLE& __cdecl Get3DHandle() const noexcept;
// Static functions
struct RendererDetail
{
std::wstring deviceId;
std::wstring description;
};
static std::vector<RendererDetail> __cdecl GetRendererDetails();
// Returns a list of valid audio endpoint devices
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
explicit AudioEngine(
AUDIO_ENGINE_FLAGS flags = AudioEngine_Default,
_In_opt_ const WAVEFORMATEX* wfx = nullptr,
_In_opt_z_ const __wchar_t* deviceId = nullptr,
AUDIO_STREAM_CATEGORY category = AudioCategory_GameEffects) noexcept(false);
bool __cdecl Reset(_In_opt_ const WAVEFORMATEX* wfx = nullptr, _In_opt_z_ const __wchar_t* deviceId = nullptr);
#endif
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
class WaveBank
{
public:
WaveBank(_In_ AudioEngine* engine, _In_z_ const wchar_t* wbFileName);
WaveBank(WaveBank&&) noexcept;
WaveBank& operator= (WaveBank&&) noexcept;
WaveBank(WaveBank const&) = delete;
WaveBank& operator= (WaveBank const&) = delete;
virtual ~WaveBank();
void __cdecl Play(unsigned int index);
void __cdecl Play(unsigned int index, float volume, float pitch, float pan);
void __cdecl Play(_In_z_ const char* name);
void __cdecl Play(_In_z_ const char* name, float volume, float pitch, float pan);
std::unique_ptr<SoundEffectInstance> __cdecl CreateInstance(unsigned int index,
SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default);
std::unique_ptr<SoundEffectInstance> __cdecl CreateInstance(_In_z_ const char* name,
SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default);
std::unique_ptr<SoundStreamInstance> __cdecl CreateStreamInstance(unsigned int index,
SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default);
std::unique_ptr<SoundStreamInstance> __cdecl CreateStreamInstance(_In_z_ const char* name,
SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default);
bool __cdecl IsPrepared() const noexcept;
bool __cdecl IsInUse() const noexcept;
bool __cdecl IsStreamingBank() const noexcept;
bool __cdecl IsAdvancedFormat() const noexcept;
size_t __cdecl GetSampleSizeInBytes(unsigned int index) const noexcept;
// Returns size of wave audio data
size_t __cdecl GetSampleDuration(unsigned int index) const noexcept;
// Returns the duration in samples
size_t __cdecl GetSampleDurationMS(unsigned int index) const noexcept;
// Returns the duration in milliseconds
const WAVEFORMATEX* __cdecl GetFormat(unsigned int index, _Out_writes_bytes_(maxsize) WAVEFORMATEX* wfx, size_t maxsize) const noexcept;
int __cdecl Find(_In_z_ const char* name) const;
#ifdef USING_XAUDIO2_9
bool __cdecl FillSubmitBuffer(unsigned int index, _Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const;
#else
void __cdecl FillSubmitBuffer(unsigned int index, _Out_ XAUDIO2_BUFFER& buffer) const;
#endif
void __cdecl UnregisterInstance(_In_ IVoiceNotify* instance);
HANDLE __cdecl GetAsyncHandle() const noexcept;
bool __cdecl GetPrivateData(unsigned int index, _Out_writes_bytes_(datasize) void* data, size_t datasize);
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
WaveBank(_In_ AudioEngine* engine, _In_z_ const __wchar_t* wbFileName);
#endif
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
class SoundEffect
{
public:
SoundEffect(_In_ AudioEngine* engine, _In_z_ const wchar_t* waveFileName);
SoundEffect(_In_ AudioEngine* engine, _Inout_ std::unique_ptr<uint8_t[]>& wavData,
_In_ const WAVEFORMATEX* wfx, _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes);
SoundEffect(_In_ AudioEngine* engine, _Inout_ std::unique_ptr<uint8_t[]>& wavData,
_In_ const WAVEFORMATEX* wfx, _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes,
uint32_t loopStart, uint32_t loopLength);
#ifdef USING_XAUDIO2_9
SoundEffect(_In_ AudioEngine* engine, _Inout_ std::unique_ptr<uint8_t[]>& wavData,
_In_ const WAVEFORMATEX* wfx, _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes,
_In_reads_(seekCount) const uint32_t* seekTable, size_t seekCount);
#endif
SoundEffect(SoundEffect&&) noexcept;
SoundEffect& operator= (SoundEffect&&) noexcept;
SoundEffect(SoundEffect const&) = delete;
SoundEffect& operator= (SoundEffect const&) = delete;
virtual ~SoundEffect();
void __cdecl Play();
void __cdecl Play(float volume, float pitch, float pan);
std::unique_ptr<SoundEffectInstance> __cdecl CreateInstance(SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default);
bool __cdecl IsInUse() const noexcept;
size_t __cdecl GetSampleSizeInBytes() const noexcept;
// Returns size of wave audio data
size_t __cdecl GetSampleDuration() const noexcept;
// Returns the duration in samples
size_t __cdecl GetSampleDurationMS() const noexcept;
// Returns the duration in milliseconds
const WAVEFORMATEX* __cdecl GetFormat() const noexcept;
#ifdef USING_XAUDIO2_9
bool __cdecl FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const;
#else
void __cdecl FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer) const;
#endif
void __cdecl UnregisterInstance(_In_ IVoiceNotify* instance);
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
SoundEffect(_In_ AudioEngine* engine, _In_z_ const __wchar_t* waveFileName);
#endif
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
struct AudioListener : public X3DAUDIO_LISTENER
{
X3DAUDIO_CONE ListenerCone;
AudioListener() noexcept :
X3DAUDIO_LISTENER{},
ListenerCone{}
{
OrientFront.z = -1.f;
OrientTop.y = 1.f;
}
void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept
{
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), v);
}
void __cdecl SetPosition(const XMFLOAT3& pos) noexcept
{
Position.x = pos.x;
Position.y = pos.y;
Position.z = pos.z;
}
void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept
{
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v);
}
void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept
{
Velocity.x = vel.x;
Velocity.y = vel.y;
Velocity.z = vel.z;
}
void XM_CALLCONV SetOrientation(FXMVECTOR forward, FXMVECTOR up) noexcept
{
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up);
}
void __cdecl SetOrientation(const XMFLOAT3& forward, const XMFLOAT3& up) noexcept
{
OrientFront.x = forward.x; OrientTop.x = up.x;
OrientFront.y = forward.y; OrientTop.y = up.y;
OrientFront.z = forward.z; OrientTop.z = up.z;
}
void XM_CALLCONV SetOrientationFromQuaternion(FXMVECTOR quat) noexcept
{
const XMVECTOR forward = XMVector3Rotate(g_XMIdentityR2, quat);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward);
const XMVECTOR up = XMVector3Rotate(g_XMIdentityR1, quat);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up);
}
// Updates velocity and orientation by tracking changes in position over time.
void XM_CALLCONV Update(FXMVECTOR newPos, XMVECTOR upDir, float dt) noexcept
{
if (dt > 0.f)
{
const XMVECTOR lastPos = XMLoadFloat3(reinterpret_cast<const XMFLOAT3*>(&Position));
XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos);
const XMVECTOR vt = XMVectorReplicate(dt);
XMVECTOR v = XMVectorDivide(vDelta, vt);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v);
vDelta = XMVector3Normalize(vDelta);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), vDelta);
v = XMVector3Cross(upDir, vDelta);
v = XMVector3Normalize(v);
v = XMVector3Cross(vDelta, v);
v = XMVector3Normalize(v);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), v);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), newPos);
}
}
void __cdecl SetOmnidirectional() noexcept
{
pCone = nullptr;
}
void __cdecl SetCone(const X3DAUDIO_CONE& listenerCone);
bool __cdecl IsValid() const;
};
//----------------------------------------------------------------------------------
struct AudioEmitter : public X3DAUDIO_EMITTER
{
X3DAUDIO_CONE EmitterCone;
float EmitterAzimuths[XAUDIO2_MAX_AUDIO_CHANNELS];
AudioEmitter() noexcept :
X3DAUDIO_EMITTER{},
EmitterCone{},
EmitterAzimuths{}
{
OrientFront.z = -1.f;
OrientTop.y =
ChannelRadius =
CurveDistanceScaler =
DopplerScaler = 1.f;
ChannelCount = 1;
pChannelAzimuths = EmitterAzimuths;
InnerRadiusAngle = X3DAUDIO_PI / 4.0f;
}
void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept
{
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), v);
}
void __cdecl SetPosition(const XMFLOAT3& pos) noexcept
{
Position.x = pos.x;
Position.y = pos.y;
Position.z = pos.z;
}
void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept
{
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v);
}
void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept
{
Velocity.x = vel.x;
Velocity.y = vel.y;
Velocity.z = vel.z;
}
void XM_CALLCONV SetOrientation(FXMVECTOR forward, FXMVECTOR up) noexcept
{
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up);
}
void __cdecl SetOrientation(const XMFLOAT3& forward, const XMFLOAT3& up) noexcept
{
OrientFront.x = forward.x; OrientTop.x = up.x;
OrientFront.y = forward.y; OrientTop.y = up.y;
OrientFront.z = forward.z; OrientTop.z = up.z;
}
void XM_CALLCONV SetOrientationFromQuaternion(FXMVECTOR quat) noexcept
{
const XMVECTOR forward = XMVector3Rotate(g_XMIdentityR2, quat);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward);
const XMVECTOR up = XMVector3Rotate(g_XMIdentityR1, quat);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up);
}
// Updates velocity and orientation by tracking changes in position over time.
void XM_CALLCONV Update(FXMVECTOR newPos, XMVECTOR upDir, float dt) noexcept
{
if (dt > 0.f)
{
const XMVECTOR lastPos = XMLoadFloat3(reinterpret_cast<const XMFLOAT3*>(&Position));
XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos);
const XMVECTOR vt = XMVectorReplicate(dt);
XMVECTOR v = XMVectorDivide(vDelta, vt);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v);
vDelta = XMVector3Normalize(vDelta);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), vDelta);
v = XMVector3Cross(upDir, vDelta);
v = XMVector3Normalize(v);
v = XMVector3Cross(vDelta, v);
v = XMVector3Normalize(v);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), v);
XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), newPos);
}
}
void __cdecl SetOmnidirectional() noexcept
{
pCone = nullptr;
}
// Only used for single-channel emitters.
void __cdecl SetCone(const X3DAUDIO_CONE& emitterCone);
// Set multi-channel emitter azimuths based on speaker configuration geometry.
void __cdecl EnableDefaultMultiChannel(unsigned int channels, float radius = 1.f);
// Set default volume, LFE, LPF, and reverb curves.
void __cdecl EnableDefaultCurves() noexcept;
void __cdecl EnableLinearCurves() noexcept;
void __cdecl EnableInverseSquareCurves() noexcept
{
pVolumeCurve = nullptr;
pLFECurve = nullptr;
pLPFDirectCurve = nullptr;
pLPFReverbCurve = nullptr;
pReverbCurve = nullptr;
}
bool __cdecl IsValid() const;
};
//----------------------------------------------------------------------------------
class SoundEffectInstance
{
public:
SoundEffectInstance(SoundEffectInstance&&) noexcept;
SoundEffectInstance& operator= (SoundEffectInstance&&) noexcept;
SoundEffectInstance(SoundEffectInstance const&) = delete;
SoundEffectInstance& operator= (SoundEffectInstance const&) = delete;
virtual ~SoundEffectInstance();
void __cdecl Play(bool loop = false);
void __cdecl Stop(bool immediate = true) noexcept;
void __cdecl Pause() noexcept;
void __cdecl Resume();
void __cdecl SetVolume(float volume);
void __cdecl SetPitch(float pitch);
void __cdecl SetPan(float pan);
void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true);
bool __cdecl IsLooped() const noexcept;
SoundState __cdecl GetState() noexcept;
unsigned int __cdecl GetChannelCount() const noexcept;
IVoiceNotify* __cdecl GetVoiceNotify() const noexcept;
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
// Private constructors
SoundEffectInstance(_In_ AudioEngine* engine, _In_ SoundEffect* effect, SOUND_EFFECT_INSTANCE_FLAGS flags);
SoundEffectInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags);
friend std::unique_ptr<SoundEffectInstance> __cdecl SoundEffect::CreateInstance(SOUND_EFFECT_INSTANCE_FLAGS);
friend std::unique_ptr<SoundEffectInstance> __cdecl WaveBank::CreateInstance(unsigned int, SOUND_EFFECT_INSTANCE_FLAGS);
};
//----------------------------------------------------------------------------------
class SoundStreamInstance
{
public:
SoundStreamInstance(SoundStreamInstance&&) noexcept;
SoundStreamInstance& operator= (SoundStreamInstance&&) noexcept;
SoundStreamInstance(SoundStreamInstance const&) = delete;
SoundStreamInstance& operator= (SoundStreamInstance const&) = delete;
virtual ~SoundStreamInstance();
void __cdecl Play(bool loop = false);
void __cdecl Stop(bool immediate = true) noexcept;
void __cdecl Pause() noexcept;
void __cdecl Resume();
void __cdecl SetVolume(float volume);
void __cdecl SetPitch(float pitch);
void __cdecl SetPan(float pan);
void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true);
bool __cdecl IsLooped() const noexcept;
SoundState __cdecl GetState() noexcept;
unsigned int __cdecl GetChannelCount() const noexcept;
IVoiceNotify* __cdecl GetVoiceNotify() const noexcept;
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
// Private constructors
SoundStreamInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags);
friend std::unique_ptr<SoundStreamInstance> __cdecl WaveBank::CreateStreamInstance(unsigned int, SOUND_EFFECT_INSTANCE_FLAGS);
};
//----------------------------------------------------------------------------------
class DynamicSoundEffectInstance
{
public:
DynamicSoundEffectInstance(_In_ AudioEngine* engine,
_In_ std::function<void __cdecl(DynamicSoundEffectInstance*)> bufferNeeded,
int sampleRate, int channels, int sampleBits = 16,
SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default);
DynamicSoundEffectInstance(DynamicSoundEffectInstance&&) noexcept;
DynamicSoundEffectInstance& operator= (DynamicSoundEffectInstance&&) noexcept;
DynamicSoundEffectInstance(DynamicSoundEffectInstance const&) = delete;
DynamicSoundEffectInstance& operator= (DynamicSoundEffectInstance const&) = delete;
virtual ~DynamicSoundEffectInstance();
void __cdecl Play();
void __cdecl Stop(bool immediate = true) noexcept;
void __cdecl Pause() noexcept;
void __cdecl Resume();
void __cdecl SetVolume(float volume);
void __cdecl SetPitch(float pitch);
void __cdecl SetPan(float pan);
void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true);
void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, size_t audioBytes);
void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, uint32_t offset, size_t audioBytes);
SoundState __cdecl GetState() noexcept;
size_t __cdecl GetSampleDuration(size_t bytes) const noexcept;
// Returns duration in samples of a buffer of a given size
size_t __cdecl GetSampleDurationMS(size_t bytes) const noexcept;
// Returns duration in milliseconds of a buffer of a given size
size_t __cdecl GetSampleSizeInBytes(uint64_t duration) const noexcept;
// Returns size of a buffer for a duration given in milliseconds
int __cdecl GetPendingBufferCount() const noexcept;
const WAVEFORMATEX* __cdecl GetFormat() const noexcept;
unsigned int __cdecl GetChannelCount() const noexcept;
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#endif
DEFINE_ENUM_FLAG_OPERATORS(AUDIO_ENGINE_FLAGS);
DEFINE_ENUM_FLAG_OPERATORS(SOUND_EFFECT_INSTANCE_FLAGS);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}

View File

@@ -0,0 +1,164 @@
//--------------------------------------------------------------------------------------
// File: BufferHelpers.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include <cassert>
#include <cstddef>
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#include "GraphicsMemory.h"
#else
#include <d3d11_1.h>
#endif
#include <wrl\client.h>
namespace DirectX
{
// Helpers for creating initialized Direct3D buffer resources.
HRESULT __cdecl CreateStaticBuffer(_In_ ID3D11Device* device,
_In_reads_bytes_(count* stride) const void* ptr,
size_t count,
size_t stride,
unsigned int bindFlags,
_COM_Outptr_ ID3D11Buffer** pBuffer) noexcept;
template<typename T>
HRESULT CreateStaticBuffer(_In_ ID3D11Device* device,
_In_reads_(count) T const* data,
size_t count,
unsigned int bindFlags,
_COM_Outptr_ ID3D11Buffer** pBuffer) noexcept
{
return CreateStaticBuffer(device, data, count, sizeof(T), bindFlags, pBuffer);
}
template<typename T>
HRESULT CreateStaticBuffer(_In_ ID3D11Device* device,
T const& data,
unsigned int bindFlags,
_COM_Outptr_ ID3D11Buffer** pBuffer) noexcept
{
return CreateStaticBuffer(device, data.data(), data.size(), sizeof(typename T::value_type), bindFlags, pBuffer);
}
// Helpers for creating texture from memory arrays.
HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device,
size_t width,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture1D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView,
unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept;
HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device,
size_t width, size_t height,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture2D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView,
unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept;
HRESULT __cdecl CreateTextureFromMemory(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDeviceX,
_In_ ID3D11DeviceContextX* d3dContextX,
#else
_In_ ID3D11Device* device,
_In_ ID3D11DeviceContext* d3dContext,
#endif
size_t width, size_t height,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture2D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device,
size_t width, size_t height, size_t depth,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture3D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView,
unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept;
// Strongly typed wrapper around a Direct3D constant buffer.
inline namespace DX11
{
namespace Private
{
// Base class, not to be used directly: clients should access this via the derived PrimitiveBatch<T>.
class ConstantBufferBase
{
protected:
void __cdecl CreateBuffer(_In_ ID3D11Device* device, size_t bytes, _Outptr_ ID3D11Buffer** pBuffer);
};
}
}
template<typename T>
class ConstantBuffer : public DX11::Private::ConstantBufferBase
{
public:
// Constructor.
ConstantBuffer() = default;
explicit ConstantBuffer(_In_ ID3D11Device* device) noexcept(false)
{
CreateBuffer(device, sizeof(T), mConstantBuffer.GetAddressOf());
}
ConstantBuffer(ConstantBuffer&&) = default;
ConstantBuffer& operator= (ConstantBuffer&&) = default;
ConstantBuffer(ConstantBuffer const&) = delete;
ConstantBuffer& operator= (ConstantBuffer const&) = delete;
void Create(_In_ ID3D11Device* device)
{
CreateBuffer(device, sizeof(T), mConstantBuffer.ReleaseAndGetAddressOf());
}
// Writes new data into the constant buffer.
#if defined(_XBOX_ONE) && defined(_TITLE)
void __cdecl SetData(_In_ ID3D11DeviceContext* deviceContext, T const& value, void** grfxMemory)
{
assert(grfxMemory != nullptr);
void* ptr = GraphicsMemory::Get().Allocate(deviceContext, sizeof(T), 64);
assert(ptr != nullptr);
*(T*)ptr = value;
*grfxMemory = ptr;
}
#else
void __cdecl SetData(_In_ ID3D11DeviceContext* deviceContext, T const& value) noexcept
{
assert(mConstantBuffer);
D3D11_MAPPED_SUBRESOURCE mappedResource;
if (SUCCEEDED(deviceContext->Map(mConstantBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
{
*static_cast<T*>(mappedResource.pData) = value;
deviceContext->Unmap(mConstantBuffer.Get(), 0);
}
}
#endif // _XBOX_ONE && _TITLE
// Looks up the underlying D3D constant buffer.
ID3D11Buffer* GetBuffer() const noexcept { return mConstantBuffer.Get(); }
private:
Microsoft::WRL::ComPtr<ID3D11Buffer> mConstantBuffer;
};
}

View File

@@ -0,0 +1,72 @@
//--------------------------------------------------------------------------------------
// File: CommonStates.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <memory>
namespace DirectX
{
inline namespace DX11
{
class CommonStates
{
public:
explicit CommonStates(_In_ ID3D11Device* device);
CommonStates(CommonStates&&) noexcept;
CommonStates& operator= (CommonStates&&) noexcept;
CommonStates(CommonStates const&) = delete;
CommonStates& operator= (CommonStates const&) = delete;
virtual ~CommonStates();
// Blend states.
ID3D11BlendState* __cdecl Opaque() const;
ID3D11BlendState* __cdecl AlphaBlend() const;
ID3D11BlendState* __cdecl Additive() const;
ID3D11BlendState* __cdecl NonPremultiplied() const;
// Depth stencil states.
ID3D11DepthStencilState* __cdecl DepthNone() const;
ID3D11DepthStencilState* __cdecl DepthDefault() const;
ID3D11DepthStencilState* __cdecl DepthRead() const;
ID3D11DepthStencilState* __cdecl DepthReverseZ() const;
ID3D11DepthStencilState* __cdecl DepthReadReverseZ() const;
// Rasterizer states.
ID3D11RasterizerState* __cdecl CullNone() const;
ID3D11RasterizerState* __cdecl CullClockwise() const;
ID3D11RasterizerState* __cdecl CullCounterClockwise() const;
ID3D11RasterizerState* __cdecl Wireframe() const;
// Sampler states.
ID3D11SamplerState* __cdecl PointWrap() const;
ID3D11SamplerState* __cdecl PointClamp() const;
ID3D11SamplerState* __cdecl LinearWrap() const;
ID3D11SamplerState* __cdecl LinearClamp() const;
ID3D11SamplerState* __cdecl AnisotropicWrap() const;
ID3D11SamplerState* __cdecl AnisotropicClamp() const;
private:
// Private implementation.
class Impl;
std::shared_ptr<Impl> pImpl;
};
}
}

View File

@@ -0,0 +1,182 @@
//--------------------------------------------------------------------------------------
// File: DDSTextureLoader.h
//
// Functions for loading a DDS texture and creating a Direct3D runtime resource for it
//
// Note these functions are useful as a light-weight runtime loader for DDS files. For
// a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' library.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <cstddef>
#include <cstdint>
namespace DirectX
{
#ifndef DDS_ALPHA_MODE_DEFINED
#define DDS_ALPHA_MODE_DEFINED
enum DDS_ALPHA_MODE : uint32_t
{
DDS_ALPHA_MODE_UNKNOWN = 0,
DDS_ALPHA_MODE_STRAIGHT = 1,
DDS_ALPHA_MODE_PREMULTIPLIED = 2,
DDS_ALPHA_MODE_OPAQUE = 3,
DDS_ALPHA_MODE_CUSTOM = 4,
};
#endif
inline namespace DX11
{
enum DDS_LOADER_FLAGS : uint32_t
{
DDS_LOADER_DEFAULT = 0,
DDS_LOADER_FORCE_SRGB = 0x1,
DDS_LOADER_IGNORE_SRGB = 0x2,
};
}
// Standard version
HRESULT __cdecl CreateDDSTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
HRESULT __cdecl CreateDDSTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
// Standard version with optional auto-gen mipmap support
HRESULT __cdecl CreateDDSTextureFromMemory(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
HRESULT __cdecl CreateDDSTextureFromFile(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
// Extended version
HRESULT __cdecl CreateDDSTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ DDS_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
HRESULT __cdecl CreateDDSTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ DDS_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
// Extended version with optional auto-gen mipmap support
HRESULT __cdecl CreateDDSTextureFromMemoryEx(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ DDS_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
HRESULT __cdecl CreateDDSTextureFromFileEx(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ DDS_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr) noexcept;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#endif
inline namespace DX11
{
DEFINE_ENUM_FLAG_OPERATORS(DDS_LOADER_FLAGS);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}

View File

@@ -0,0 +1,232 @@
//--------------------------------------------------------------------------------------
// File: DirectXHelpers.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#ifdef _MSC_VER
#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
#if !defined(_XBOX_ONE) || !defined(_TITLE)
#pragma comment(lib,"dxguid.lib")
#endif
#endif
#endif
#ifndef IID_GRAPHICS_PPV_ARGS
#define IID_GRAPHICS_PPV_ARGS(x) IID_PPV_ARGS(x)
#endif
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <exception>
//
// The core Direct3D headers provide the following helper C++ classes
// CD3D11_RECT
// CD3D11_BOX
// CD3D11_DEPTH_STENCIL_DESC
// CD3D11_BLEND_DESC, CD3D11_BLEND_DESC1
// CD3D11_RASTERIZER_DESC, CD3D11_RASTERIZER_DESC1
// CD3D11_BUFFER_DESC
// CD3D11_TEXTURE1D_DESC
// CD3D11_TEXTURE2D_DESC
// CD3D11_TEXTURE3D_DESC
// CD3D11_SHADER_RESOURCE_VIEW_DESC
// CD3D11_RENDER_TARGET_VIEW_DESC
// CD3D11_VIEWPORT
// CD3D11_DEPTH_STENCIL_VIEW_DESC
// CD3D11_UNORDERED_ACCESS_VIEW_DESC
// CD3D11_SAMPLER_DESC
// CD3D11_QUERY_DESC
// CD3D11_COUNTER_DESC
//
namespace DirectX
{
inline namespace DX11
{
class IEffect;
}
// simliar to std::lock_guard for exception-safe Direct3D resource locking
class MapGuard : public D3D11_MAPPED_SUBRESOURCE
{
public:
MapGuard(_In_ ID3D11DeviceContext* context,
_In_ ID3D11Resource *resource,
_In_ unsigned int subresource,
_In_ D3D11_MAP mapType,
_In_ unsigned int mapFlags) noexcept(false)
: mContext(context), mResource(resource), mSubresource(subresource)
{
HRESULT hr = mContext->Map(resource, subresource, mapType, mapFlags, this);
if (FAILED(hr))
{
throw std::exception();
}
}
MapGuard(MapGuard&&) = delete;
MapGuard& operator= (MapGuard&&) = delete;
MapGuard(MapGuard const&) = delete;
MapGuard& operator= (MapGuard const&) = delete;
~MapGuard()
{
mContext->Unmap(mResource, mSubresource);
}
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"
#endif
uint8_t* get() const noexcept
{
return static_cast<uint8_t*>(pData);
}
uint8_t* get(size_t slice) const noexcept
{
return static_cast<uint8_t*>(pData) + (slice * DepthPitch);
}
uint8_t* scanline(size_t row) const noexcept
{
return static_cast<uint8_t*>(pData) + (row * RowPitch);
}
uint8_t* scanline(size_t slice, size_t row) const noexcept
{
return static_cast<uint8_t*>(pData) + (slice * DepthPitch) + (row * RowPitch);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
template<typename T>
void copy(_In_reads_(count) T const* data, size_t count) noexcept
{
memcpy(pData, data, count * sizeof(T));
}
template<typename T>
void copy(T const& data) noexcept
{
memcpy(pData, data.data(), data.size() * sizeof(typename T::value_type));
}
private:
ID3D11DeviceContext* mContext;
ID3D11Resource* mResource;
unsigned int mSubresource;
};
// Helper sets a D3D resource name string (used by PIX and debug layer leak reporting).
#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
template<UINT TNameLength>
inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const char(&name)[TNameLength]) noexcept
{
#if defined(_XBOX_ONE) && defined(_TITLE)
wchar_t wname[MAX_PATH];
int result = MultiByteToWideChar(CP_UTF8, 0, name, TNameLength, wname, MAX_PATH);
if (result > 0)
{
resource->SetName(wname);
}
#else
resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name);
#endif
}
#else
template<UINT TNameLength>
inline void SetDebugObjectName(_In_ ID3D11DeviceChild*, _In_z_ const char(&)[TNameLength]) noexcept
{
}
#endif
#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
template<UINT TNameLength>
inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const wchar_t(&name)[TNameLength])
{
#if defined(_XBOX_ONE) && defined(_TITLE)
resource->SetName(name);
#else
char aname[MAX_PATH];
int result = WideCharToMultiByte(CP_UTF8, 0, name, TNameLength, aname, MAX_PATH, nullptr, nullptr);
if (result > 0)
{
resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, aname);
}
#endif
}
#else
template<UINT TNameLength>
inline void SetDebugObjectName(_In_ ID3D11DeviceChild*, _In_z_ const wchar_t(&)[TNameLength])
{
}
#endif
inline namespace DX11
{
// Helper to check for power-of-2
template<typename T>
constexpr bool IsPowerOf2(T x) noexcept { return ((x != 0) && !(x & (x - 1))); }
// Helpers for aligning values by a power of 2
template<typename T>
inline T AlignDown(T size, size_t alignment) noexcept
{
if (alignment > 0)
{
assert(((alignment - 1) & alignment) == 0);
auto mask = static_cast<T>(alignment - 1);
return size & ~mask;
}
return size;
}
template<typename T>
inline T AlignUp(T size, size_t alignment) noexcept
{
if (alignment > 0)
{
assert(((alignment - 1) & alignment) == 0);
auto mask = static_cast<T>(alignment - 1);
return (size + mask) & ~mask;
}
return size;
}
}
// Helper for creating a Direct3D input layout to match a shader from an IEffect
HRESULT __cdecl CreateInputLayoutFromEffect(_In_ ID3D11Device* device,
_In_ IEffect* effect,
_In_reads_(count) const D3D11_INPUT_ELEMENT_DESC* desc,
size_t count,
_COM_Outptr_ ID3D11InputLayout** pInputLayout) noexcept;
template<typename T>
HRESULT CreateInputLayoutFromEffect(_In_ ID3D11Device* device,
_In_ IEffect* effect,
_COM_Outptr_ ID3D11InputLayout** pInputLayout) noexcept
{
return CreateInputLayoutFromEffect(device, effect, T::InputElements, T::InputElementCount, pInputLayout);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,329 @@
//--------------------------------------------------------------------------------------
// File: GamePad.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#pragma once
#if !defined(USING_XINPUT) && !defined(USING_GAMEINPUT) && !defined(USING_WINDOWS_GAMING_INPUT)
#ifdef _GAMING_DESKTOP
#include <grdk.h>
#endif
#if (defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_GAMES)) || (defined(_GAMING_DESKTOP) && (_GRDK_EDITION >= 220600))
#define USING_GAMEINPUT
#elif (_WIN32_WINNT >= 0x0A00 /*_WIN32_WINNT_WIN10*/) && !defined(_GAMING_DESKTOP) && !defined(__MINGW32__)
#define USING_WINDOWS_GAMING_INPUT
#elif !defined(_XBOX_ONE)
#define USING_XINPUT
#endif
#endif // !USING_XINPUT && !USING_GAMEINPUT && !USING_WINDOWS_GAMING_INPUT
#ifdef USING_GAMEINPUT
#include <GameInput.h>
#if !defined(_GAMING_XBOX) && defined(_MSC_VER)
#pragma comment(lib,"gameinput.lib")
#endif
#elif defined(USING_WINDOWS_GAMING_INPUT)
#ifdef _MSC_VER
#pragma comment(lib,"runtimeobject.lib")
#endif
#include <string>
#elif defined(_XBOX_ONE)
// Legacy Xbox One XDK uses Windows::Xbox::Input
#elif defined(USING_XINPUT)
#ifdef _MSC_VER
#if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/ )
#pragma comment(lib,"xinput.lib")
#else
#pragma comment(lib,"xinput9_1_0.lib")
#endif
#endif
#endif
#include <cstdint>
#include <memory>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#endif
namespace DirectX
{
class GamePad
{
public:
GamePad() noexcept(false);
GamePad(GamePad&&) noexcept;
GamePad& operator= (GamePad&&) noexcept;
GamePad(GamePad const&) = delete;
GamePad& operator=(GamePad const&) = delete;
virtual ~GamePad();
#if defined(USING_GAMEINPUT) || defined(USING_WINDOWS_GAMING_INPUT) || defined(_XBOX_ONE)
static constexpr int MAX_PLAYER_COUNT = 8;
#else
static constexpr int MAX_PLAYER_COUNT = 4;
#endif
static constexpr int c_MostRecent = -1;
#ifdef USING_GAMEINPUT
static constexpr int c_MergedInput = -2;
#endif
enum DeadZone
{
DEAD_ZONE_INDEPENDENT_AXES = 0,
DEAD_ZONE_CIRCULAR,
DEAD_ZONE_NONE,
};
struct Buttons
{
bool a;
bool b;
bool x;
bool y;
bool leftStick;
bool rightStick;
bool leftShoulder;
bool rightShoulder;
union
{
bool back;
bool view;
};
union
{
bool start;
bool menu;
};
};
struct DPad
{
bool up;
bool down;
bool right;
bool left;
};
struct ThumbSticks
{
float leftX;
float leftY;
float rightX;
float rightY;
};
struct Triggers
{
float left;
float right;
};
struct State
{
bool connected;
uint64_t packet;
Buttons buttons;
DPad dpad;
ThumbSticks thumbSticks;
Triggers triggers;
bool __cdecl IsConnected() const noexcept { return connected; }
// Is the button pressed currently?
bool __cdecl IsAPressed() const noexcept { return buttons.a; }
bool __cdecl IsBPressed() const noexcept { return buttons.b; }
bool __cdecl IsXPressed() const noexcept { return buttons.x; }
bool __cdecl IsYPressed() const noexcept { return buttons.y; }
bool __cdecl IsLeftStickPressed() const noexcept { return buttons.leftStick; }
bool __cdecl IsRightStickPressed() const noexcept { return buttons.rightStick; }
bool __cdecl IsLeftShoulderPressed() const noexcept { return buttons.leftShoulder; }
bool __cdecl IsRightShoulderPressed() const noexcept { return buttons.rightShoulder; }
bool __cdecl IsBackPressed() const noexcept { return buttons.back; }
bool __cdecl IsViewPressed() const noexcept { return buttons.view; }
bool __cdecl IsStartPressed() const noexcept { return buttons.start; }
bool __cdecl IsMenuPressed() const noexcept { return buttons.menu; }
bool __cdecl IsDPadDownPressed() const noexcept { return dpad.down; }
bool __cdecl IsDPadUpPressed() const noexcept { return dpad.up; }
bool __cdecl IsDPadLeftPressed() const noexcept { return dpad.left; }
bool __cdecl IsDPadRightPressed() const noexcept { return dpad.right; }
bool __cdecl IsLeftThumbStickUp() const noexcept { return (thumbSticks.leftY > 0.5f) != 0; }
bool __cdecl IsLeftThumbStickDown() const noexcept { return (thumbSticks.leftY < -0.5f) != 0; }
bool __cdecl IsLeftThumbStickLeft() const noexcept { return (thumbSticks.leftX < -0.5f) != 0; }
bool __cdecl IsLeftThumbStickRight() const noexcept { return (thumbSticks.leftX > 0.5f) != 0; }
bool __cdecl IsRightThumbStickUp() const noexcept { return (thumbSticks.rightY > 0.5f) != 0; }
bool __cdecl IsRightThumbStickDown() const noexcept { return (thumbSticks.rightY < -0.5f) != 0; }
bool __cdecl IsRightThumbStickLeft() const noexcept { return (thumbSticks.rightX < -0.5f) != 0; }
bool __cdecl IsRightThumbStickRight() const noexcept { return (thumbSticks.rightX > 0.5f) != 0; }
bool __cdecl IsLeftTriggerPressed() const noexcept { return (triggers.left > 0.5f) != 0; }
bool __cdecl IsRightTriggerPressed() const noexcept { return (triggers.right > 0.5f) != 0; }
};
struct Capabilities
{
enum Type
{
UNKNOWN = 0,
GAMEPAD,
WHEEL,
ARCADE_STICK,
FLIGHT_STICK,
DANCE_PAD,
GUITAR,
GUITAR_ALTERNATE,
DRUM_KIT,
GUITAR_BASS = 11,
ARCADE_PAD = 19,
};
bool connected;
Type gamepadType;
#ifdef USING_GAMEINPUT
APP_LOCAL_DEVICE_ID id;
#elif defined(USING_WINDOWS_GAMING_INPUT)
std::wstring id;
#else
uint64_t id;
#endif
uint16_t vid;
uint16_t pid;
Capabilities() noexcept : connected(false), gamepadType(UNKNOWN), id{}, vid(0), pid(0) {}
bool __cdecl IsConnected() const noexcept { return connected; }
};
class ButtonStateTracker
{
public:
enum ButtonState
{
UP = 0, // Button is up
HELD = 1, // Button is held down
RELEASED = 2, // Button was just released
PRESSED = 3, // Buton was just pressed
};
ButtonState a;
ButtonState b;
ButtonState x;
ButtonState y;
ButtonState leftStick;
ButtonState rightStick;
ButtonState leftShoulder;
ButtonState rightShoulder;
union
{
ButtonState back;
ButtonState view;
};
union
{
ButtonState start;
ButtonState menu;
};
ButtonState dpadUp;
ButtonState dpadDown;
ButtonState dpadLeft;
ButtonState dpadRight;
ButtonState leftStickUp;
ButtonState leftStickDown;
ButtonState leftStickLeft;
ButtonState leftStickRight;
ButtonState rightStickUp;
ButtonState rightStickDown;
ButtonState rightStickLeft;
ButtonState rightStickRight;
ButtonState leftTrigger;
ButtonState rightTrigger;
#ifdef _PREFAST_
#pragma prefast(push)
#pragma prefast(disable : 26495, "Reset() performs the initialization")
#endif
ButtonStateTracker() noexcept { Reset(); }
#ifdef _PREFAST_
#pragma prefast(pop)
#endif
void __cdecl Update(const State& state) noexcept;
void __cdecl Reset() noexcept;
State __cdecl GetLastState() const noexcept { return lastState; }
private:
State lastState;
};
// Retrieve the current state of the gamepad of the associated player index
State __cdecl GetState(int player, DeadZone deadZoneMode = DEAD_ZONE_INDEPENDENT_AXES);
// Retrieve the current capabilities of the gamepad of the associated player index
Capabilities __cdecl GetCapabilities(int player);
// Set the vibration motor speeds of the gamepad
bool __cdecl SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger = 0.f, float rightTrigger = 0.f) noexcept;
// Handle suspending/resuming
void __cdecl Suspend() noexcept;
void __cdecl Resume() noexcept;
#ifdef USING_GAMEINPUT
void __cdecl RegisterEvents(void* ctrlChanged) noexcept;
// Underlying device access
_Success_(return)
bool __cdecl GetDevice(int player, _Outptr_ IGameInputDevice * *device) noexcept;
#elif defined(USING_WINDOWS_GAMING_INPUT) || defined(_XBOX_ONE)
void __cdecl RegisterEvents(void* ctrlChanged, void* userChanged) noexcept;
#endif
// Singleton
static GamePad& __cdecl Get();
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif

View File

@@ -0,0 +1,111 @@
//--------------------------------------------------------------------------------------
// File: GeometricPrimitive.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include "VertexTypes.h"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <vector>
#include <DirectXColors.h>
namespace DirectX
{
inline namespace DX11
{
class IEffect;
class GeometricPrimitive
{
public:
GeometricPrimitive(GeometricPrimitive&&) = default;
GeometricPrimitive& operator= (GeometricPrimitive&&) = default;
GeometricPrimitive(GeometricPrimitive const&) = delete;
GeometricPrimitive& operator= (GeometricPrimitive const&) = delete;
using VertexType = VertexPositionNormalTexture;
using VertexCollection = std::vector<VertexType>;
using IndexCollection = std::vector<uint16_t>;
virtual ~GeometricPrimitive();
// Factory methods.
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCube(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateBox(_In_ ID3D11DeviceContext* deviceContext, const XMFLOAT3& size, bool rhcoords = true, bool invertn = false);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateSphere(_In_ ID3D11DeviceContext* deviceContext, float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateGeoSphere(_In_ ID3D11DeviceContext* deviceContext, float diameter = 1, size_t tessellation = 3, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCylinder(_In_ ID3D11DeviceContext* deviceContext, float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCone(_In_ ID3D11DeviceContext* deviceContext, float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTorus(_In_ ID3D11DeviceContext* deviceContext, float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTetrahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateOctahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateDodecahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateIcosahedron(_In_ ID3D11DeviceContext* deviceContext, float size = 1, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateTeapot(_In_ ID3D11DeviceContext* deviceContext, float size = 1, size_t tessellation = 8, bool rhcoords = true);
static std::unique_ptr<GeometricPrimitive> __cdecl CreateCustom(_In_ ID3D11DeviceContext* deviceContext, const VertexCollection& vertices, const IndexCollection& indices);
static void __cdecl CreateCube(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateBox(VertexCollection& vertices, IndexCollection& indices, const XMFLOAT3& size, bool rhcoords = true, bool invertn = false);
static void __cdecl CreateSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 16, bool rhcoords = true, bool invertn = false);
static void __cdecl CreateGeoSphere(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, size_t tessellation = 3, bool rhcoords = true);
static void __cdecl CreateCylinder(VertexCollection& vertices, IndexCollection& indices, float height = 1, float diameter = 1, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateCone(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float height = 1, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateTorus(VertexCollection& vertices, IndexCollection& indices, float diameter = 1, float thickness = 0.333f, size_t tessellation = 32, bool rhcoords = true);
static void __cdecl CreateTetrahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateOctahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateDodecahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateIcosahedron(VertexCollection& vertices, IndexCollection& indices, float size = 1, bool rhcoords = true);
static void __cdecl CreateTeapot(VertexCollection& vertices, IndexCollection& indices, float size = 1, size_t tessellation = 8, bool rhcoords = true);
// Draw the primitive.
void XM_CALLCONV Draw(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection,
FXMVECTOR color = Colors::White,
_In_opt_ ID3D11ShaderResourceView* texture = nullptr,
bool wireframe = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Draw the primitive using a custom effect.
void __cdecl Draw(_In_ IEffect* effect,
_In_ ID3D11InputLayout* inputLayout,
bool alpha = false, bool wireframe = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
void __cdecl DrawInstanced(_In_ IEffect* effect,
_In_ ID3D11InputLayout* inputLayout,
uint32_t instanceCount,
bool alpha = false, bool wireframe = false,
uint32_t startInstanceLocation = 0,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Create input layout for drawing with a custom effect.
void __cdecl CreateInputLayout(_In_ IEffect* effect, _Outptr_ ID3D11InputLayout** inputLayout) const;
static void SetDepthBufferMode(bool reverseZ)
{
s_reversez = reverseZ;
}
private:
static bool s_reversez;
GeometricPrimitive() noexcept(false);
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
}

View File

@@ -0,0 +1,57 @@
//--------------------------------------------------------------------------------------
// File: GraphicsMemory.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <cstddef>
#include <memory>
namespace DirectX
{
inline namespace DX11
{
class GraphicsMemory
{
public:
#if defined(_XBOX_ONE) && defined(_TITLE)
GraphicsMemory(_In_ ID3D11DeviceX* device, unsigned int backBufferCount = 2);
#else
GraphicsMemory(_In_ ID3D11Device* device, unsigned int backBufferCount = 2);
#endif
GraphicsMemory(GraphicsMemory&&) noexcept;
GraphicsMemory& operator= (GraphicsMemory&&) noexcept;
GraphicsMemory(GraphicsMemory const&) = delete;
GraphicsMemory& operator=(GraphicsMemory const&) = delete;
virtual ~GraphicsMemory();
void* __cdecl Allocate(_In_opt_ ID3D11DeviceContext* context, size_t size, int alignment);
void __cdecl Commit();
// Singleton
static GraphicsMemory& __cdecl Get();
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
}

View File

@@ -0,0 +1,532 @@
//--------------------------------------------------------------------------------------
// File: Keyboard.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#pragma once
#if !defined(USING_XINPUT) && !defined(USING_GAMEINPUT) && !defined(USING_COREWINDOW)
#ifdef _GAMING_DESKTOP
#include <grdk.h>
#endif
#if (defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_GAMES)) || (defined(_GAMING_DESKTOP) && (_GRDK_EDITION >= 220600))
#define USING_GAMEINPUT
#elif (defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)) || (defined(_XBOX_ONE) && defined(_TITLE))
#define USING_COREWINDOW
#endif
#endif // !USING_XINPUT && !USING_GAMEINPUT && !USING_WINDOWS_GAMING_INPUT
#if defined(USING_GAMEINPUT) && !defined(_GAMING_XBOX) && defined(_MSC_VER)
#pragma comment(lib,"gameinput.lib")
#endif
#include <cstdint>
#include <memory>
#ifdef USING_COREWINDOW
namespace ABI { namespace Windows { namespace UI { namespace Core { struct ICoreWindow; } } } }
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#endif
namespace DirectX
{
class Keyboard
{
public:
Keyboard() noexcept(false);
Keyboard(Keyboard&&) noexcept;
Keyboard& operator= (Keyboard&&) noexcept;
Keyboard(Keyboard const&) = delete;
Keyboard& operator=(Keyboard const&) = delete;
virtual ~Keyboard();
enum Keys : unsigned char
{
None = 0,
Back = 0x8,
Tab = 0x9,
Enter = 0xd,
Pause = 0x13,
CapsLock = 0x14,
Kana = 0x15,
ImeOn = 0x16,
Kanji = 0x19,
ImeOff = 0x1a,
Escape = 0x1b,
ImeConvert = 0x1c,
ImeNoConvert = 0x1d,
Space = 0x20,
PageUp = 0x21,
PageDown = 0x22,
End = 0x23,
Home = 0x24,
Left = 0x25,
Up = 0x26,
Right = 0x27,
Down = 0x28,
Select = 0x29,
Print = 0x2a,
Execute = 0x2b,
PrintScreen = 0x2c,
Insert = 0x2d,
Delete = 0x2e,
Help = 0x2f,
D0 = 0x30,
D1 = 0x31,
D2 = 0x32,
D3 = 0x33,
D4 = 0x34,
D5 = 0x35,
D6 = 0x36,
D7 = 0x37,
D8 = 0x38,
D9 = 0x39,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4a,
K = 0x4b,
L = 0x4c,
M = 0x4d,
N = 0x4e,
O = 0x4f,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5a,
LeftWindows = 0x5b,
RightWindows = 0x5c,
Apps = 0x5d,
Sleep = 0x5f,
NumPad0 = 0x60,
NumPad1 = 0x61,
NumPad2 = 0x62,
NumPad3 = 0x63,
NumPad4 = 0x64,
NumPad5 = 0x65,
NumPad6 = 0x66,
NumPad7 = 0x67,
NumPad8 = 0x68,
NumPad9 = 0x69,
Multiply = 0x6a,
Add = 0x6b,
Separator = 0x6c,
Subtract = 0x6d,
Decimal = 0x6e,
Divide = 0x6f,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7a,
F12 = 0x7b,
F13 = 0x7c,
F14 = 0x7d,
F15 = 0x7e,
F16 = 0x7f,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
NumLock = 0x90,
Scroll = 0x91,
LeftShift = 0xa0,
RightShift = 0xa1,
LeftControl = 0xa2,
RightControl = 0xa3,
LeftAlt = 0xa4,
RightAlt = 0xa5,
BrowserBack = 0xa6,
BrowserForward = 0xa7,
BrowserRefresh = 0xa8,
BrowserStop = 0xa9,
BrowserSearch = 0xaa,
BrowserFavorites = 0xab,
BrowserHome = 0xac,
VolumeMute = 0xad,
VolumeDown = 0xae,
VolumeUp = 0xaf,
MediaNextTrack = 0xb0,
MediaPreviousTrack = 0xb1,
MediaStop = 0xb2,
MediaPlayPause = 0xb3,
LaunchMail = 0xb4,
SelectMedia = 0xb5,
LaunchApplication1 = 0xb6,
LaunchApplication2 = 0xb7,
OemSemicolon = 0xba,
OemPlus = 0xbb,
OemComma = 0xbc,
OemMinus = 0xbd,
OemPeriod = 0xbe,
OemQuestion = 0xbf,
OemTilde = 0xc0,
OemOpenBrackets = 0xdb,
OemPipe = 0xdc,
OemCloseBrackets = 0xdd,
OemQuotes = 0xde,
Oem8 = 0xdf,
OemBackslash = 0xe2,
ProcessKey = 0xe5,
OemCopy = 0xf2,
OemAuto = 0xf3,
OemEnlW = 0xf4,
Attn = 0xf6,
Crsel = 0xf7,
Exsel = 0xf8,
EraseEof = 0xf9,
Play = 0xfa,
Zoom = 0xfb,
Pa1 = 0xfd,
OemClear = 0xfe,
};
struct State
{
bool Reserved0 : 8;
bool Back : 1; // VK_BACK, 0x8
bool Tab : 1; // VK_TAB, 0x9
bool Reserved1 : 3;
bool Enter : 1; // VK_RETURN, 0xD
bool Reserved2 : 2;
bool Reserved3 : 3;
bool Pause : 1; // VK_PAUSE, 0x13
bool CapsLock : 1; // VK_CAPITAL, 0x14
bool Kana : 1; // VK_KANA, 0x15
bool ImeOn : 1; // VK_IME_ON, 0x16
bool Reserved4 : 1;
bool Reserved5 : 1;
bool Kanji : 1; // VK_KANJI, 0x19
bool ImeOff : 1; // VK_IME_OFF, 0X1A
bool Escape : 1; // VK_ESCAPE, 0x1B
bool ImeConvert : 1; // VK_CONVERT, 0x1C
bool ImeNoConvert : 1; // VK_NONCONVERT, 0x1D
bool Reserved7 : 2;
bool Space : 1; // VK_SPACE, 0x20
bool PageUp : 1; // VK_PRIOR, 0x21
bool PageDown : 1; // VK_NEXT, 0x22
bool End : 1; // VK_END, 0x23
bool Home : 1; // VK_HOME, 0x24
bool Left : 1; // VK_LEFT, 0x25
bool Up : 1; // VK_UP, 0x26
bool Right : 1; // VK_RIGHT, 0x27
bool Down : 1; // VK_DOWN, 0x28
bool Select : 1; // VK_SELECT, 0x29
bool Print : 1; // VK_PRINT, 0x2A
bool Execute : 1; // VK_EXECUTE, 0x2B
bool PrintScreen : 1; // VK_SNAPSHOT, 0x2C
bool Insert : 1; // VK_INSERT, 0x2D
bool Delete : 1; // VK_DELETE, 0x2E
bool Help : 1; // VK_HELP, 0x2F
bool D0 : 1; // 0x30
bool D1 : 1; // 0x31
bool D2 : 1; // 0x32
bool D3 : 1; // 0x33
bool D4 : 1; // 0x34
bool D5 : 1; // 0x35
bool D6 : 1; // 0x36
bool D7 : 1; // 0x37
bool D8 : 1; // 0x38
bool D9 : 1; // 0x39
bool Reserved8 : 6;
bool Reserved9 : 1;
bool A : 1; // 0x41
bool B : 1; // 0x42
bool C : 1; // 0x43
bool D : 1; // 0x44
bool E : 1; // 0x45
bool F : 1; // 0x46
bool G : 1; // 0x47
bool H : 1; // 0x48
bool I : 1; // 0x49
bool J : 1; // 0x4A
bool K : 1; // 0x4B
bool L : 1; // 0x4C
bool M : 1; // 0x4D
bool N : 1; // 0x4E
bool O : 1; // 0x4F
bool P : 1; // 0x50
bool Q : 1; // 0x51
bool R : 1; // 0x52
bool S : 1; // 0x53
bool T : 1; // 0x54
bool U : 1; // 0x55
bool V : 1; // 0x56
bool W : 1; // 0x57
bool X : 1; // 0x58
bool Y : 1; // 0x59
bool Z : 1; // 0x5A
bool LeftWindows : 1; // VK_LWIN, 0x5B
bool RightWindows : 1; // VK_RWIN, 0x5C
bool Apps : 1; // VK_APPS, 0x5D
bool Reserved10 : 1;
bool Sleep : 1; // VK_SLEEP, 0x5F
bool NumPad0 : 1; // VK_NUMPAD0, 0x60
bool NumPad1 : 1; // VK_NUMPAD1, 0x61
bool NumPad2 : 1; // VK_NUMPAD2, 0x62
bool NumPad3 : 1; // VK_NUMPAD3, 0x63
bool NumPad4 : 1; // VK_NUMPAD4, 0x64
bool NumPad5 : 1; // VK_NUMPAD5, 0x65
bool NumPad6 : 1; // VK_NUMPAD6, 0x66
bool NumPad7 : 1; // VK_NUMPAD7, 0x67
bool NumPad8 : 1; // VK_NUMPAD8, 0x68
bool NumPad9 : 1; // VK_NUMPAD9, 0x69
bool Multiply : 1; // VK_MULTIPLY, 0x6A
bool Add : 1; // VK_ADD, 0x6B
bool Separator : 1; // VK_SEPARATOR, 0x6C
bool Subtract : 1; // VK_SUBTRACT, 0x6D
bool Decimal : 1; // VK_DECIMANL, 0x6E
bool Divide : 1; // VK_DIVIDE, 0x6F
bool F1 : 1; // VK_F1, 0x70
bool F2 : 1; // VK_F2, 0x71
bool F3 : 1; // VK_F3, 0x72
bool F4 : 1; // VK_F4, 0x73
bool F5 : 1; // VK_F5, 0x74
bool F6 : 1; // VK_F6, 0x75
bool F7 : 1; // VK_F7, 0x76
bool F8 : 1; // VK_F8, 0x77
bool F9 : 1; // VK_F9, 0x78
bool F10 : 1; // VK_F10, 0x79
bool F11 : 1; // VK_F11, 0x7A
bool F12 : 1; // VK_F12, 0x7B
bool F13 : 1; // VK_F13, 0x7C
bool F14 : 1; // VK_F14, 0x7D
bool F15 : 1; // VK_F15, 0x7E
bool F16 : 1; // VK_F16, 0x7F
bool F17 : 1; // VK_F17, 0x80
bool F18 : 1; // VK_F18, 0x81
bool F19 : 1; // VK_F19, 0x82
bool F20 : 1; // VK_F20, 0x83
bool F21 : 1; // VK_F21, 0x84
bool F22 : 1; // VK_F22, 0x85
bool F23 : 1; // VK_F23, 0x86
bool F24 : 1; // VK_F24, 0x87
bool Reserved11 : 8;
bool NumLock : 1; // VK_NUMLOCK, 0x90
bool Scroll : 1; // VK_SCROLL, 0x91
bool Reserved12 : 6;
bool Reserved13 : 8;
bool LeftShift : 1; // VK_LSHIFT, 0xA0
bool RightShift : 1; // VK_RSHIFT, 0xA1
bool LeftControl : 1; // VK_LCONTROL, 0xA2
bool RightControl : 1; // VK_RCONTROL, 0xA3
bool LeftAlt : 1; // VK_LMENU, 0xA4
bool RightAlt : 1; // VK_RMENU, 0xA5
bool BrowserBack : 1; // VK_BROWSER_BACK, 0xA6
bool BrowserForward : 1; // VK_BROWSER_FORWARD, 0xA7
bool BrowserRefresh : 1; // VK_BROWSER_REFRESH, 0xA8
bool BrowserStop : 1; // VK_BROWSER_STOP, 0xA9
bool BrowserSearch : 1; // VK_BROWSER_SEARCH, 0xAA
bool BrowserFavorites : 1; // VK_BROWSER_FAVORITES, 0xAB
bool BrowserHome : 1; // VK_BROWSER_HOME, 0xAC
bool VolumeMute : 1; // VK_VOLUME_MUTE, 0xAD
bool VolumeDown : 1; // VK_VOLUME_DOWN, 0xAE
bool VolumeUp : 1; // VK_VOLUME_UP, 0xAF
bool MediaNextTrack : 1; // VK_MEDIA_NEXT_TRACK, 0xB0
bool MediaPreviousTrack : 1;// VK_MEDIA_PREV_TRACK, 0xB1
bool MediaStop : 1; // VK_MEDIA_STOP, 0xB2
bool MediaPlayPause : 1; // VK_MEDIA_PLAY_PAUSE, 0xB3
bool LaunchMail : 1; // VK_LAUNCH_MAIL, 0xB4
bool SelectMedia : 1; // VK_LAUNCH_MEDIA_SELECT, 0xB5
bool LaunchApplication1 : 1;// VK_LAUNCH_APP1, 0xB6
bool LaunchApplication2 : 1;// VK_LAUNCH_APP2, 0xB7
bool Reserved14 : 2;
bool OemSemicolon : 1; // VK_OEM_1, 0xBA
bool OemPlus : 1; // VK_OEM_PLUS, 0xBB
bool OemComma : 1; // VK_OEM_COMMA, 0xBC
bool OemMinus : 1; // VK_OEM_MINUS, 0xBD
bool OemPeriod : 1; // VK_OEM_PERIOD, 0xBE
bool OemQuestion : 1; // VK_OEM_2, 0xBF
bool OemTilde : 1; // VK_OEM_3, 0xC0
bool Reserved15 : 7;
bool Reserved16 : 8;
bool Reserved17 : 8;
bool Reserved18 : 3;
bool OemOpenBrackets : 1; // VK_OEM_4, 0xDB
bool OemPipe : 1; // VK_OEM_5, 0xDC
bool OemCloseBrackets : 1; // VK_OEM_6, 0xDD
bool OemQuotes : 1; // VK_OEM_7, 0xDE
bool Oem8 : 1; // VK_OEM_8, 0xDF
bool Reserved19 : 2;
bool OemBackslash : 1; // VK_OEM_102, 0xE2
bool Reserved20 : 2;
bool ProcessKey : 1; // VK_PROCESSKEY, 0xE5
bool Reserved21 : 2;
bool Reserved22 : 8;
bool Reserved23 : 2;
bool OemCopy : 1; // 0XF2
bool OemAuto : 1; // 0xF3
bool OemEnlW : 1; // 0xF4
bool Reserved24 : 1;
bool Attn : 1; // VK_ATTN, 0xF6
bool Crsel : 1; // VK_CRSEL, 0xF7
bool Exsel : 1; // VK_EXSEL, 0xF8
bool EraseEof : 1; // VK_EREOF, 0xF9
bool Play : 1; // VK_PLAY, 0xFA
bool Zoom : 1; // VK_ZOOM, 0xFB
bool Reserved25 : 1;
bool Pa1 : 1; // VK_PA1, 0xFD
bool OemClear : 1; // VK_OEM_CLEAR, 0xFE
bool Reserved26 : 1;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"
#endif
bool __cdecl IsKeyDown(Keys key) const noexcept
{
if (key <= 0xfe)
{
auto ptr = reinterpret_cast<const uint32_t*>(this);
const unsigned int bf = 1u << (key & 0x1f);
return (ptr[(key >> 5)] & bf) != 0;
}
return false;
}
bool __cdecl IsKeyUp(Keys key) const noexcept
{
if (key <= 0xfe)
{
auto ptr = reinterpret_cast<const uint32_t*>(this);
const unsigned int bf = 1u << (key & 0x1f);
return (ptr[(key >> 5)] & bf) == 0;
}
return false;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
};
class KeyboardStateTracker
{
public:
State released;
State pressed;
#ifdef _PREFAST_
#pragma prefast(push)
#pragma prefast(disable : 26495, "Reset() performs the initialization")
#endif
KeyboardStateTracker() noexcept { Reset(); }
#ifdef _PREFAST_
#pragma prefast(pop)
#endif
void __cdecl Update(const State& state) noexcept;
void __cdecl Reset() noexcept;
bool __cdecl IsKeyPressed(Keys key) const noexcept { return pressed.IsKeyDown(key); }
bool __cdecl IsKeyReleased(Keys key) const noexcept { return released.IsKeyDown(key); }
State __cdecl GetLastState() const noexcept { return lastState; }
public:
State lastState;
};
// Retrieve the current state of the keyboard
State __cdecl GetState() const;
// Reset the keyboard state
void __cdecl Reset() noexcept;
// Feature detection
bool __cdecl IsConnected() const;
#ifdef USING_COREWINDOW
void __cdecl SetWindow(ABI::Windows::UI::Core::ICoreWindow* window);
#ifdef __cplusplus_winrt
void __cdecl SetWindow(Windows::UI::Core::CoreWindow^ window)
{
// See https://msdn.microsoft.com/en-us/library/hh755802.aspx
SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window));
}
#endif
#ifdef CPPWINRT_VERSION
void __cdecl SetWindow(winrt::Windows::UI::Core::CoreWindow window)
{
// See https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/interop-winrt-abi
SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(winrt::get_abi(window)));
}
#endif
#elif defined(WM_USER)
static void __cdecl ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam);
#endif
// Singleton
static Keyboard& __cdecl Get();
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif

View File

@@ -0,0 +1,372 @@
//--------------------------------------------------------------------------------------
// File: Model.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#include <dxgiformat.h>
#endif
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <new>
#include <set>
#include <string>
#include <vector>
#include <malloc.h>
#include <wrl\client.h>
#include <DirectXMath.h>
#include <DirectXCollision.h>
namespace DirectX
{
inline namespace DX11
{
class IEffect;
class IEffectFactory;
class CommonStates;
class ModelMesh;
//------------------------------------------------------------------------------
// Model loading options
enum ModelLoaderFlags : uint32_t
{
ModelLoader_Clockwise = 0x0,
ModelLoader_CounterClockwise = 0x1,
ModelLoader_PremultipledAlpha = 0x2,
ModelLoader_MaterialColorsSRGB = 0x4,
ModelLoader_AllowLargeModels = 0x8,
ModelLoader_IncludeBones = 0x10,
ModelLoader_DisableSkinning = 0x20,
};
//------------------------------------------------------------------------------
// Frame hierarchy for rigid body and skeletal animation
struct ModelBone
{
ModelBone() noexcept :
parentIndex(c_Invalid),
childIndex(c_Invalid),
siblingIndex(c_Invalid)
{
}
ModelBone(uint32_t parent, uint32_t child, uint32_t sibling) noexcept :
parentIndex(parent),
childIndex(child),
siblingIndex(sibling)
{
}
uint32_t parentIndex;
uint32_t childIndex;
uint32_t siblingIndex;
std::wstring name;
using Collection = std::vector<ModelBone>;
static constexpr uint32_t c_Invalid = uint32_t(-1);
struct aligned_deleter { void operator()(void* p) noexcept { _aligned_free(p); } };
using TransformArray = std::unique_ptr<XMMATRIX[], aligned_deleter>;
static TransformArray MakeArray(size_t count)
{
void* temp = _aligned_malloc(sizeof(XMMATRIX) * count, 16);
if (!temp)
throw std::bad_alloc();
return TransformArray(static_cast<XMMATRIX*>(temp));
}
};
//------------------------------------------------------------------------------
// Each mesh part is a submesh with a single effect
class ModelMeshPart
{
public:
ModelMeshPart() noexcept;
ModelMeshPart(ModelMeshPart&&) = default;
ModelMeshPart& operator= (ModelMeshPart&&) = default;
ModelMeshPart(ModelMeshPart const&) = default;
ModelMeshPart& operator= (ModelMeshPart const&) = default;
virtual ~ModelMeshPart();
using Collection = std::vector<std::unique_ptr<ModelMeshPart>>;
using InputLayoutCollection = std::vector<D3D11_INPUT_ELEMENT_DESC>;
uint32_t indexCount;
uint32_t startIndex;
int32_t vertexOffset;
uint32_t vertexStride;
D3D_PRIMITIVE_TOPOLOGY primitiveType;
DXGI_FORMAT indexFormat;
Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
Microsoft::WRL::ComPtr<ID3D11Buffer> indexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBuffer;
std::shared_ptr<IEffect> effect;
std::shared_ptr<InputLayoutCollection> vbDecl;
bool isAlpha;
// Draw mesh part with custom effect
void __cdecl Draw(
_In_ ID3D11DeviceContext* deviceContext,
_In_ IEffect* ieffect,
_In_ ID3D11InputLayout* iinputLayout,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
void __cdecl DrawInstanced(
_In_ ID3D11DeviceContext* deviceContext,
_In_ IEffect* ieffect,
_In_ ID3D11InputLayout* iinputLayout,
uint32_t instanceCount,
uint32_t startInstanceLocation = 0,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Create input layout for drawing with a custom effect.
void __cdecl CreateInputLayout(_In_ ID3D11Device* device, _In_ IEffect* ieffect, _Outptr_ ID3D11InputLayout** iinputLayout) const;
// Change effect used by part and regenerate input layout (be sure to call Model::Modified as well)
void __cdecl ModifyEffect(_In_ ID3D11Device* device, _In_ const std::shared_ptr<IEffect>& ieffect, bool isalpha = false);
};
//------------------------------------------------------------------------------
// A mesh consists of one or more model mesh parts
class ModelMesh
{
public:
ModelMesh() noexcept;
ModelMesh(ModelMesh&&) = default;
ModelMesh& operator= (ModelMesh&&) = default;
ModelMesh(ModelMesh const&) = default;
ModelMesh& operator= (ModelMesh const&) = default;
virtual ~ModelMesh();
BoundingSphere boundingSphere;
BoundingBox boundingBox;
ModelMeshPart::Collection meshParts;
uint32_t boneIndex;
std::vector<uint32_t> boneInfluences;
std::wstring name;
bool ccw;
bool pmalpha;
using Collection = std::vector<std::shared_ptr<ModelMesh>>;
// Setup states for drawing mesh
void __cdecl PrepareForRendering(
_In_ ID3D11DeviceContext* deviceContext,
const CommonStates& states,
bool alpha = false,
bool wireframe = false) const;
// Draw the mesh
void XM_CALLCONV Draw(
_In_ ID3D11DeviceContext* deviceContext,
FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection,
bool alpha = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Draw the mesh using model bones
void XM_CALLCONV Draw(
_In_ ID3D11DeviceContext* deviceContext,
size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms,
FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection,
bool alpha = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Draw the mesh using skinning
void XM_CALLCONV DrawSkinned(
_In_ ID3D11DeviceContext* deviceContext,
size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms,
FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection,
bool alpha = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
static void SetDepthBufferMode(bool reverseZ)
{
s_reversez = reverseZ;
}
private:
static bool s_reversez;
};
//------------------------------------------------------------------------------
// A model consists of one or more meshes
class Model
{
public:
Model() = default;
Model(Model&&) = default;
Model& operator= (Model&&) = default;
Model(Model const& other);
Model& operator= (Model const& rhs);
virtual ~Model();
ModelMesh::Collection meshes;
ModelBone::Collection bones;
ModelBone::TransformArray boneMatrices;
ModelBone::TransformArray invBindPoseMatrices;
std::wstring name;
// Draw all the meshes in the model
void XM_CALLCONV Draw(
_In_ ID3D11DeviceContext* deviceContext,
const CommonStates& states,
FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection,
bool wireframe = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Draw all the meshes using model bones
void XM_CALLCONV Draw(
_In_ ID3D11DeviceContext* deviceContext,
const CommonStates& states,
size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms,
FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection,
bool wireframe = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Draw all the meshes using skinning
void XM_CALLCONV DrawSkinned(
_In_ ID3D11DeviceContext* deviceContext,
const CommonStates& states,
size_t nbones, _In_reads_(nbones) const XMMATRIX* boneTransforms,
FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection,
bool wireframe = false,
_In_ std::function<void __cdecl()> setCustomState = nullptr) const;
// Compute bone positions based on heirarchy and transform matrices
void __cdecl CopyAbsoluteBoneTransformsTo(
size_t nbones,
_Out_writes_(nbones) XMMATRIX* boneTransforms) const;
void __cdecl CopyAbsoluteBoneTransforms(
size_t nbones,
_In_reads_(nbones) const XMMATRIX* inBoneTransforms,
_Out_writes_(nbones) XMMATRIX* outBoneTransforms) const;
// Set bone matrices to a set of relative tansforms
void __cdecl CopyBoneTransformsFrom(
size_t nbones,
_In_reads_(nbones) const XMMATRIX* boneTransforms);
// Copies the relative bone matrices to a transform array
void __cdecl CopyBoneTransformsTo(
size_t nbones,
_Out_writes_(nbones) XMMATRIX* boneTransforms) const;
// Notify model that effects, parts list, or mesh list has changed
void __cdecl Modified() noexcept { mEffectCache.clear(); }
// Update all effects used by the model
void __cdecl UpdateEffects(_In_ std::function<void __cdecl(IEffect*)> setEffect);
// Loads a model from a Visual Studio Starter Kit .CMO file
static std::unique_ptr<Model> __cdecl CreateFromCMO(
_In_ ID3D11Device* device,
_In_reads_bytes_(dataSize) const uint8_t* meshData, size_t dataSize,
_In_ IEffectFactory& fxFactory,
ModelLoaderFlags flags = ModelLoader_CounterClockwise,
_Out_opt_ size_t* animsOffset = nullptr);
static std::unique_ptr<Model> __cdecl CreateFromCMO(
_In_ ID3D11Device* device,
_In_z_ const wchar_t* szFileName,
_In_ IEffectFactory& fxFactory,
ModelLoaderFlags flags = ModelLoader_CounterClockwise,
_Out_opt_ size_t* animsOffset = nullptr);
// Loads a model from a DirectX SDK .SDKMESH file
static std::unique_ptr<Model> __cdecl CreateFromSDKMESH(
_In_ ID3D11Device* device,
_In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize,
_In_ IEffectFactory& fxFactory,
ModelLoaderFlags flags = ModelLoader_Clockwise);
static std::unique_ptr<Model> __cdecl CreateFromSDKMESH(
_In_ ID3D11Device* device,
_In_z_ const wchar_t* szFileName,
_In_ IEffectFactory& fxFactory,
ModelLoaderFlags flags = ModelLoader_Clockwise);
// Loads a model from a .VBO file
static std::unique_ptr<Model> __cdecl CreateFromVBO(
_In_ ID3D11Device* device,
_In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize,
_In_ std::shared_ptr<IEffect> ieffect = nullptr,
ModelLoaderFlags flags = ModelLoader_Clockwise);
static std::unique_ptr<Model> __cdecl CreateFromVBO(
_In_ ID3D11Device* device,
_In_z_ const wchar_t* szFileName,
_In_ std::shared_ptr<IEffect> ieffect = nullptr,
ModelLoaderFlags flags = ModelLoader_Clockwise);
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
static std::unique_ptr<Model> __cdecl CreateFromCMO(
_In_ ID3D11Device* device,
_In_z_ const __wchar_t* szFileName,
_In_ IEffectFactory& fxFactory,
ModelLoaderFlags flags = ModelLoader_CounterClockwise,
_Out_opt_ size_t* animsOffset = nullptr);
static std::unique_ptr<Model> __cdecl CreateFromSDKMESH(
_In_ ID3D11Device* device,
_In_z_ const __wchar_t* szFileName,
_In_ IEffectFactory& fxFactory,
ModelLoaderFlags flags = ModelLoader_Clockwise);
static std::unique_ptr<Model> __cdecl CreateFromVBO(
_In_ ID3D11Device* device,
_In_z_ const __wchar_t* szFileName,
_In_ std::shared_ptr<IEffect> ieffect = nullptr,
ModelLoaderFlags flags = ModelLoader_Clockwise);
#endif // !_NATIVE_WCHAR_T_DEFINED
private:
std::set<IEffect*> mEffectCache;
void __cdecl ComputeAbsolute(uint32_t index,
CXMMATRIX local, size_t nbones,
_In_reads_(nbones) const XMMATRIX* inBoneTransforms,
_Inout_updates_(nbones) XMMATRIX* outBoneTransforms,
size_t& visited) const;
};
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#endif
DEFINE_ENUM_FLAG_OPERATORS(ModelLoaderFlags);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
}

View File

@@ -0,0 +1,172 @@
//--------------------------------------------------------------------------------------
// File: Mouse.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#pragma once
#if !defined(USING_XINPUT) && !defined(USING_GAMEINPUT) && !defined(USING_COREWINDOW)
#ifdef _GAMING_DESKTOP
#include <grdk.h>
#endif
#if (defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_GAMES)) || (defined(_GAMING_DESKTOP) && (_GRDK_EDITION >= 220600))
#define USING_GAMEINPUT
#elif (defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)) || (defined(_XBOX_ONE) && defined(_TITLE))
#define USING_COREWINDOW
#endif
#endif // !USING_XINPUT && !USING_GAMEINPUT && !USING_WINDOWS_GAMING_INPUT
#if defined(USING_GAMEINPUT) && !defined(_GAMING_XBOX) && defined(_MSC_VER)
#pragma comment(lib,"gameinput.lib")
#endif
#include <memory>
#ifdef USING_COREWINDOW
namespace ABI { namespace Windows { namespace UI { namespace Core { struct ICoreWindow; } } } }
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#endif
namespace DirectX
{
class Mouse
{
public:
Mouse() noexcept(false);
Mouse(Mouse&&) noexcept;
Mouse& operator= (Mouse&&) noexcept;
Mouse(Mouse const&) = delete;
Mouse& operator=(Mouse const&) = delete;
virtual ~Mouse();
enum Mode
{
MODE_ABSOLUTE = 0,
MODE_RELATIVE,
};
struct State
{
bool leftButton;
bool middleButton;
bool rightButton;
bool xButton1;
bool xButton2;
int x;
int y;
int scrollWheelValue;
Mode positionMode;
};
class ButtonStateTracker
{
public:
enum ButtonState
{
UP = 0, // Button is up
HELD = 1, // Button is held down
RELEASED = 2, // Button was just released
PRESSED = 3, // Buton was just pressed
};
ButtonState leftButton;
ButtonState middleButton;
ButtonState rightButton;
ButtonState xButton1;
ButtonState xButton2;
#ifdef _PREFAST_
#pragma prefast(push)
#pragma prefast(disable : 26495, "Reset() performs the initialization")
#endif
ButtonStateTracker() noexcept { Reset(); }
#ifdef _PREFAST_
#pragma prefast(pop)
#endif
void __cdecl Update(const State& state) noexcept;
void __cdecl Reset() noexcept;
State __cdecl GetLastState() const noexcept { return lastState; }
private:
State lastState;
};
// Retrieve the current state of the mouse
State __cdecl GetState() const;
// Resets the accumulated scroll wheel value
void __cdecl ResetScrollWheelValue() noexcept;
// Sets mouse mode (defaults to absolute)
void __cdecl SetMode(Mode mode);
// Signals the end of frame (recommended, but optional)
void __cdecl EndOfInputFrame() noexcept;
// Feature detection
bool __cdecl IsConnected() const;
// Cursor visibility
bool __cdecl IsVisible() const noexcept;
void __cdecl SetVisible(bool visible);
#ifdef USING_COREWINDOW
void __cdecl SetWindow(ABI::Windows::UI::Core::ICoreWindow* window);
#ifdef __cplusplus_winrt
void __cdecl SetWindow(Windows::UI::Core::CoreWindow^ window)
{
// See https://msdn.microsoft.com/en-us/library/hh755802.aspx
SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window));
}
#endif
#ifdef CPPWINRT_VERSION
void __cdecl SetWindow(winrt::Windows::UI::Core::CoreWindow window)
{
// See https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/interop-winrt-abi
SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(winrt::get_abi(window)));
}
#endif
static void __cdecl SetDpi(float dpi);
#elif defined(WM_USER)
void __cdecl SetWindow(HWND window);
static void __cdecl ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam);
#ifdef _GAMING_XBOX
static void __cdecl SetResolution(float scale);
#endif
#endif
// Singleton
static Mouse& __cdecl Get();
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif

View File

@@ -0,0 +1,227 @@
//--------------------------------------------------------------------------------------
// File: PostProcess.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <memory>
#include <functional>
#include <DirectXMath.h>
namespace DirectX
{
inline namespace DX11
{
//------------------------------------------------------------------------------
// Abstract interface representing a post-process pass
class IPostProcess
{
public:
virtual ~IPostProcess() = default;
IPostProcess(const IPostProcess&) = delete;
IPostProcess& operator=(const IPostProcess&) = delete;
virtual void __cdecl Process(_In_ ID3D11DeviceContext* deviceContext,
_In_ std::function<void __cdecl()> setCustomState = nullptr) = 0;
protected:
IPostProcess() = default;
IPostProcess(IPostProcess&&) = default;
IPostProcess& operator=(IPostProcess&&) = default;
};
//------------------------------------------------------------------------------
// Basic post-process
class BasicPostProcess : public IPostProcess
{
public:
enum Effect : unsigned int
{
Copy,
Monochrome,
Sepia,
DownScale_2x2,
DownScale_4x4,
GaussianBlur_5x5,
BloomExtract,
BloomBlur,
Effect_Max
};
explicit BasicPostProcess(_In_ ID3D11Device* device);
BasicPostProcess(BasicPostProcess&&) noexcept;
BasicPostProcess& operator= (BasicPostProcess&&) noexcept;
BasicPostProcess(BasicPostProcess const&) = delete;
BasicPostProcess& operator= (BasicPostProcess const&) = delete;
~BasicPostProcess() override;
// IPostProcess methods.
void __cdecl Process(
_In_ ID3D11DeviceContext* deviceContext,
_In_ std::function<void __cdecl()> setCustomState = nullptr) override;
// Shader control
void __cdecl SetEffect(Effect fx);
// Properties
void __cdecl SetSourceTexture(_In_opt_ ID3D11ShaderResourceView* value);
// Sets multiplier for GaussianBlur_5x5
void __cdecl SetGaussianParameter(float multiplier);
// Sets parameters for BloomExtract
void __cdecl SetBloomExtractParameter(float threshold);
// Sets parameters for BloomBlur
void __cdecl SetBloomBlurParameters(bool horizontal, float size, float brightness);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//------------------------------------------------------------------------------
// Dual-texure post-process
class DualPostProcess : public IPostProcess
{
public:
enum Effect : unsigned int
{
Merge,
BloomCombine,
Effect_Max
};
explicit DualPostProcess(_In_ ID3D11Device* device);
DualPostProcess(DualPostProcess&&) noexcept;
DualPostProcess& operator= (DualPostProcess&&) noexcept;
DualPostProcess(DualPostProcess const&) = delete;
DualPostProcess& operator= (DualPostProcess const&) = delete;
~DualPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D11DeviceContext* deviceContext,
_In_ std::function<void __cdecl()> setCustomState = nullptr) override;
// Shader control
void __cdecl SetEffect(Effect fx);
// Properties
void __cdecl SetSourceTexture(_In_opt_ ID3D11ShaderResourceView* value);
void __cdecl SetSourceTexture2(_In_opt_ ID3D11ShaderResourceView* value);
// Sets parameters for Merge
void __cdecl SetMergeParameters(float weight1, float weight2);
// Sets parameters for BloomCombine
void __cdecl SetBloomCombineParameters(float bloom, float base, float bloomSaturation, float baseSaturation);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//------------------------------------------------------------------------------
// Tone-map post-process
class ToneMapPostProcess : public IPostProcess
{
public:
// Tone-mapping operator
enum Operator : unsigned int
{
None, // Pass-through
Saturate, // Clamp [0,1]
Reinhard, // x/(1+x)
ACESFilmic,
Operator_Max
};
// Electro-Optical Transfer Function (EOTF)
enum TransferFunction : unsigned int
{
Linear, // Pass-through
SRGB, // sRGB (Rec.709 and approximate sRGB display curve)
ST2084, // HDR10 (Rec.2020 color primaries and ST.2084 display curve)
TransferFunction_Max
};
// Color Rotation Transform for HDR10
enum ColorPrimaryRotation : unsigned int
{
HDTV_to_UHDTV, // Rec.709 to Rec.2020
DCI_P3_D65_to_UHDTV, // DCI-P3-D65 (a.k.a Display P3 or P3D65) to Rec.2020
HDTV_to_DCI_P3_D65, // Rec.709 to DCI-P3-D65 (a.k.a Display P3 or P3D65)
};
explicit ToneMapPostProcess(_In_ ID3D11Device* device);
ToneMapPostProcess(ToneMapPostProcess&&) noexcept;
ToneMapPostProcess& operator= (ToneMapPostProcess&&) noexcept;
ToneMapPostProcess(ToneMapPostProcess const&) = delete;
ToneMapPostProcess& operator= (ToneMapPostProcess const&) = delete;
~ToneMapPostProcess() override;
// IPostProcess methods.
void __cdecl Process(_In_ ID3D11DeviceContext* deviceContext,
_In_ std::function<void __cdecl()> setCustomState = nullptr) override;
// Shader control
void __cdecl SetOperator(Operator op);
void __cdecl SetTransferFunction(TransferFunction func);
#if defined(_XBOX_ONE) && defined(_TITLE)
// Uses Multiple Render Targets to generate both HDR10 and GameDVR SDR signals
void __cdecl SetMRTOutput(bool value = true);
#endif
// Properties
void __cdecl SetHDRSourceTexture(_In_opt_ ID3D11ShaderResourceView* value);
// Sets the Color Rotation Transform for HDR10 signal output
void __cdecl SetColorRotation(ColorPrimaryRotation value);
void __cdecl SetColorRotation(CXMMATRIX value);
// Sets exposure value for LDR tonemap operators
void __cdecl SetExposure(float exposureValue);
// Sets ST.2084 parameter for how bright white should be in nits
void __cdecl SetST2084Parameter(float paperWhiteNits);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
}

View File

@@ -0,0 +1,140 @@
//--------------------------------------------------------------------------------------
// File: PrimitiveBatch.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <utility>
namespace DirectX
{
inline namespace DX11
{
namespace Private
{
// Base class, not to be used directly: clients should access this via the derived PrimitiveBatch<T>.
class PrimitiveBatchBase
{
protected:
PrimitiveBatchBase(_In_ ID3D11DeviceContext* deviceContext, size_t maxIndices, size_t maxVertices, size_t vertexSize);
PrimitiveBatchBase(PrimitiveBatchBase&&) noexcept;
PrimitiveBatchBase& operator= (PrimitiveBatchBase&&) noexcept;
PrimitiveBatchBase(PrimitiveBatchBase const&) = delete;
PrimitiveBatchBase& operator= (PrimitiveBatchBase const&) = delete;
virtual ~PrimitiveBatchBase();
public:
// Begin/End a batch of primitive drawing operations.
void __cdecl Begin();
void __cdecl End();
protected:
// Internal, untyped drawing method.
void __cdecl Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIndexed, _In_opt_count_(indexCount) uint16_t const* indices, size_t indexCount, size_t vertexCount, _Out_ void** pMappedVertices);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
}
// Template makes the API typesafe, eg. PrimitiveBatch<VertexPositionColor>.
template<typename TVertex>
class PrimitiveBatch : public Private::PrimitiveBatchBase
{
static constexpr size_t DefaultBatchSize = 2048;
public:
explicit PrimitiveBatch(_In_ ID3D11DeviceContext* deviceContext, size_t maxIndices = DefaultBatchSize * 3, size_t maxVertices = DefaultBatchSize)
: PrimitiveBatchBase(deviceContext, maxIndices, maxVertices, sizeof(TVertex))
{
}
PrimitiveBatch(PrimitiveBatch&&) = default;
PrimitiveBatch& operator= (PrimitiveBatch&&) = default;
PrimitiveBatch(PrimitiveBatch const&) = delete;
PrimitiveBatch& operator= (PrimitiveBatch const&) = delete;
// Similar to the D3D9 API DrawPrimitiveUP.
void Draw(D3D11_PRIMITIVE_TOPOLOGY topology, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount)
{
void* mappedVertices;
PrimitiveBatchBase::Draw(topology, false, nullptr, 0, vertexCount, &mappedVertices);
memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex));
}
// Similar to the D3D9 API DrawIndexedPrimitiveUP.
void DrawIndexed(D3D11_PRIMITIVE_TOPOLOGY topology, _In_reads_(indexCount) uint16_t const* indices, size_t indexCount, _In_reads_(vertexCount) TVertex const* vertices, size_t vertexCount)
{
void* mappedVertices;
PrimitiveBatchBase::Draw(topology, true, indices, indexCount, vertexCount, &mappedVertices);
memcpy(mappedVertices, vertices, vertexCount * sizeof(TVertex));
}
void DrawLine(TVertex const& v1, TVertex const& v2)
{
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D11_PRIMITIVE_TOPOLOGY_LINELIST, false, nullptr, 0, 2, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
}
void DrawTriangle(TVertex const& v1, TVertex const& v2, TVertex const& v3)
{
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, false, nullptr, 0, 3, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
mappedVertices[2] = v3;
}
void DrawQuad(TVertex const& v1, TVertex const& v2, TVertex const& v3, TVertex const& v4)
{
static const uint16_t quadIndices[] = { 0, 1, 2, 0, 2, 3 };
TVertex* mappedVertices;
PrimitiveBatchBase::Draw(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, true, quadIndices, 6, 4, reinterpret_cast<void**>(&mappedVertices));
mappedVertices[0] = v1;
mappedVertices[1] = v2;
mappedVertices[2] = v3;
mappedVertices[3] = v4;
}
};
}
}

View File

@@ -0,0 +1,54 @@
//--------------------------------------------------------------------------------------
// File: ScreenGrab.h
//
// Function for capturing a 2D texture and saving it to a file (aka a 'screenshot'
// when used on a Direct3D Render Target).
//
// Note these functions are useful as a light-weight runtime screen grabber. For
// full-featured texture capture, DDS writer, and texture processing pipeline,
// see the 'Texconv' sample and the 'DirectXTex' library.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <functional>
#if defined(NTDDI_WIN10_FE) || defined(__MINGW32__)
#include <ocidl.h>
#else
#include <OCIdl.h>
#endif
#ifdef _MSC_VER
#pragma comment(lib,"uuid.lib")
#endif
namespace DirectX
{
HRESULT __cdecl SaveDDSTextureToFile(
_In_ ID3D11DeviceContext* pContext,
_In_ ID3D11Resource* pSource,
_In_z_ const wchar_t* fileName) noexcept;
HRESULT __cdecl SaveWICTextureToFile(
_In_ ID3D11DeviceContext* pContext,
_In_ ID3D11Resource* pSource,
_In_ REFGUID guidContainerFormat,
_In_z_ const wchar_t* fileName,
_In_opt_ const GUID* targetFormat = nullptr,
_In_ std::function<void __cdecl(IPropertyBag2*)> setCustomProps = nullptr,
_In_ bool forceSRGB = false);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,102 @@
//--------------------------------------------------------------------------------------
// File: SpriteBatch.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#include <dxgi1_2.h>
#endif
#include <cstdint>
#include <functional>
#include <memory>
#include <DirectXMath.h>
#include <DirectXColors.h>
namespace DirectX
{
inline namespace DX11
{
enum SpriteSortMode
{
SpriteSortMode_Deferred,
SpriteSortMode_Immediate,
SpriteSortMode_Texture,
SpriteSortMode_BackToFront,
SpriteSortMode_FrontToBack,
};
enum SpriteEffects : uint32_t
{
SpriteEffects_None = 0,
SpriteEffects_FlipHorizontally = 1,
SpriteEffects_FlipVertically = 2,
SpriteEffects_FlipBoth = SpriteEffects_FlipHorizontally | SpriteEffects_FlipVertically,
};
class SpriteBatch
{
public:
explicit SpriteBatch(_In_ ID3D11DeviceContext* deviceContext);
SpriteBatch(SpriteBatch&&) noexcept;
SpriteBatch& operator= (SpriteBatch&&) noexcept;
SpriteBatch(SpriteBatch const&) = delete;
SpriteBatch& operator= (SpriteBatch const&) = delete;
virtual ~SpriteBatch();
// Begin/End a batch of sprite drawing operations.
void XM_CALLCONV Begin(SpriteSortMode sortMode = SpriteSortMode_Deferred,
_In_opt_ ID3D11BlendState* blendState = nullptr,
_In_opt_ ID3D11SamplerState* samplerState = nullptr,
_In_opt_ ID3D11DepthStencilState* depthStencilState = nullptr,
_In_opt_ ID3D11RasterizerState* rasterizerState = nullptr,
_In_ std::function<void __cdecl()> setCustomShaders = nullptr,
FXMMATRIX transformMatrix = MatrixIdentity);
void __cdecl End();
// Draw overloads specifying position, origin and scale as XMFLOAT2.
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, XMFLOAT2 const& position, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, XMFLOAT2 const& position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
// Draw overloads specifying position, origin and scale via the first two components of an XMVECTOR.
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, FXMVECTOR position, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, FXMVECTOR position, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
// Draw overloads specifying position as a RECT.
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, RECT const& destinationRectangle, FXMVECTOR color = Colors::White);
void XM_CALLCONV Draw(_In_ ID3D11ShaderResourceView* texture, RECT const& destinationRectangle, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0);
// Rotation mode to be applied to the sprite transformation
void __cdecl SetRotation(DXGI_MODE_ROTATION mode);
DXGI_MODE_ROTATION __cdecl GetRotation() const noexcept;
// Set viewport for sprite transformation
void __cdecl SetViewport(const D3D11_VIEWPORT& viewPort);
private:
// Private implementation.
struct Impl;
std::unique_ptr<Impl> pImpl;
static const XMMATRIX MatrixIdentity;
static const XMFLOAT2 Float2Zero;
};
}
}

View File

@@ -0,0 +1,116 @@
//--------------------------------------------------------------------------------------
// File: SpriteFont.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include "SpriteBatch.h"
#include <cstddef>
#include <cstdint>
#include <memory>
namespace DirectX
{
inline namespace DX11
{
class SpriteFont
{
public:
struct Glyph;
SpriteFont(_In_ ID3D11Device* device, _In_z_ wchar_t const* fileName, bool forceSRGB = false);
SpriteFont(_In_ ID3D11Device* device, _In_reads_bytes_(dataSize) uint8_t const* dataBlob, _In_ size_t dataSize, bool forceSRGB = false);
SpriteFont(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, _In_ float lineSpacing);
SpriteFont(SpriteFont&&) noexcept;
SpriteFont& operator= (SpriteFont&&) noexcept;
SpriteFont(SpriteFont const&) = delete;
SpriteFont& operator= (SpriteFont const&) = delete;
virtual ~SpriteFont();
// Wide-character / UTF-16LE
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
XMVECTOR XM_CALLCONV MeasureString(_In_z_ wchar_t const* text, bool ignoreWhitespace = true) const;
RECT __cdecl MeasureDrawBounds(_In_z_ wchar_t const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const;
RECT XM_CALLCONV MeasureDrawBounds(_In_z_ wchar_t const* text, FXMVECTOR position, bool ignoreWhitespace = true) const;
// UTF-8
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ char const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
XMVECTOR XM_CALLCONV MeasureString(_In_z_ char const* text, bool ignoreWhitespace = true) const;
RECT __cdecl MeasureDrawBounds(_In_z_ char const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const;
RECT XM_CALLCONV MeasureDrawBounds(_In_z_ char const* text, FXMVECTOR position, bool ignoreWhitespace = true) const;
// Spacing properties
float __cdecl GetLineSpacing() const noexcept;
void __cdecl SetLineSpacing(float spacing);
// Font properties
wchar_t __cdecl GetDefaultCharacter() const noexcept;
void __cdecl SetDefaultCharacter(wchar_t character);
bool __cdecl ContainsCharacter(wchar_t character) const;
// Custom layout/rendering
Glyph const* __cdecl FindGlyph(wchar_t character) const;
void __cdecl GetSpriteSheet(ID3D11ShaderResourceView** texture) const;
// Describes a single character glyph.
struct Glyph
{
uint32_t Character;
RECT Subrect;
float XOffset;
float YOffset;
float XAdvance;
};
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
SpriteFont(_In_ ID3D11Device* device, _In_z_ __wchar_t const* fileName, bool forceSRGB = false);
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, FXMVECTOR position, FXMVECTOR color = Colors::White, float rotation = 0, FXMVECTOR origin = g_XMZero, float scale = 1, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
void XM_CALLCONV DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ __wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0) const;
XMVECTOR XM_CALLCONV MeasureString(_In_z_ __wchar_t const* text, bool ignoreWhitespace = true) const;
RECT __cdecl MeasureDrawBounds(_In_z_ __wchar_t const* text, XMFLOAT2 const& position, bool ignoreWhitespace = true) const;
RECT XM_CALLCONV MeasureDrawBounds(_In_z_ __wchar_t const* text, FXMVECTOR position, bool ignoreWhitespace = true) const;
void __cdecl SetDefaultCharacter(__wchar_t character);
bool __cdecl ContainsCharacter(__wchar_t character) const;
Glyph const* __cdecl FindGlyph(__wchar_t character) const;
#endif // !_NATIVE_WCHAR_T_DEFINED
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
static const XMFLOAT2 Float2Zero;
};
}
}

View File

@@ -0,0 +1,504 @@
//--------------------------------------------------------------------------------------
// File: VertexTypes.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <cstdint>
#include <DirectXMath.h>
namespace DirectX
{
inline namespace DX11
{
// Vertex struct holding position information.
struct VertexPosition
{
VertexPosition() = default;
VertexPosition(const VertexPosition&) = default;
VertexPosition& operator=(const VertexPosition&) = default;
VertexPosition(VertexPosition&&) = default;
VertexPosition& operator=(VertexPosition&&) = default;
VertexPosition(XMFLOAT3 const& iposition) noexcept
: position(iposition)
{
}
VertexPosition(FXMVECTOR iposition) noexcept
{
XMStoreFloat3(&this->position, iposition);
}
XMFLOAT3 position;
static constexpr unsigned int InputElementCount = 1;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and color information.
struct VertexPositionColor
{
VertexPositionColor() = default;
VertexPositionColor(const VertexPositionColor&) = default;
VertexPositionColor& operator=(const VertexPositionColor&) = default;
VertexPositionColor(VertexPositionColor&&) = default;
VertexPositionColor& operator=(VertexPositionColor&&) = default;
VertexPositionColor(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor) noexcept
: position(iposition),
color(icolor)
{
}
VertexPositionColor(FXMVECTOR iposition, FXMVECTOR icolor) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat4(&this->color, icolor);
}
XMFLOAT3 position;
XMFLOAT4 color;
static constexpr unsigned int InputElementCount = 2;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and texture mapping information.
struct VertexPositionTexture
{
VertexPositionTexture() = default;
VertexPositionTexture(const VertexPositionTexture&) = default;
VertexPositionTexture& operator=(const VertexPositionTexture&) = default;
VertexPositionTexture(VertexPositionTexture&&) = default;
VertexPositionTexture& operator=(VertexPositionTexture&&) = default;
VertexPositionTexture(XMFLOAT3 const& iposition, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionTexture(FXMVECTOR iposition, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT2 textureCoordinate;
static constexpr unsigned int InputElementCount = 2;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and dual texture mapping information.
struct VertexPositionDualTexture
{
VertexPositionDualTexture() = default;
VertexPositionDualTexture(const VertexPositionDualTexture&) = default;
VertexPositionDualTexture& operator=(const VertexPositionDualTexture&) = default;
VertexPositionDualTexture(VertexPositionDualTexture&&) = default;
VertexPositionDualTexture& operator=(VertexPositionDualTexture&&) = default;
VertexPositionDualTexture(
XMFLOAT3 const& iposition,
XMFLOAT2 const& itextureCoordinate0,
XMFLOAT2 const& itextureCoordinate1) noexcept
: position(iposition),
textureCoordinate0(itextureCoordinate0),
textureCoordinate1(itextureCoordinate1)
{
}
VertexPositionDualTexture(
FXMVECTOR iposition,
FXMVECTOR itextureCoordinate0,
FXMVECTOR itextureCoordinate1) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat2(&this->textureCoordinate0, itextureCoordinate0);
XMStoreFloat2(&this->textureCoordinate1, itextureCoordinate1);
}
XMFLOAT3 position;
XMFLOAT2 textureCoordinate0;
XMFLOAT2 textureCoordinate1;
static constexpr unsigned int InputElementCount = 3;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position and normal vector.
struct VertexPositionNormal
{
VertexPositionNormal() = default;
VertexPositionNormal(const VertexPositionNormal&) = default;
VertexPositionNormal& operator=(const VertexPositionNormal&) = default;
VertexPositionNormal(VertexPositionNormal&&) = default;
VertexPositionNormal& operator=(VertexPositionNormal&&) = default;
VertexPositionNormal(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal) noexcept
: position(iposition),
normal(inormal)
{
}
VertexPositionNormal(FXMVECTOR iposition, FXMVECTOR inormal) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
}
XMFLOAT3 position;
XMFLOAT3 normal;
static constexpr unsigned int InputElementCount = 2;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, color, and texture mapping information.
struct VertexPositionColorTexture
{
VertexPositionColorTexture() = default;
VertexPositionColorTexture(const VertexPositionColorTexture&) = default;
VertexPositionColorTexture& operator=(const VertexPositionColorTexture&) = default;
VertexPositionColorTexture(VertexPositionColorTexture&&) = default;
VertexPositionColorTexture& operator=(VertexPositionColorTexture&&) = default;
VertexPositionColorTexture(XMFLOAT3 const& iposition, XMFLOAT4 const& icolor, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
color(icolor),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionColorTexture(FXMVECTOR iposition, FXMVECTOR icolor, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat4(&this->color, icolor);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT4 color;
XMFLOAT2 textureCoordinate;
static constexpr unsigned int InputElementCount = 3;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, normal vector, and color information.
struct VertexPositionNormalColor
{
VertexPositionNormalColor() = default;
VertexPositionNormalColor(const VertexPositionNormalColor&) = default;
VertexPositionNormalColor& operator=(const VertexPositionNormalColor&) = default;
VertexPositionNormalColor(VertexPositionNormalColor&&) = default;
VertexPositionNormalColor& operator=(VertexPositionNormalColor&&) = default;
VertexPositionNormalColor(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT4 const& icolor) noexcept
: position(iposition),
normal(inormal),
color(icolor)
{
}
VertexPositionNormalColor(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->color, icolor);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT4 color;
static constexpr unsigned int InputElementCount = 3;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, normal vector, and texture mapping information.
struct VertexPositionNormalTexture
{
VertexPositionNormalTexture() = default;
VertexPositionNormalTexture(const VertexPositionNormalTexture&) = default;
VertexPositionNormalTexture& operator=(const VertexPositionNormalTexture&) = default;
VertexPositionNormalTexture(VertexPositionNormalTexture&&) = default;
VertexPositionNormalTexture& operator=(VertexPositionNormalTexture&&) = default;
VertexPositionNormalTexture(XMFLOAT3 const& iposition, XMFLOAT3 const& inormal, XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionNormalTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT2 textureCoordinate;
static constexpr unsigned int InputElementCount = 3;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct holding position, normal vector, color, and texture mapping information.
struct VertexPositionNormalColorTexture
{
VertexPositionNormalColorTexture() = default;
VertexPositionNormalColorTexture(const VertexPositionNormalColorTexture&) = default;
VertexPositionNormalColorTexture& operator=(const VertexPositionNormalColorTexture&) = default;
VertexPositionNormalColorTexture(VertexPositionNormalColorTexture&&) = default;
VertexPositionNormalColorTexture& operator=(VertexPositionNormalColorTexture&&) = default;
VertexPositionNormalColorTexture(
XMFLOAT3 const& iposition,
XMFLOAT3 const& inormal,
XMFLOAT4 const& icolor,
XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
color(icolor),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionNormalColorTexture(FXMVECTOR iposition, FXMVECTOR inormal, FXMVECTOR icolor, CXMVECTOR itextureCoordinate) noexcept
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->color, icolor);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT4 color;
XMFLOAT2 textureCoordinate;
static constexpr unsigned int InputElementCount = 4;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct for Visual Studio Shader Designer (DGSL) holding position, normal,
// tangent, color (RGBA), and texture mapping information
struct VertexPositionNormalTangentColorTexture
{
VertexPositionNormalTangentColorTexture() = default;
VertexPositionNormalTangentColorTexture(const VertexPositionNormalTangentColorTexture&) = default;
VertexPositionNormalTangentColorTexture& operator=(const VertexPositionNormalTangentColorTexture&) = default;
VertexPositionNormalTangentColorTexture(VertexPositionNormalTangentColorTexture&&) = default;
VertexPositionNormalTangentColorTexture& operator=(VertexPositionNormalTangentColorTexture&&) = default;
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT4 tangent;
uint32_t color;
XMFLOAT2 textureCoordinate;
VertexPositionNormalTangentColorTexture(
XMFLOAT3 const& iposition,
XMFLOAT3 const& inormal,
XMFLOAT4 const& itangent,
uint32_t irgba,
XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
tangent(itangent),
color(irgba),
textureCoordinate(itextureCoordinate)
{
}
VertexPositionNormalTangentColorTexture(
FXMVECTOR iposition,
FXMVECTOR inormal,
FXMVECTOR itangent,
uint32_t irgba,
CXMVECTOR itextureCoordinate) noexcept
: color(irgba)
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->tangent, itangent);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
}
VertexPositionNormalTangentColorTexture(
XMFLOAT3 const& iposition,
XMFLOAT3 const& inormal,
XMFLOAT4 const& itangent,
XMFLOAT4 const& icolor,
XMFLOAT2 const& itextureCoordinate) noexcept
: position(iposition),
normal(inormal),
tangent(itangent),
color{},
textureCoordinate(itextureCoordinate)
{
SetColor(icolor);
}
VertexPositionNormalTangentColorTexture(
FXMVECTOR iposition,
FXMVECTOR inormal,
FXMVECTOR itangent,
CXMVECTOR icolor,
CXMVECTOR itextureCoordinate) noexcept
: color{}
{
XMStoreFloat3(&this->position, iposition);
XMStoreFloat3(&this->normal, inormal);
XMStoreFloat4(&this->tangent, itangent);
XMStoreFloat2(&this->textureCoordinate, itextureCoordinate);
SetColor(icolor);
}
void __cdecl SetColor(XMFLOAT4 const& icolor) noexcept { SetColor(XMLoadFloat4(&icolor)); }
void XM_CALLCONV SetColor(FXMVECTOR icolor) noexcept;
static constexpr unsigned int InputElementCount = 5;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
// Vertex struct for Visual Studio Shader Designer (DGSL) holding position, normal,
// tangent, color (RGBA), texture mapping information, and skinning weights
struct VertexPositionNormalTangentColorTextureSkinning : public VertexPositionNormalTangentColorTexture
{
VertexPositionNormalTangentColorTextureSkinning() = default;
VertexPositionNormalTangentColorTextureSkinning(const VertexPositionNormalTangentColorTextureSkinning&) = default;
VertexPositionNormalTangentColorTextureSkinning& operator=(const VertexPositionNormalTangentColorTextureSkinning&) = default;
VertexPositionNormalTangentColorTextureSkinning(VertexPositionNormalTangentColorTextureSkinning&&) = default;
VertexPositionNormalTangentColorTextureSkinning& operator=(VertexPositionNormalTangentColorTextureSkinning&&) = default;
uint32_t indices;
uint32_t weights;
VertexPositionNormalTangentColorTextureSkinning(
XMFLOAT3 const& iposition,
XMFLOAT3 const& inormal,
XMFLOAT4 const& itangent,
uint32_t irgba,
XMFLOAT2 const& itextureCoordinate,
XMUINT4 const& iindices,
XMFLOAT4 const& iweights) noexcept
: VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, irgba, itextureCoordinate),
indices{},
weights{}
{
SetBlendIndices(iindices);
SetBlendWeights(iweights);
}
VertexPositionNormalTangentColorTextureSkinning(
FXMVECTOR iposition,
FXMVECTOR inormal,
FXMVECTOR itangent,
uint32_t irgba,
CXMVECTOR itextureCoordinate,
XMUINT4 const& iindices,
CXMVECTOR iweights) noexcept
: VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, irgba, itextureCoordinate),
indices{},
weights{}
{
SetBlendIndices(iindices);
SetBlendWeights(iweights);
}
VertexPositionNormalTangentColorTextureSkinning(
XMFLOAT3 const& iposition,
XMFLOAT3 const& inormal,
XMFLOAT4 const& itangent,
XMFLOAT4 const& icolor,
XMFLOAT2 const& itextureCoordinate,
XMUINT4 const& iindices,
XMFLOAT4 const& iweights) noexcept
: VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, icolor, itextureCoordinate),
indices{},
weights{}
{
SetBlendIndices(iindices);
SetBlendWeights(iweights);
}
VertexPositionNormalTangentColorTextureSkinning(
FXMVECTOR iposition,
FXMVECTOR inormal,
FXMVECTOR itangent,
CXMVECTOR icolor,
CXMVECTOR itextureCoordinate,
XMUINT4 const& iindices,
CXMVECTOR iweights) noexcept
: VertexPositionNormalTangentColorTexture(iposition, inormal, itangent, icolor, itextureCoordinate),
indices{},
weights{}
{
SetBlendIndices(iindices);
SetBlendWeights(iweights);
}
void __cdecl SetBlendIndices(XMUINT4 const& iindices) noexcept;
void __cdecl SetBlendWeights(XMFLOAT4 const& iweights) noexcept { SetBlendWeights(XMLoadFloat4(&iweights)); }
void XM_CALLCONV SetBlendWeights(FXMVECTOR iweights) noexcept;
static constexpr unsigned int InputElementCount = 7;
static const D3D11_INPUT_ELEMENT_DESC InputElements[InputElementCount];
};
}
}

View File

@@ -0,0 +1,177 @@
//--------------------------------------------------------------------------------------
// File: WICTextureLoader.h
//
// Function for loading a WIC image and creating a Direct3D runtime texture for it
// (auto-generating mipmaps if possible)
//
// Note: Assumes application has already called CoInitializeEx
//
// Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for
// auto-gen mipmap support.
//
// Note these functions are useful for images created as simple 2D textures. For
// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader.
// For a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' library.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <cstddef>
#include <cstdint>
#ifdef _MSC_VER
#pragma comment(lib,"uuid.lib")
#endif
namespace DirectX
{
inline namespace DX11
{
enum WIC_LOADER_FLAGS : uint32_t
{
WIC_LOADER_DEFAULT = 0,
WIC_LOADER_FORCE_SRGB = 0x1,
WIC_LOADER_IGNORE_SRGB = 0x2,
WIC_LOADER_SRGB_DEFAULT = 0x4,
WIC_LOADER_FIT_POW2 = 0x20,
WIC_LOADER_MAKE_SQUARE = 0x40,
WIC_LOADER_FORCE_RGBA32 = 0x80,
};
}
// Standard version
HRESULT __cdecl CreateWICTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
HRESULT __cdecl CreateWICTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
// Standard version with optional auto-gen mipmap support
HRESULT __cdecl CreateWICTextureFromMemory(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
HRESULT __cdecl CreateWICTextureFromFile(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
// Extended version
HRESULT __cdecl CreateWICTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
HRESULT __cdecl CreateWICTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
// Extended version with optional auto-gen mipmap support
HRESULT __cdecl CreateWICTextureFromMemoryEx(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
HRESULT __cdecl CreateWICTextureFromFileEx(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#endif
inline namespace DX11
{
DEFINE_ENUM_FLAG_OPERATORS(WIC_LOADER_FLAGS);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}

View File

@@ -0,0 +1,67 @@
//--------------------------------------------------------------------------------------
// File: XboxDDSTextureLoader.h
//
// Functions for loading a DDS texture using the XBOX extended header and creating a
// Direct3D11.X runtime resource for it via the CreatePlacement APIs
//
// Note these functions will not load standard DDS files. Use the DDSTextureLoader
// module in the DirectXTex package or as part of the DirectXTK library to load
// these files which use standard Direct3D resource creation APIs.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if !defined(_XBOX_ONE) || !defined(_TITLE)
#error This module only supports Xbox One exclusive apps
#endif
#include <d3d11_x.h>
#include <cstddef>
#include <cstdint>
#ifndef DDS_ALPHA_MODE_DEFINED
#define DDS_ALPHA_MODE_DEFINED
namespace DirectX
{
enum DDS_ALPHA_MODE : uint32_t
{
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,
};
}
#endif
namespace Xbox
{
using DirectX::DDS_ALPHA_MODE;
HRESULT __cdecl CreateDDSTextureFromMemory(
_In_ ID3D11DeviceX* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Outptr_ void** grfxMemory,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr,
_In_ bool forceSRGB = false) noexcept;
HRESULT __cdecl CreateDDSTextureFromFile( _In_ ID3D11DeviceX* d3dDevice,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Outptr_ void** grfxMemory,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr,
_In_ bool forceSRGB = false) noexcept;
void FreeDDSTextureMemory( _In_opt_ void* grfxMemory ) noexcept;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 MiB

View File

@@ -5,7 +5,6 @@ ModelClass::ModelClass()
{ {
m_vertexBuffer = 0; m_vertexBuffer = 0;
m_indexBuffer = 0; m_indexBuffer = 0;
m_Textures = 0;
m_model = 0; m_model = 0;
} }
@@ -19,16 +18,14 @@ ModelClass::~ModelClass()
{ {
} }
bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* modelFilename, vector<string> filename) bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* modelFilename, std::vector<ID3D11ShaderResourceView*> textures) {
{ Logger::Get().Log("Initializing model class with preloaded textures", __FILE__, __LINE__, Logger::LogLevel::Initialize);
Logger::Get().Log("Initializing model class", __FILE__, __LINE__, Logger::LogLevel::Initialize);
bool result; bool result;
// Load in the model data. // Load in the model data.
result = LoadModel(modelFilename); result = LoadModel(modelFilename);
if (!result) if (!result) {
{
Logger::Get().Log("Failed to load model data", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Failed to load model data", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
} }
@@ -38,20 +35,14 @@ bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceCon
// Initialize the vertex and index buffers. // Initialize the vertex and index buffers.
result = InitializeBuffers(device); result = InitializeBuffers(device);
if (!result) if (!result) {
{
Logger::Get().Log("Failed to initialize buffers", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Failed to initialize buffers", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
} }
// Load the textures for this model.
result = LoadTextures(device, deviceContext, filename);
if (!result)
{
Logger::Get().Log("Failed to load textures", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
Logger::Get().Log("Model class initialized", __FILE__, __LINE__, Logger::LogLevel::Initialize); m_Textures = textures;
Logger::Get().Log("Model class initialized with preloaded textures", __FILE__, __LINE__, Logger::LogLevel::Initialize);
return true; return true;
} }
@@ -86,9 +77,11 @@ int ModelClass::GetIndexCount()
return m_indexCount; return m_indexCount;
} }
ID3D11ShaderResourceView* ModelClass::GetTexture(int index) ID3D11ShaderResourceView* ModelClass::GetTexture(int index) const {
{ if (index >= 0 && index < m_Textures.size()) {
return m_Textures[index].GetTexture(); return m_Textures[index];
}
return nullptr; // Retourne nullptr si l'index est hors limites
} }
@@ -221,52 +214,23 @@ void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
return; return;
} }
bool ModelClass::LoadTextures(ID3D11Device* device, ID3D11DeviceContext* deviceContext, vector<string> textureFile)
{
Logger::Get().Log("Loading textures", __FILE__, __LINE__);
bool result;
// Create and initialize the texture object array.
m_Textures = new TextureClass[textureFile.size()];
for (int i = 0; i < textureFile.size(); i++)
{
result = m_Textures[i].Initialize(device, deviceContext, textureFile[i]);
if (!result)
{
Logger::Get().Log("Failed to initialize texture", __FILE__, __LINE__, Logger::LogLevel::Error);
return false;
}
}
Logger::Get().Log("Textures loaded", __FILE__, __LINE__);
return true;
}
void ModelClass::ReleaseTextures() void ModelClass::ReleaseTextures()
{ {
Logger::Get().Log("Releasing textures", __FILE__, __LINE__); Logger::Get().Log("Releasing textures", __FILE__, __LINE__);
// Release the texture object array. // Release the texture object array.
if (m_Textures) for (auto& texture : m_Textures)
{ {
m_Textures[0].Shutdown(); if (texture)
m_Textures[1].Shutdown(); {
m_Textures[2].Shutdown(); texture->Release();
m_Textures[3].Shutdown(); texture = nullptr;
m_Textures[4].Shutdown(); }
m_Textures[5].Shutdown();
delete[] m_Textures;
m_Textures = 0;
} }
Logger::Get().Log("Textures released", __FILE__, __LINE__); m_Textures.clear();
return; Logger::Get().Log("Textures released", __FILE__, __LINE__);
} }
bool ModelClass::LoadModel(char* filename) bool ModelClass::LoadModel(char* filename)
@@ -590,23 +554,39 @@ void ModelClass::ReleaseModel()
bool ModelClass::ChangeTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, std::wstring filename, int index) bool ModelClass::ChangeTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, std::wstring filename, int index)
{ {
bool result; Logger::Get().Log("Changing texture", __FILE__, __LINE__, Logger::LogLevel::Initialize);
// convert wstring to string HRESULT result;
std::string str(filename.begin(), filename.end()); ID3D11ShaderResourceView* newTexture = nullptr;
// Release the old texture object. // Load the new texture using WICTextureLoader.
m_Textures[index].Shutdown(); result = DirectX::CreateWICTextureFromFile(device, deviceContext, filename.c_str(), nullptr, &newTexture);
if (FAILED(result))
// Initialize the new texture object.
result = m_Textures[index].Initialize(device, deviceContext, str);
if (!result)
{ {
Logger::Get().Log("Failed to initialize texture", __FILE__, __LINE__, Logger::LogLevel::Error); Logger::Get().Log("Failed to load new texture", __FILE__, __LINE__, Logger::LogLevel::Error);
return false; return false;
} }
Logger::Get().Log("Texture changed", __FILE__, __LINE__, Logger::LogLevel::Debug); // Release the old texture if it exists.
if (index >= 0 && index < m_Textures.size() && m_Textures[index])
{
m_Textures[index]->Release();
m_Textures[index] = nullptr;
}
// Assign the new texture to the specified index.
if (index >= 0 && index < m_Textures.size())
{
m_Textures[index] = newTexture;
}
else
{
// If the index is out of range, log an error and release the new texture.
Logger::Get().Log("Texture index out of range", __FILE__, __LINE__, Logger::LogLevel::Error);
newTexture->Release();
return false;
}
Logger::Get().Log("Texture changed successfully", __FILE__, __LINE__, Logger::LogLevel::Initialize);
return true; return true;
} }

View File

@@ -13,6 +13,7 @@
#include <sstream> #include <sstream>
#include <vector> #include <vector>
#include <string> #include <string>
#include <WICTextureLoader.h>
using namespace DirectX; using namespace DirectX;
using namespace std; using namespace std;
@@ -82,12 +83,13 @@ public:
ModelClass(const ModelClass&); ModelClass(const ModelClass&);
~ModelClass(); ~ModelClass();
bool Initialize(ID3D11Device*, ID3D11DeviceContext*, char*, vector<string>); bool Initialize(ID3D11Device*, ID3D11DeviceContext*, char*, std::vector<ID3D11ShaderResourceView*>);
void Shutdown(); void Shutdown();
void Render(ID3D11DeviceContext*); void Render(ID3D11DeviceContext*);
int GetIndexCount(); int GetIndexCount();
ID3D11ShaderResourceView* GetTexture(int); ID3D11ShaderResourceView* GetTexture(int index) const;
bool ChangeTexture(ID3D11Device*, ID3D11DeviceContext*, std::wstring filename, int index); bool ChangeTexture(ID3D11Device*, ID3D11DeviceContext*, std::wstring filename, int index);
private: private:
@@ -108,7 +110,7 @@ private:
private: private:
ID3D11Buffer* m_vertexBuffer, * m_indexBuffer; ID3D11Buffer* m_vertexBuffer, * m_indexBuffer;
int m_vertexCount, m_indexCount; int m_vertexCount, m_indexCount;
TextureClass* m_Textures; std::vector<ID3D11ShaderResourceView*> m_Textures;
ModelType* m_model; ModelType* m_model;
}; };

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

View File

@@ -17,6 +17,7 @@ Object::Object() : ModelClass()
Object::~Object() Object::~Object()
{ {
} }
void Object::SetScaleMatrix(XMMATRIX scaleMatrix) void Object::SetScaleMatrix(XMMATRIX scaleMatrix)

View File

@@ -1,5 +1,7 @@
#pragma once #pragma once
#include "modelclass.h" #include "modelclass.h"
#include <WICTextureLoader.h>
#include <SimpleMath.h>
class Object : public ModelClass class Object : public ModelClass
{ {
@@ -50,6 +52,8 @@ public:
int SetId(int id); int SetId(int id);
int GetId() const; int GetId() const;
bool LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, const std::wstring& filename);
public : public :
bool m_demoSpinning = false; bool m_demoSpinning = false;
XMVECTOR m_previousPosition; XMVECTOR m_previousPosition;
@@ -68,5 +72,4 @@ private:
bool m_isGrounded; bool m_isGrounded;
std::string m_name; std::string m_name;
}; };

View File

@@ -13,6 +13,7 @@ ShaderManagerClass::ShaderManagerClass()
m_LightMapShader = 0; m_LightMapShader = 0;
m_RefractionShader = 0; m_RefractionShader = 0;
m_WaterShader = 0; m_WaterShader = 0;
m_CelShadingShader = 0;
} }
@@ -140,6 +141,14 @@ bool ShaderManagerClass::Initialize(ID3D11Device* device, HWND hwnd)
return false; return false;
} }
m_CelShadingShader = new CelShadingShader;
result = m_CelShadingShader->Initialize(device, hwnd);
if (!result)
{
return false;
}
Logger::Get().Log("ShaderManagerClass initialized", __FILE__, __LINE__, Logger::LogLevel::Initialize); Logger::Get().Log("ShaderManagerClass initialized", __FILE__, __LINE__, Logger::LogLevel::Initialize);
return true; return true;
@@ -417,4 +426,18 @@ bool ShaderManagerClass::RenderWaterShader(ID3D11DeviceContext* deviceContext, i
} }
return true; return true;
}
bool ShaderManagerClass::RenderCelShadingShader(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
ID3D11ShaderResourceView* texture, XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor, XMFLOAT3 lightPosition)
{
bool result;
result = m_CelShadingShader->Render(deviceContext, indexCount, worldMatrix, viewMatrix, projectionMatrix, texture, lightDirection, diffuseColor, lightPosition);
if (!result)
{
return false;
}
return true;
} }

View File

@@ -15,6 +15,7 @@
#include "lightmapshaderclass.h" #include "lightmapshaderclass.h"
#include "refractionshaderclass.h" #include "refractionshaderclass.h"
#include "watershaderclass.h" #include "watershaderclass.h"
#include "CelShadingShader.h"
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@@ -43,6 +44,7 @@ public:
XMFLOAT3, XMFLOAT4[], XMFLOAT4[], XMFLOAT4[], XMFLOAT4); XMFLOAT3, XMFLOAT4[], XMFLOAT4[], XMFLOAT4[], XMFLOAT4);
bool RenderWaterShader(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, bool RenderWaterShader(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*,
ID3D11ShaderResourceView*, ID3D11ShaderResourceView*, float, float); ID3D11ShaderResourceView*, ID3D11ShaderResourceView*, float, float);
bool RenderCelShadingShader(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT3, XMFLOAT4, XMFLOAT3);
private: private:
TextureShaderClass* m_TextureShader; TextureShaderClass* m_TextureShader;
NormalMapShaderClass* m_NormalMapShader; NormalMapShaderClass* m_NormalMapShader;
@@ -56,6 +58,7 @@ private:
LightMapShaderClass* m_LightMapShader; LightMapShaderClass* m_LightMapShader;
RefractionShaderClass* m_RefractionShader; RefractionShaderClass* m_RefractionShader;
WaterShaderClass* m_WaterShader; WaterShaderClass* m_WaterShader;
CelShadingShader* m_CelShadingShader;
}; };
#endif #endif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 768 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB