Merge branch 'main' into la-fusion-de-l'enfer

This commit is contained in:
CatChow0 2024-03-29 16:49:31 +01:00
commit 513c12bee0
58 changed files with 23966 additions and 554 deletions

84
enginecustom/Light.ps Normal file
View File

@ -0,0 +1,84 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: light.ps
////////////////////////////////////////////////////////////////////////////////
/////////////
// DEFINES //
/////////////
#define NUM_LIGHTS 4
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture : register(t0);
SamplerState SampleType : register(s0);
cbuffer LightBuffer
{
float4 ambientColor;
float3 lightDirection;
float padding;
float specularPower;
float4 specularColor;
};
cbuffer LightColorBuffer
{
float4 diffuseColor[NUM_LIGHTS];
};
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 lightPos[NUM_LIGHTS] : TEXCOORD1;
};
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
float4 textureColor;
float3 lightDir;
float4 color;
float3 reflection;
float4 specular;
float lightIntensity[NUM_LIGHTS];
float4 colorArray[NUM_LIGHTS];
float4 colorSum;
int i;
// Sample the pixel color from the texture using the sampler at this texture coordinate location.
textureColor = shaderTexture.Sample(SampleType, input.tex);
for(i=0; i<NUM_LIGHTS; i++)
{
// Calculate the different amounts of light on this pixel based on the positions of the lights.
lightIntensity[i] = saturate(dot(input.normal, input.lightPos[i]));
// Determine the diffuse color amount of each of the four lights.
colorArray[i] = diffuseColor[i] * lightIntensity[i];
}
// Initialize the sum of colors.
colorSum = float4(0.0f, 0.0f, 0.0f, 1.0f);
// Add all of the light colors up.
for(i=0; i<NUM_LIGHTS; i++)
{
colorSum.r += colorArray[i].r;
colorSum.g += colorArray[i].g;
colorSum.b += colorArray[i].b;
}
// Multiply the texture pixel by the combination of all four light colors to get the final result.
color = saturate(colorSum) * textureColor;
return color;
}

89
enginecustom/Light.vs Normal file
View File

@ -0,0 +1,89 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: light.vs
////////////////////////////////////////////////////////////////////////////////
/////////////
// DEFINES //
/////////////
#define NUM_LIGHTS 4
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};
cbuffer CameraBuffer
{
float3 cameraPosition;
float padding;
};
cbuffer LightPositionBuffer
{
float4 lightPosition[NUM_LIGHTS];
};
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
};
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 lightPos[NUM_LIGHTS] : TEXCOORD1;
};
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType LightVertexShader(VertexInputType input)
{
PixelInputType output;
float4 worldPosition;
int i;
// 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.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);
// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
// Calculate the normal vector against the world matrix only.
output.normal = mul(input.normal, (float3x3)worldMatrix);
// Normalize the normal vector.
output.normal = normalize(output.normal);
// Calculate the position of the vertex in the world.
worldPosition = mul(input.position, worldMatrix);
for(i=0; i<NUM_LIGHTS; i++)
{
// Determine the light positions based on the position of the lights and the position of the vertex in the world.
output.lightPos[i] = lightPosition[i].xyz - worldPosition.xyz;
// Normalize the light position vectors.
output.lightPos[i] = normalize(output.lightPos[i]);
}
return output;
}

View File

@ -0,0 +1,91 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: lightclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "lightclass.h"
LightClass::LightClass()
{
}
LightClass::LightClass(const LightClass& other)
{
}
LightClass::~LightClass()
{
}
void LightClass::SetAmbientColor(float red, float green, float blue, float alpha)
{
m_ambientColor = XMFLOAT4(red, green, blue, alpha);
return;
}
void LightClass::SetDiffuseColor(float red, float green, float blue, float alpha)
{
m_diffuseColor = XMFLOAT4(red, green, blue, alpha);
return;
}
void LightClass::SetDirection(float x, float y, float z)
{
m_direction = XMFLOAT3(x, y, z);
return;
}
void LightClass::SetSpecularColor(float red, float green, float blue, float alpha)
{
m_specularColor = XMFLOAT4(red, green, blue, alpha);
return;
}
void LightClass::SetSpecularPower(float power)
{
m_specularPower = power;
return;
}
void LightClass::SetPosition(float x, float y, float z)
{
m_position = XMFLOAT4(x, y, z, 1.0f);
return;
}
XMFLOAT4 LightClass::GetAmbientColor()
{
return m_ambientColor;
}
XMFLOAT4 LightClass::GetDiffuseColor()
{
return m_diffuseColor;
}
XMFLOAT3 LightClass::GetDirection()
{
return m_direction;
}
XMFLOAT4 LightClass::GetSpecularColor()
{
return m_specularColor;
}
float LightClass::GetSpecularPower()
{
return m_specularPower;
}
XMFLOAT4 LightClass::GetPosition()
{
return m_position;
}

49
enginecustom/Lightclass.h Normal file
View File

@ -0,0 +1,49 @@
#pragma once
////////////////////////////////////////////////////////////////////////////////
// Filename: lightclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _LIGHTCLASS_H_
#define _LIGHTCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <directxmath.h>
using namespace DirectX;
////////////////////////////////////////////////////////////////////////////////
// Class name: LightClass
////////////////////////////////////////////////////////////////////////////////
class LightClass
{
public:
LightClass();
LightClass(const LightClass&);
~LightClass();
void SetAmbientColor(float, float, float, float);
void SetDiffuseColor(float, float, float, float);
void SetDirection(float, float, float);
void SetSpecularColor(float, float, float, float);
void SetSpecularPower(float);
void SetPosition(float, float, float);
XMFLOAT4 GetAmbientColor();
XMFLOAT4 GetDiffuseColor();
XMFLOAT3 GetDirection();
XMFLOAT4 GetSpecularColor();
float GetSpecularPower();
XMFLOAT4 GetPosition();
private:
XMFLOAT4 m_ambientColor;
XMFLOAT4 m_diffuseColor;
XMFLOAT3 m_direction;
XMFLOAT4 m_specularColor;
float m_specularPower;
XMFLOAT4 m_position;
};
#endif

View File

@ -0,0 +1,516 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: lightshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "lightshaderclass.h"
LightShaderClass::LightShaderClass()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_sampleState = 0;
m_matrixBuffer = 0;
m_cameraBuffer = 0;
m_lightBuffer = 0;
m_lightColorBuffer = 0;
m_lightPositionBuffer = 0;
}
LightShaderClass::LightShaderClass(const LightShaderClass& other)
{
}
LightShaderClass::~LightShaderClass()
{
}
bool LightShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
wchar_t vsFilename[128];
wchar_t psFilename[128];
int error;
bool result;
// Set the filename of the vertex shader.
error = wcscpy_s(vsFilename, 128, L"light.vs");
if (error != 0)
{
return false;
}
// Set the filename of the pixel shader.
error = wcscpy_s(psFilename, 128, L"light.ps");
if (error != 0)
{
return false;
}
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, vsFilename, psFilename);
if (!result)
{
return false;
}
return true;
}
void LightShaderClass::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
return;
}
bool LightShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
ID3D11ShaderResourceView* texture, XMFLOAT4 diffuseColor[], XMFLOAT4 lightPosition[])
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, diffuseColor, lightPosition);
if(!result)
{
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
}
bool LightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* pixelShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
unsigned int numElements;
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_BUFFER_DESC cameraBufferDesc;
D3D11_BUFFER_DESC lightColorBufferDesc;
D3D11_BUFFER_DESC lightPositionBufferDesc;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
pixelShaderBuffer = 0;
// Compile the vertex shader code.
result = D3DCompileFromFile(vsFilename, NULL, NULL, "LightVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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, NULL, NULL, "LightPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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(), NULL, &m_vertexShader);
if (FAILED(result))
{
return false;
}
// Create the pixel shader from the buffer.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
if (FAILED(result))
{
return false;
}
// Create the vertex input layout description.
// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_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 = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_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 = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
// 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 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, NULL, &m_matrixBuffer);
if (FAILED(result))
{
return false;
}
// Setup the description of the camera dynamic constant buffer that is in the vertex shader.
cameraBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
cameraBufferDesc.ByteWidth = sizeof(CameraBufferType);
cameraBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cameraBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cameraBufferDesc.MiscFlags = 0;
cameraBufferDesc.StructureByteStride = 0;
// Create the camera constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&cameraBufferDesc, NULL, &m_cameraBuffer);
if (FAILED(result))
{
return false;
}
// Setup the description of the dynamic constant buffer that is in the pixel shader.
lightColorBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightColorBufferDesc.ByteWidth = sizeof(LightColorBufferType);
lightColorBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightColorBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightColorBufferDesc.MiscFlags = 0;
lightColorBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
result = device->CreateBuffer(&lightColorBufferDesc, NULL, &m_lightColorBuffer);
if (FAILED(result))
{
return false;
}
// Setup the description of the dynamic constant buffer that is in the vertex shader.
lightPositionBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightPositionBufferDesc.ByteWidth = sizeof(LightPositionBufferType);
lightPositionBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightPositionBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightPositionBufferDesc.MiscFlags = 0;
lightPositionBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&lightPositionBufferDesc, NULL, &m_lightPositionBuffer);
if (FAILED(result))
{
return false;
}
return true;
}
void LightShaderClass::ShutdownShader()
{
// Release the light constant buffers.
if (m_lightColorBuffer)
{
m_lightColorBuffer->Release();
m_lightColorBuffer = 0;
}
if (m_lightPositionBuffer)
{
m_lightPositionBuffer->Release();
m_lightPositionBuffer = 0;
}
// Release the light constant buffer.
if (m_lightBuffer)
{
m_lightBuffer->Release();
m_lightBuffer = 0;
}
// Release the camera constant buffer.
if (m_cameraBuffer)
{
m_cameraBuffer->Release();
m_cameraBuffer = 0;
}
// Release the matrix constant buffer.
if (m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the sampler state.
if (m_sampleState)
{
m_sampleState->Release();
m_sampleState = 0;
}
// Release the layout.
if (m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the pixel shader.
if (m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the vertex shader.
if (m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
return;
}
void LightShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned __int64 bufferSize, i;
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 = 0;
// 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);
return;
}
bool LightShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
ID3D11ShaderResourceView* texture, XMFLOAT4 diffuseColor[], XMFLOAT4 lightPosition[])
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
unsigned int bufferNumber;
MatrixBufferType* dataPtr;
LightPositionBufferType* dataPtr2;
LightColorBufferType* dataPtr3;
// 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;
// Now set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
// Lock the camera constant buffer so it can be written to.
result = deviceContext->Map(m_cameraBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Lock the light position constant buffer so it can be written to.
result = deviceContext->Map(m_lightPositionBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr2 = (LightPositionBufferType*)mappedResource.pData;
// Copy the light position variables into the constant buffer.
dataPtr2->lightPosition[0] = lightPosition[0];
dataPtr2->lightPosition[1] = lightPosition[1];
dataPtr2->lightPosition[2] = lightPosition[2];
dataPtr2->lightPosition[3] = lightPosition[3];
// Unlock the constant buffer.
deviceContext->Unmap(m_lightPositionBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 1;
// Finally set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_lightPositionBuffer);
// Set shader texture resource in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &texture);
// Lock the light color constant buffer so it can be written to.
result = deviceContext->Map(m_lightColorBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr3 = (LightColorBufferType*)mappedResource.pData;
// Copy the light color variables into the constant buffer.
dataPtr3->diffuseColor[0] = diffuseColor[0];
dataPtr3->diffuseColor[1] = diffuseColor[1];
dataPtr3->diffuseColor[2] = diffuseColor[2];
dataPtr3->diffuseColor[3] = diffuseColor[3];
// Unlock the constant buffer.
deviceContext->Unmap(m_lightColorBuffer, 0);
// Set the position of the constant buffer in the pixel shader.
bufferNumber = 0;
// Finally set the constant buffer in the pixel shader with the updated values.
deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightColorBuffer);
return true;
}
void LightShaderClass::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, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
return;
}

View File

@ -0,0 +1,92 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: lightshaderclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _LIGHTSHADERCLASS_H_
#define _LIGHTSHADERCLASS_H_
/////////////
// GLOBALS //
/////////////
const int NUM_LIGHTS = 4;
//////////////
// INCLUDES //
//////////////
#include <d3d11.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <fstream>
using namespace DirectX;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Class name: LightShaderClass
////////////////////////////////////////////////////////////////////////////////
class LightShaderClass
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
struct CameraBufferType
{
XMFLOAT3 cameraPosition;
float padding;
};
struct LightBufferType
{
XMFLOAT4 ambientColor;
XMFLOAT4 diffuseColor;
XMFLOAT3 lightDirection;
float padding; // Added extra padding so structure is a multiple of 16 for CreateBuffer function requirements.
float specularPower;
XMFLOAT4 specularColor;
};
struct LightColorBufferType
{
XMFLOAT4 diffuseColor[NUM_LIGHTS];
};
struct LightPositionBufferType
{
XMFLOAT4 lightPosition[NUM_LIGHTS];
};
public:
LightShaderClass();
LightShaderClass(const LightShaderClass&);
~LightShaderClass();
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4[], XMFLOAT4[]);
private:
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4[], XMFLOAT4[]);
void RenderShader(ID3D11DeviceContext*, int);
private:
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11SamplerState* m_sampleState;
ID3D11Buffer* m_matrixBuffer;
ID3D11Buffer* m_cameraBuffer;
ID3D11Buffer* m_lightBuffer;
ID3D11Buffer* m_lightColorBuffer;
ID3D11Buffer* m_lightPositionBuffer;
};
#endif

View File

@ -0,0 +1,45 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: multitexture.ps
////////////////////////////////////////////////////////////////////////////////
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture1 : register(t0);
Texture2D shaderTexture2 : register(t1);
SamplerState SampleType : register(s0);
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
};
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 MultiTexturePixelShader(PixelInputType input) : SV_TARGET
{
float4 color1;
float4 color2;
float4 blendColor;
// Sample the pixel color from the textures using the sampler at this texture coordinate location.
color1 = shaderTexture1.Sample(SampleType, input.tex);
color2 = shaderTexture2.Sample(SampleType, input.tex);
// Combine the two textures together.
blendColor = color1 * color2 * 2.0;
// Saturate the final color.
blendColor = saturate(blendColor);
return blendColor;
}

View File

@ -0,0 +1,54 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: multitexture.vs
////////////////////////////////////////////////////////////////////////////////
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
};
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
};
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType MultiTextureVertexShader(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.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);
// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
return output;
}

View File

@ -0,0 +1,373 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: multitextureshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "multitextureshaderclass.h"
MultiTextureShaderClass::MultiTextureShaderClass()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_matrixBuffer = 0;
m_sampleState = 0;
}
MultiTextureShaderClass::MultiTextureShaderClass(const MultiTextureShaderClass& other)
{
}
MultiTextureShaderClass::~MultiTextureShaderClass()
{
}
bool MultiTextureShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
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"multitexture.vs");
if (error != 0)
{
return false;
}
// Set the filename of the pixel shader.
error = wcscpy_s(psFilename, 128, L"multitexture.ps");
if (error != 0)
{
return false;
}
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, vsFilename, psFilename);
if (!result)
{
return false;
}
return true;
}
void MultiTextureShaderClass::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
return;
}
bool MultiTextureShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture1, ID3D11ShaderResourceView* texture2)
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture1, texture2);
if (!result)
{
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
}
bool MultiTextureShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* pixelShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_SAMPLER_DESC samplerDesc;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
pixelShaderBuffer = 0;
// Compile the vertex shader code.
result = D3DCompileFromFile(vsFilename, NULL, NULL, "MultiTextureVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
&vertexShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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, NULL, NULL, "MultiTexturePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
&pixelShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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(), NULL, &m_vertexShader);
if (FAILED(result))
{
return false;
}
// Create the pixel shader from the buffer.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
if (FAILED(result))
{
return false;
}
// Create the vertex input layout description.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_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 = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_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 = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
// 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, NULL, &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;
}
return true;
}
void MultiTextureShaderClass::ShutdownShader()
{
// Release the sampler state.
if (m_sampleState)
{
m_sampleState->Release();
m_sampleState = 0;
}
// Release the matrix constant buffer.
if (m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the layout.
if (m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the pixel shader.
if (m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the vertex shader.
if (m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
return;
}
void MultiTextureShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned long long bufferSize, i;
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 = 0;
// 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);
return;
}
bool MultiTextureShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture1, ID3D11ShaderResourceView* texture2)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBufferType* dataPtr;
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);
// Set shader texture resources in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &texture1);
deviceContext->PSSetShaderResources(1, 1, &texture2);
return true;
}
void MultiTextureShaderClass::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, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
return;
}

View File

@ -0,0 +1,57 @@
////////////////////////////////////////////////////////////////////////////////
// Filename: multitextureshaderclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _MULTITEXTURESHADERCLASS_H_
#define _MULTITEXTURESHADERCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <d3d11.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <fstream>
using namespace DirectX;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Class name: MultiTextureShaderClass
////////////////////////////////////////////////////////////////////////////////
class MultiTextureShaderClass
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
public:
MultiTextureShaderClass();
MultiTextureShaderClass(const MultiTextureShaderClass&);
~MultiTextureShaderClass();
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, ID3D11ShaderResourceView*);
private:
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, ID3D11ShaderResourceView*);
void RenderShader(ID3D11DeviceContext*, int);
private:
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11Buffer* m_matrixBuffer;
ID3D11SamplerState* m_sampleState;
};
#endif

View File

@ -0,0 +1,421 @@
#include "spriteclass.h"
SpriteClass::SpriteClass()
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
m_Textures = 0;
}
SpriteClass::SpriteClass(const SpriteClass& other)
{
}
SpriteClass::~SpriteClass()
{
}
bool SpriteClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, int screenWidth, int screenHeight, char* spriteFilename, int renderX, int renderY)
{
bool result;
// Store the screen size.
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
// Store where the sprite should be rendered to.
m_renderX = renderX;
m_renderY = renderY;
// Initialize the frame time for this sprite object.
m_frameTime = 0;
// Initialize the vertex and index buffer that hold the geometry for the sprite bitmap.
result = InitializeBuffers(device);
if (!result)
{
return false;
}
// Load the textures for this sprite.
result = LoadTextures(device, deviceContext, spriteFilename);
if (!result)
{
return false;
}
return true;
}
void SpriteClass::Shutdown()
{
// Release the textures used for this sprite.
ReleaseTextures();
// Release the vertex and index buffers.
ShutdownBuffers();
return;
}
bool SpriteClass::Render(ID3D11DeviceContext* deviceContext)
{
bool result;
// Update the buffers if the position of the sprite has changed from its original position.
result = UpdateBuffers(deviceContext);
if (!result)
{
return false;
}
// Put the vertex and index buffers on the graphics pipeline to prepare them for drawing.
RenderBuffers(deviceContext);
return true;
}
void SpriteClass::Update(float frameTime)
{
// Increment the frame time each frame.
m_frameTime += frameTime;
// Check if the frame time has reached the cycle time.
if (m_frameTime >= m_cycleTime)
{
// If it has then reset the frame time and cycle to the next sprite in the texture array.
m_frameTime -= m_cycleTime;
m_currentTexture++;
// If we are at the last sprite texture then go back to the beginning of the texture array to the first texture again.
if (m_currentTexture == m_textureCount)
{
m_currentTexture = 0;
}
}
return;
}
int SpriteClass::GetIndexCount()
{
return m_indexCount;
}
ID3D11ShaderResourceView* SpriteClass::GetTexture()
{
return m_Textures[m_currentTexture].GetTexture();
}
bool SpriteClass::InitializeBuffers(ID3D11Device* device)
{
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
int i;
// Initialize the previous rendering position to negative one.
m_prevPosX = -1;
m_prevPosY = -1;
// Set the number of vertices in the vertex array.
m_vertexCount = 6;
// Set the number of indices in the index array.
m_indexCount = m_vertexCount;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
// Create the index array.
indices = new unsigned long[m_indexCount];
// Initialize vertex array to zeros at first.
memset(vertices, 0, (sizeof(VertexType) * m_vertexCount));
// Load the index array with data.
for (i = 0; i < m_indexCount; i++)
{
indices[i] = i;
}
// Set up the description of the dynamic vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Now finally create the vertex buffer.
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer);
if (FAILED(result))
{
return false;
}
// Set up the description of the index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer);
if (FAILED(result))
{
return false;
}
// Release the arrays now that the vertex and index buffers have been created and loaded.
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
void SpriteClass::ShutdownBuffers()
{
// Release the index buffer.
if (m_indexBuffer)
{
m_indexBuffer->Release();
m_indexBuffer = 0;
}
// Release the vertex buffer.
if (m_vertexBuffer)
{
m_vertexBuffer->Release();
m_vertexBuffer = 0;
}
return;
}
bool SpriteClass::UpdateBuffers(ID3D11DeviceContext* deviceContent)
{
float left, right, top, bottom;
VertexType* vertices;
D3D11_MAPPED_SUBRESOURCE mappedResource;
VertexType* dataPtr;
HRESULT result;
// If the position we are rendering this bitmap to hasn't changed then don't update the vertex buffer.
if ((m_prevPosX == m_renderX) && (m_prevPosY == m_renderY))
{
return true;
}
// If the rendering location has changed then store the new position and update the vertex buffer.
m_prevPosX = m_renderX;
m_prevPosY = m_renderY;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
// Calculate the screen coordinates of the left side of the bitmap.
left = (float)((m_screenWidth / 2) * -1) + (float)m_renderX;
// Calculate the screen coordinates of the right side of the bitmap.
right = left + (float)m_bitmapWidth;
// Calculate the screen coordinates of the top of the bitmap.
top = (float)(m_screenHeight / 2) - (float)m_renderY;
// Calculate the screen coordinates of the bottom of the bitmap.
bottom = top - (float)m_bitmapHeight;
// Load the vertex array with data.
// First triangle.
vertices[0].position = XMFLOAT3(left, top, 0.0f); // Top left.
vertices[0].texture = XMFLOAT2(0.0f, 0.0f);
vertices[1].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right.
vertices[1].texture = XMFLOAT2(1.0f, 1.0f);
vertices[2].position = XMFLOAT3(left, bottom, 0.0f); // Bottom left.
vertices[2].texture = XMFLOAT2(0.0f, 1.0f);
// Second triangle.
vertices[3].position = XMFLOAT3(left, top, 0.0f); // Top left.
vertices[3].texture = XMFLOAT2(0.0f, 0.0f);
vertices[4].position = XMFLOAT3(right, top, 0.0f); // Top right.
vertices[4].texture = XMFLOAT2(1.0f, 0.0f);
vertices[5].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right.
vertices[5].texture = XMFLOAT2(1.0f, 1.0f);
// Lock the vertex buffer.
result = deviceContent->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr = (VertexType*)mappedResource.pData;
// Copy the data into the vertex buffer.
memcpy(dataPtr, (void*)vertices, (sizeof(VertexType) * m_vertexCount));
// Unlock the vertex buffer.
deviceContent->Unmap(m_vertexBuffer, 0);
// Release the pointer reference.
dataPtr = 0;
// Release the vertex array as it is no longer needed.
delete[] vertices;
vertices = 0;
return true;
}
void SpriteClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
unsigned int stride;
unsigned int offset;
// Set vertex buffer stride and offset.
stride = sizeof(VertexType);
offset = 0;
// Set the vertex buffer to active in the input assembler so it can be rendered.
deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
// Set the index buffer to active in the input assembler so it can be rendered.
deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
return;
}
bool SpriteClass::LoadTextures(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
{
char textureFilename[128];
std::ifstream fin;
int i, j;
char input;
bool result;
// Open the sprite info data file.
fin.open(filename);
if (fin.fail())
{
return false;
}
// Read in the number of textures.
fin >> m_textureCount;
// Create and initialize the texture array with the texture count from the file.
m_Textures = new TextureClass[m_textureCount];
// Read to start of next line.
fin.get(input);
// Read in each texture file name.
for (i = 0; i < m_textureCount; i++)
{
j = 0;
fin.get(input);
while (input != '\n')
{
textureFilename[j] = input;
j++;
fin.get(input);
}
textureFilename[j] = '\0';
// Once you have the filename then load the texture in the texture array.
result = m_Textures[i].Initialize(device, deviceContext, textureFilename);
if (!result)
{
return false;
}
}
// Read in the cycle time.
fin >> m_cycleTime;
// Convert the integer milliseconds to float representation.
m_cycleTime = m_cycleTime * 0.001f;
// Close the file.
fin.close();
// Get the dimensions of the first texture and use that as the dimensions of the 2D sprite images.
m_bitmapWidth = m_Textures[0].GetWidth();
m_bitmapHeight = m_Textures[0].GetHeight();
// Set the starting texture in the cycle to be the first one in the list.
m_currentTexture = 0;
return true;
}
void SpriteClass::ReleaseTextures()
{
int i;
// Release the texture objects.
if (m_Textures)
{
for (i = 0; i < m_textureCount; i++)
{
m_Textures[i].Shutdown();
}
delete[] m_Textures;
m_Textures = 0;
}
return;
}
void SpriteClass::SetRenderLocation(int x, int y)
{
m_renderX = x;
m_renderY = y;
return;
}

View File

@ -0,0 +1,63 @@
#ifndef _SPRITECLASS_H_
#define _SPRITECLASS_H_
//////////////
// INCLUDES //
//////////////
#include <directxmath.h>
#include <fstream>
using namespace DirectX;
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "textureclass.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: SpriteClass
////////////////////////////////////////////////////////////////////////////////
class SpriteClass
{
private:
struct VertexType
{
XMFLOAT3 position;
XMFLOAT2 texture;
};
public:
SpriteClass();
SpriteClass(const SpriteClass&);
~SpriteClass();
bool Initialize(ID3D11Device*, ID3D11DeviceContext*, int, int, char*, int, int);
void Shutdown();
bool Render(ID3D11DeviceContext*);
void Update(float);
int GetIndexCount();
ID3D11ShaderResourceView* GetTexture();
void SetRenderLocation(int, int);
private:
bool InitializeBuffers(ID3D11Device*);
void ShutdownBuffers();
bool UpdateBuffers(ID3D11DeviceContext*);
void RenderBuffers(ID3D11DeviceContext*);
bool LoadTextures(ID3D11Device*, ID3D11DeviceContext*, char*);
void ReleaseTextures();
private:
ID3D11Buffer* m_vertexBuffer, * m_indexBuffer;
int m_vertexCount, m_indexCount, m_screenWidth, m_screenHeight, m_bitmapWidth, m_bitmapHeight, m_renderX, m_renderY, m_prevPosX, m_prevPosY;
TextureClass* m_Textures;
float m_frameTime, m_cycleTime;
int m_currentTexture, m_textureCount;
};
#endif

View File

@ -282,9 +282,9 @@ void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight)
}
else
{
// If windowed then set it to 800x600 resolution.
screenWidth = 800;
screenHeight = 600;
// If windowed then set it to 1600x900 resolution.
screenWidth = 1600;
screenHeight = 900;
// Place the window in the middle of the screen.
posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2;

View File

@ -0,0 +1,63 @@
#include "timerclass.h"
TimerClass::TimerClass()
{
}
TimerClass::TimerClass(const TimerClass& other)
{
}
TimerClass::~TimerClass()
{
}
bool TimerClass::Initialize()
{
INT64 frequency;
// Get the cycles per second speed for this system.
QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
if (frequency == 0)
{
return false;
}
// Store it in floating point.
m_frequency = (float)frequency;
// Get the initial start time.
QueryPerformanceCounter((LARGE_INTEGER*)&m_startTime);
return true;
}
void TimerClass::Frame()
{
INT64 currentTime;
INT64 elapsedTicks;
// Query the current time.
QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
// Calculate the difference in time since the last time we queried for the current time.
elapsedTicks = currentTime - m_startTime;
// Calculate the frame time.
m_frameTime = (float)elapsedTicks / m_frequency;
// Restart the timer.
m_startTime = currentTime;
return;
}
float TimerClass::GetTime()
{
return m_frameTime;
}

32
enginecustom/Timerclass.h Normal file
View File

@ -0,0 +1,32 @@
#ifndef _TIMERCLASS_H_
#define _TIMERCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <windows.h>
////////////////////////////////////////////////////////////////////////////////
// Class name: TimerClass
////////////////////////////////////////////////////////////////////////////////
class TimerClass
{
public:
TimerClass();
TimerClass(const TimerClass&);
~TimerClass();
bool Initialize();
void Frame();
float GetTime();
private:
float m_frequency;
INT64 m_startTime;
float m_frameTime;
};
#endif

View File

@ -3,10 +3,23 @@
ApplicationClass::ApplicationClass()
{
m_Direct3D = 0;
m_Camera = 0;
m_Camera = 0;
m_MultiTextureShader = 0;
m_Model = 0;
m_LightShader = 0;
m_Light = 0;
m_TextureShader = 0;
m_Bitmap = 0;
m_Sprite = 0;
m_Timer = 0;
m_Lights = 0;
m_FontShader = 0;
m_Font = 0;
m_TextString1 = 0;
m_TextString2 = 0;
m_TextString3 = 0;
m_Fps = 0;
m_FpsString = 0;
}
@ -22,8 +35,12 @@ ApplicationClass::~ApplicationClass()
bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
char testString1[32], testString2[32], testString3[32];
char modelFilename[128];
char textureFilename[128];
char textureFilename1[128], textureFilename2[128];
char bitmapFilename[128];
char spriteFilename[128];
char fpsString[32];
bool result;
// Create the Direct3D object.
@ -48,25 +65,131 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
}
// Set the initial position of the camera.
m_Camera->SetPosition(0.0f, 0.0f, -10.0f);
m_Camera->SetPosition(0.0f, 0.0f, -12.0f);
m_Camera->SetRotation(0.0f, 0.0f, 0.0f);
// Create and initialize the font shader object.
m_FontShader = new FontShaderClass;
result = m_FontShader->Initialize(m_Direct3D->GetDevice(), hwnd);
if (!result)
{
MessageBox(hwnd, L"Could not initialize the font shader object.", L"Error", MB_OK);
return false;
}
// Create and initialize the font object.
m_Font = new FontClass;
result = m_Font->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), 0);
if (!result)
{
return false;
}
// Set the strings we want to display.
strcpy_s(testString1, "Yo");
strcpy_s(testString2, "Les");
strcpy_s(testString3, "Noobs !");
// Create and initialize the first text object.
m_TextString1 = new TextClass;
result = m_TextString1->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, 32, m_Font, testString1, 25, screenHeight / 2 - m_Font->GetFontHeight(), 1.0f, 1.0f, 1.0f);
if (!result)
{
return false;
}
// Create and initialize the second text object.
m_TextString2 = new TextClass;
result = m_TextString2->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, 32, m_Font, testString2, 250, screenHeight / 2 - m_Font->GetFontHeight(), 0.0f, 1.0f, 1.0f);
if (!result)
{
return false;
}
// Create and initialize the second text object.
m_TextString3 = new TextClass;
result = m_TextString3->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, 32, m_Font, testString3, screenWidth / 2 - m_Font->GetSentencePixelLength(testString3), screenHeight / 2 - m_Font->GetFontHeight(), 1.0f, 1.0f, 0.0f);
if (!result)
{
return false;
}
// Create and initialize the texture shader object.
m_TextureShader = new TextureShaderClass;
result = m_TextureShader->Initialize(m_Direct3D->GetDevice(), hwnd);
if (!result)
{
MessageBox(hwnd, L"Could not initialize the texture shader object.", L"Error", MB_OK);
return false;
}
// Set the sprite info file we will be using.
strcpy_s(spriteFilename, "sprite_data_01.txt");
// Create and initialize the sprite object.
m_Sprite = new SpriteClass;
result = m_Sprite->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, spriteFilename, 50, 50);
if (!result)
{
return false;
}
// Create and initialize the timer object.
m_Timer = new TimerClass;
result = m_Timer->Initialize();
if (!result)
{
return false;
}
// Set the file name of the bitmap file.
strcpy_s(bitmapFilename, "stone01.tga");
// Create and initialize the bitmap object.
m_Bitmap = new BitmapClass;
result = m_Bitmap->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, bitmapFilename, 50, 50);
if (!result)
{
return false;
}
// Create and initialize the multitexture shader object.
m_MultiTextureShader = new MultiTextureShaderClass;
result = m_MultiTextureShader->Initialize(m_Direct3D->GetDevice(), hwnd);
if (!result)
{
MessageBox(hwnd, L"Could not initialize the multitexture shader object.", L"Error", MB_OK);
return false;
}
// Set the file name of the model.
strcpy_s(modelFilename, "cube.txt");
// Set the name of the texture file that we will be loading.
strcpy_s(textureFilename, "stone01.tga");
// Set the file name of the textures.
strcpy_s(textureFilename1, "stone01.tga");
strcpy_s(textureFilename2, "moss01.tga");
// Create and initialize the model object.
m_Model = new ModelClass;
result = m_Model->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textureFilename);
result = m_Model->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), modelFilename, textureFilename1, textureFilename2);
if (!result)
{
MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
return false;
}
// Create and initialize the light shader object.
m_LightShader = new LightShaderClass;
@ -76,6 +199,7 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
return false;
}
// Set the number of lights we will use.
m_numLights = 4;
@ -94,11 +218,25 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
m_Lights[3].SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f); // White
m_Lights[3].SetPosition(3.0f, 1.0f, -3.0f);
// Create and initialize the light object.
m_Light = new LightClass;
m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
m_Light->SetDirection(0.0f, -1.0f, 1.0f);
// Create and initialize the fps object.
m_Fps = new FpsClass();
m_Fps->Initialize();
// Set the initial fps and fps string.
m_previousFps = -1;
strcpy_s(fpsString, "Fps: 0");
// Create and initialize the text object for the fps string.
m_FpsString = new TextClass;
result = m_FpsString->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, 32, m_Font, fpsString, 10, 10, 0.0f, 1.0f, 0.0f);
if (!result)
{
return false;
}
return true;
}
@ -106,11 +244,88 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
void ApplicationClass::Shutdown()
{
// Release the light object.
if (m_Lights)
// Release the text object for the fps string.
if (m_FpsString)
{
delete m_Lights;
m_Lights = 0;
m_FpsString->Shutdown();
delete m_FpsString;
m_FpsString = 0;
}
// Release the fps object.
if (m_Fps)
{
delete m_Fps;
m_Fps = 0;
}
// Release the text string objects.
if (m_TextString3)
{
m_TextString3->Shutdown();
delete m_TextString3;
m_TextString3 = 0;
}
if (m_TextString2)
{
m_TextString2->Shutdown();
delete m_TextString2;
m_TextString2 = 0;
}
if (m_TextString1)
{
m_TextString1->Shutdown();
delete m_TextString1;
m_TextString1 = 0;
}
// Release the font object.
if (m_Font)
{
m_Font->Shutdown();
delete m_Font;
m_Font = 0;
}
// Release the font shader object.
if (m_FontShader)
{
m_FontShader->Shutdown();
delete m_FontShader;
m_FontShader = 0;
}
// Release the timer object.
if (m_Timer)
{
delete m_Timer;
m_Timer = 0;
}
// Release the sprite object.
if (m_Sprite)
{
m_Sprite->Shutdown();
delete m_Sprite;
m_Sprite = 0;
}
// Release the light objects.
if(m_Lights)
{
delete [] m_Lights;
m_Lights = 0;
}
// Release the light shader object.
if (m_LightShader)
{
m_LightShader->Shutdown();
delete m_LightShader;
m_LightShader = 0;
}
// Release the light shader object.
@ -129,20 +344,27 @@ void ApplicationClass::Shutdown()
m_Model = 0;
}
// Release the camera object.
if (m_Camera)
// Release the multitexture shader object.
if (m_MultiTextureShader)
{
delete m_Camera;
m_Camera = 0;
}
m_MultiTextureShader->Shutdown();
delete m_MultiTextureShader;
m_MultiTextureShader = 0;
// Release the bitmap object.
if (m_Bitmap)
{
m_Bitmap->Shutdown();
delete m_Bitmap;
m_Bitmap = 0;
}
// Release the D3D object.
if (m_Direct3D)
{
m_Direct3D->Shutdown();
delete m_Direct3D;
m_Direct3D = 0;
}
// Release the texture shader object.
if (m_TextureShader)
{
m_TextureShader->Shutdown();
delete m_TextureShader;
m_TextureShader = 0;
}
// Liberez la memoire pour chaque cube
for (auto cube : m_cubes)
@ -160,15 +382,43 @@ void ApplicationClass::Shutdown()
}
m_terrainChunk.clear();
// Release the camera object.
if (m_Camera)
{
delete m_Camera;
m_Camera = 0;
}
// Release the D3D object.
if (m_Direct3D)
{
m_Direct3D->Shutdown();
delete m_Direct3D;
m_Direct3D = 0;
}
return;
}
}
bool ApplicationClass::Frame()
{
float frameTime;
static float rotation = 0.0f;
static float x = 2.f;
static float y = 0.f;
static float z = 0.f;
bool result;
// Update the frames per second each frame.
result = UpdateFps();
if (!result)
{
return false;
}
// Update the rotation variable each frame.
rotation -= 0.0174532925f * speed;
if (rotation < 0.0f)
@ -176,20 +426,38 @@ bool ApplicationClass::Frame()
rotation += 360.0f;
}
// Update the x position variable each frame.
x -= 0.0174532925f * 0.54672f;
y -= 0.0174532925f * 0.8972f;
// Update the z position variable each frame.
z -= 0.0174532925f * 0.8972f;
// Render the graphics scene.
result = Render(rotation);
result = Render(rotation, x, y, z);
if (!result)
{
return false;
}
// Update the system stats.
m_Timer->Frame();
// Get the current frame time.
frameTime = m_Timer->GetTime();
// Update the sprite object using the frame time.
m_Sprite->Update(frameTime);
return true;
}
bool ApplicationClass::Render(float rotation)
bool ApplicationClass::Render(float rotation, float x, float y, float z)
{
XMMATRIX worldMatrix, rotateMatrix, translateMatrix, scaleMatrix, srMatrix, viewMatrix, projectionMatrix;;
XMMATRIX worldMatrix, viewMatrix, orthoMatrix, projectionMatrix, rotateMatrix, translateMatrix, scaleMatrix, srMatrix;
XMFLOAT4 diffuseColor[4], lightPosition[4];
int i;
bool result;
@ -204,6 +472,112 @@ bool ApplicationClass::Render(float rotation)
m_Direct3D->GetWorldMatrix(worldMatrix);
viewMatrix = m_Camera->GetViewMatrix();
m_Direct3D->GetProjectionMatrix(projectionMatrix);
m_Direct3D->GetOrthoMatrix(orthoMatrix);
// Disable the Z buffer and enable alpha blending for 2D rendering.
m_Direct3D->TurnZBufferOff();
m_Direct3D->EnableAlphaBlending();
// Render the fps text string using the font shader.
m_FpsString->Render(m_Direct3D->GetDeviceContext());
result = m_FontShader->Render(m_Direct3D->GetDeviceContext(), m_FpsString->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
m_Font->GetTexture(), m_FpsString->GetPixelColor());
if (!result)
{
return false;
}
// Render the first text string using the font shader.
m_TextString1->Render(m_Direct3D->GetDeviceContext());
result = m_FontShader->Render(m_Direct3D->GetDeviceContext(), m_TextString1->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
m_Font->GetTexture(), m_TextString1->GetPixelColor());
if (!result)
{
return false;
}
// Render the second text string using the font shader.
m_TextString2->Render(m_Direct3D->GetDeviceContext());
result = m_FontShader->Render(m_Direct3D->GetDeviceContext(), m_TextString2->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
m_Font->GetTexture(), m_TextString2->GetPixelColor());
if (!result)
{
return false;
}
// Render the second text string using the font shader.
m_TextString3->Render(m_Direct3D->GetDeviceContext());
result = m_FontShader->Render(m_Direct3D->GetDeviceContext(), m_TextString3->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
m_Font->GetTexture(), m_TextString3->GetPixelColor());
if (!result)
{
return false;
}
// Put the sprite vertex and index buffers on the graphics pipeline to prepare them for drawing.
result = m_Sprite->Render(m_Direct3D->GetDeviceContext());
if (!result)
{
return false;
}
// Render the sprite with the texture shader.
result = m_TextureShader->Render(m_Direct3D->GetDeviceContext(), m_Sprite->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_Sprite->GetTexture());
if (!result)
{
return false;
}
// Put the bitmap vertex and index buffers on the graphics pipeline to prepare them for drawing.
result = m_Bitmap->Render(m_Direct3D->GetDeviceContext());
if (!result)
{
return false;
}
m_Bitmap->SetRenderLocation(1200, 50);
// Render the bitmap with the texture shader.
result = m_TextureShader->Render(m_Direct3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_Bitmap->GetTexture());
if (!result)
{
return false;
}
// Get the light properties.
for (i = 0; i < m_numLights; i++)
{
// Create the diffuse color array from the four light colors.
diffuseColor[i] = m_Lights[i].GetDiffuseColor();
// Create the light position array from the four light positions.
lightPosition[i] = m_Lights[i].GetPosition();
}
scaleMatrix = XMMatrixScaling(0.5f, 0.5f, 0.5f); // Build the scaling matrix.
rotateMatrix = XMMatrixRotationY(rotation); // Build the rotation matrix.
translateMatrix = XMMatrixTranslation(x, y, z); // Build the translation matrix.
// Multiply the scale, rotation, and translation matrices together to create the final world transformation matrix.
srMatrix = XMMatrixMultiply(scaleMatrix, rotateMatrix);
worldMatrix = XMMatrixMultiply(srMatrix, translateMatrix);
// Render the model using the multitexture shader.
m_Model->Render(m_Direct3D->GetDeviceContext());
scaleMatrix = XMMatrixScaling(2.0f, 2.0f, 2.0f); // Build the scaling matrix.
rotateMatrix = XMMatrixRotationY(-rotation); // Build the rotation matrix.
translateMatrix = XMMatrixTranslation(-x, -y, -z); // Build the translation matrix.
// Multiply the scale, rotation, and translation matrices together to create the final world transformation matrix.
srMatrix = XMMatrixMultiply(scaleMatrix, rotateMatrix);
worldMatrix = XMMatrixMultiply(srMatrix, translateMatrix);
// Get the light properties.
for (i = 0; i < m_numLights; i++)
@ -217,7 +591,15 @@ bool ApplicationClass::Render(float rotation)
// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
m_Model->Render(m_Direct3D->GetDeviceContext());
// Render the model using the light shader.
result = m_LightShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture(0),
diffuseColor, lightPosition);
if (!result)
{
return false;
}
for (auto cube : m_cubes)
{
cube->Render(m_Direct3D->GetDeviceContext());
@ -236,7 +618,7 @@ bool ApplicationClass::Render(float rotation)
srMatrix = XMMatrixMultiply(scaleMatrix, rotateMatrix);
worldMatrix = XMMatrixMultiply(srMatrix, translateMatrix);
result = m_LightShader->Render(m_Direct3D->GetDeviceContext(), cube->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, cube->GetTexture(),
result = m_LightShader->Render(m_Direct3D->GetDeviceContext(), cube->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, cube->GetTexture(0),
diffuseColor, lightPosition);
if (!result)
{
@ -256,7 +638,7 @@ bool ApplicationClass::Render(float rotation)
srMatrix = XMMatrixMultiply(scaleMatrix, rotateMatrix);
worldMatrix = XMMatrixMultiply(srMatrix, translateMatrix);
result = m_LightShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture(),
result = m_LightShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture(0),
diffuseColor, lightPosition);
if (!result)
{
@ -264,6 +646,17 @@ bool ApplicationClass::Render(float rotation)
}
}
// Render the model using the multitexture shader.
result = m_MultiTextureShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix,
m_Model->GetTexture(0), m_Model->GetTexture(1));
if (!result)
{
return false;
}
// Enable the Z buffer and disable alpha blending now that 2D rendering is complete.
m_Direct3D->TurnZBufferOn();
m_Direct3D->DisableAlphaBlending();
// Present the rendered scene to the screen.
m_Direct3D->EndScene();
@ -308,8 +701,6 @@ void ApplicationClass::GenerateTerrain()
}
void ApplicationClass::AddCube()
{
char modelFilename[128];
@ -348,4 +739,72 @@ void ApplicationClass::DeleteTerrain()
delete cube;
}
m_terrainChunk.clear();
bool ApplicationClass::UpdateFps()
{
int fps;
char tempString[16], finalString[16];
float red, green, blue;
bool result;
// Update the fps each frame.
m_Fps->Frame();
// Get the current fps.
fps = m_Fps->GetFps();
// Check if the fps from the previous frame was the same, if so don't need to update the text string.
if (m_previousFps == fps)
{
return true;
}
// Store the fps for checking next frame.
m_previousFps = fps;
// Truncate the fps to below 100,000.
if (fps > 99999)
{
fps = 99999;
}
// Convert the fps integer to string format.
sprintf_s(tempString, "%d", fps);
// Setup the fps string.
strcpy_s(finalString, "Fps: ");
strcat_s(finalString, tempString);
// If fps is 60 or above set the fps color to green.
if (fps >= 60)
{
red = 0.0f;
green = 1.0f;
blue = 0.0f;
}
// If fps is below 60 set the fps color to yellow.
if (fps < 60)
{
red = 1.0f;
green = 1.0f;
blue = 0.0f;
}
// If fps is below 30 set the fps color to red.
if (fps < 30)
{
red = 1.0f;
green = 0.0f;
blue = 0.0f;
}
// Update the sentence vertex buffer with the new string information.
result = m_FpsString->UpdateText(m_Direct3D->GetDeviceContext(), m_Font, finalString, 10, 10, red, green, blue);
if (!result)
{
return false;
}
return true;
}

View File

@ -12,6 +12,15 @@
#include "lightclass.h"
#include <vector>
#include "multitextureshaderclass.h"
#include "bitmapclass.h"
#include "textureshaderclass.h"
#include "spriteclass.h"
#include "timerclass.h"
#include "fontshaderclass.h"
#include "fontclass.h"
#include "textclass.h"
#include "fpsclass.h"
/////////////
// GLOBALS //
@ -55,21 +64,32 @@ public:
private:
bool Render(float);
bool Render(float, float, float, float);
bool UpdateFps();
private:
D3DClass* m_Direct3D;
CameraClass* m_Camera;
ModelClass* m_Model;
IDXGISwapChain* m_swapChain;
LightShaderClass* m_LightShader;
LightClass* m_Light;
float speed = 0.1f;
Object* m_SelectedObject;
LightClass* m_Lights;
int m_numLights;
std::vector<Object*> m_cubes;
std::vector<Object*> m_terrainChunk;
LightShaderClass* m_LightShader;
LightClass* m_Light;
MultiTextureShaderClass* m_MultiTextureShader;
ModelClass* m_Model;
TextureShaderClass* m_TextureShader;
BitmapClass* m_Bitmap;
SpriteClass* m_Sprite;
TimerClass* m_Timer;
LightClass* m_Lights;
int m_numLights;
FontShaderClass* m_FontShader;
FontClass* m_Font;
TextClass *m_TextString1, *m_TextString2, *m_TextString3;
FpsClass* m_Fps;
TextClass* m_FpsString;
int m_previousFps;
};
#endif

View File

@ -0,0 +1,333 @@
#include "bitmapclass.h"
BitmapClass::BitmapClass()
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
m_Texture = 0;
}
BitmapClass::BitmapClass(const BitmapClass& other)
{
}
BitmapClass::~BitmapClass()
{
}
bool BitmapClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, int screenWidth, int screenHeight, char* textureFilename, int renderX, int renderY)
{
bool result;
// Store the screen size.
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
// Store where the bitmap should be rendered to.
m_renderX = renderX;
m_renderY = renderY;
// Initialize the vertex and index buffer that hold the geometry for the bitmap quad.
result = InitializeBuffers(device);
if (!result)
{
return false;
}
// Load the texture for this bitmap.
result = LoadTexture(device, deviceContext, textureFilename);
if (!result)
{
return false;
}
return true;
}
void BitmapClass::Shutdown()
{
// Release the bitmap texture.
ReleaseTexture();
// Release the vertex and index buffers.
ShutdownBuffers();
return;
}
bool BitmapClass::Render(ID3D11DeviceContext* deviceContext)
{
bool result;
// Update the buffers if the position of the bitmap has changed from its original position.
result = UpdateBuffers(deviceContext);
if (!result)
{
return false;
}
// Put the vertex and index buffers on the graphics pipeline to prepare them for drawing.
RenderBuffers(deviceContext);
return true;
}
int BitmapClass::GetIndexCount()
{
return m_indexCount;
}
ID3D11ShaderResourceView* BitmapClass::GetTexture()
{
return m_Texture->GetTexture();
}
bool BitmapClass::InitializeBuffers(ID3D11Device* device)
{
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
int i;
// Initialize the previous rendering position to negative one.
m_prevPosX = -1;
m_prevPosY = -1;
// Set the number of vertices in the vertex array.
m_vertexCount = 6;
// Set the number of indices in the index array.
m_indexCount = m_vertexCount;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
// Create the index array.
indices = new unsigned long[m_indexCount];
// Initialize vertex array to zeros at first.
memset(vertices, 0, (sizeof(VertexType) * m_vertexCount));
// Load the index array with data.
for (i = 0; i < m_indexCount; i++)
{
indices[i] = i;
}
// Set up the description of the dynamic vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Now finally create the vertex buffer.
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer);
if (FAILED(result))
{
return false;
}
// Set up the description of the index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer);
if (FAILED(result))
{
return false;
}
// Release the arrays now that the vertex and index buffers have been created and loaded.
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
void BitmapClass::ShutdownBuffers()
{
// Release the index buffer.
if (m_indexBuffer)
{
m_indexBuffer->Release();
m_indexBuffer = 0;
}
// Release the vertex buffer.
if (m_vertexBuffer)
{
m_vertexBuffer->Release();
m_vertexBuffer = 0;
}
return;
}
bool BitmapClass::UpdateBuffers(ID3D11DeviceContext* deviceContent)
{
float left, right, top, bottom;
VertexType* vertices;
D3D11_MAPPED_SUBRESOURCE mappedResource;
VertexType* dataPtr;
HRESULT result;
// If the position we are rendering this bitmap to hasn't changed then don't update the vertex buffer.
if ((m_prevPosX == m_renderX) && (m_prevPosY == m_renderY))
{
return true;
}
// If the rendering location has changed then store the new position and update the vertex buffer.
m_prevPosX = m_renderX;
m_prevPosY = m_renderY;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
// Calculate the screen coordinates of the left side of the bitmap.
left = (float)((m_screenWidth / 2) * -1) + (float)m_renderX;
// Calculate the screen coordinates of the right side of the bitmap.
right = left + (float)m_bitmapWidth;
// Calculate the screen coordinates of the top of the bitmap.
top = (float)(m_screenHeight / 2) - (float)m_renderY;
// Calculate the screen coordinates of the bottom of the bitmap.
bottom = top - (float)m_bitmapHeight;
// Load the vertex array with data.
// First triangle.
vertices[0].position = XMFLOAT3(left, top, 0.0f); // Top left.
vertices[0].texture = XMFLOAT2(0.0f, 0.0f);
vertices[1].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right.
vertices[1].texture = XMFLOAT2(1.0f, 1.0f);
vertices[2].position = XMFLOAT3(left, bottom, 0.0f); // Bottom left.
vertices[2].texture = XMFLOAT2(0.0f, 1.0f);
// Second triangle.
vertices[3].position = XMFLOAT3(left, top, 0.0f); // Top left.
vertices[3].texture = XMFLOAT2(0.0f, 0.0f);
vertices[4].position = XMFLOAT3(right, top, 0.0f); // Top right.
vertices[4].texture = XMFLOAT2(1.0f, 0.0f);
vertices[5].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right.
vertices[5].texture = XMFLOAT2(1.0f, 1.0f);
// Lock the vertex buffer.
result = deviceContent->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr = (VertexType*)mappedResource.pData;
// Copy the data into the vertex buffer.
memcpy(dataPtr, (void*)vertices, (sizeof(VertexType) * m_vertexCount));
// Unlock the vertex buffer.
deviceContent->Unmap(m_vertexBuffer, 0);
// Release the pointer reference.
dataPtr = 0;
// Release the vertex array as it is no longer needed.
delete[] vertices;
vertices = 0;
return true;
}
void BitmapClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
unsigned int stride;
unsigned int offset;
// Set vertex buffer stride and offset.
stride = sizeof(VertexType);
offset = 0;
// Set the vertex buffer to active in the input assembler so it can be rendered.
deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
// Set the index buffer to active in the input assembler so it can be rendered.
deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
return;
}
bool BitmapClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
{
bool result;
// Create and initialize the texture object.
m_Texture = new TextureClass;
result = m_Texture->Initialize(device, deviceContext, filename);
if (!result)
{
return false;
}
// Store the size in pixels that this bitmap should be rendered at.
m_bitmapWidth = m_Texture->GetWidth();
m_bitmapHeight = m_Texture->GetHeight();
return true;
}
void BitmapClass::ReleaseTexture()
{
// Release the texture object.
if (m_Texture)
{
m_Texture->Shutdown();
delete m_Texture;
m_Texture = 0;
}
return;
}
void BitmapClass::SetRenderLocation(int x, int y)
{
m_renderX = x;
m_renderY = y;
return;
}

View File

@ -0,0 +1,58 @@
#ifndef _BITMAPCLASS_H_
#define _BITMAPCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <directxmath.h>
using namespace DirectX;
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "textureclass.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: BitmapClass
////////////////////////////////////////////////////////////////////////////////
class BitmapClass
{
private:
struct VertexType
{
XMFLOAT3 position;
XMFLOAT2 texture;
};
public:
BitmapClass();
BitmapClass(const BitmapClass&);
~BitmapClass();
bool Initialize(ID3D11Device*, ID3D11DeviceContext*, int, int, char*, int, int);
void Shutdown();
bool Render(ID3D11DeviceContext*);
int GetIndexCount();
ID3D11ShaderResourceView* GetTexture();
void SetRenderLocation(int, int);
private:
bool InitializeBuffers(ID3D11Device*);
void ShutdownBuffers();
bool UpdateBuffers(ID3D11DeviceContext*);
void RenderBuffers(ID3D11DeviceContext*);
bool LoadTexture(ID3D11Device*, ID3D11DeviceContext*, char*);
void ReleaseTexture();
private:
ID3D11Buffer* m_vertexBuffer, * m_indexBuffer;
int m_vertexCount, m_indexCount, m_screenWidth, m_screenHeight, m_bitmapWidth, m_bitmapHeight, m_renderX, m_renderY, m_prevPosX, m_prevPosY;
TextureClass* m_Texture;
};
#endif

View File

@ -37,4 +37,4 @@ Data:
-1.0 -1.0 1.0 0.0 1.0 0.0 -1.0 0.0
-1.0 -1.0 1.0 0.0 1.0 0.0 -1.0 0.0
1.0 -1.0 -1.0 1.0 0.0 0.0 -1.0 0.0
1.0 -1.0 1.0 1.0 1.0 0.0 -1.0 0.0
1.0 -1.0 1.0 1.0 1.0 0.0 -1.0 0.0

View File

@ -14,6 +14,9 @@ D3DClass::D3DClass()
m_depthStencilState = 0;
m_depthStencilView = 0;
m_rasterState = 0;
m_depthDisabledStencilState = 0;
m_alphaEnableBlendingState = 0;
m_alphaDisableBlendingState = 0;
}
@ -46,7 +49,8 @@ bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hw
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
D3D11_RASTERIZER_DESC rasterDesc;
float fieldOfView, screenAspect;
D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
D3D11_BLEND_DESC blendStateDescription;
// Store the vsync setting.
m_vsync_enabled = vsync;
@ -346,6 +350,63 @@ bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hw
// Create an orthographic projection matrix for 2D rendering.
m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
// Clear the second depth stencil state before setting the parameters.
ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
// Now create a second depth stencil state which turns off the Z buffer for 2D rendering. The only difference is
// that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
depthDisabledStencilDesc.DepthEnable = false;
depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthDisabledStencilDesc.StencilEnable = true;
depthDisabledStencilDesc.StencilReadMask = 0xFF;
depthDisabledStencilDesc.StencilWriteMask = 0xFF;
depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create the state using the device.
result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState);
if (FAILED(result))
{
return false;
}
// Clear the blend state description.
ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));
// Create an alpha enabled blend state description.
blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;
// Create the blend state using the description.
result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState);
if (FAILED(result))
{
return false;
}
// Modify the description to create an alpha disabled blend state description.
blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
// Create the blend state using the description.
result = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState);
if (FAILED(result))
{
return false;
}
return true;
}
@ -358,6 +419,24 @@ void D3DClass::Shutdown()
m_swapChain->SetFullscreenState(false, NULL);
}
if (m_alphaEnableBlendingState)
{
m_alphaEnableBlendingState->Release();
m_alphaEnableBlendingState = 0;
}
if (m_alphaDisableBlendingState)
{
m_alphaDisableBlendingState->Release();
m_alphaDisableBlendingState = 0;
}
if (m_depthDisabledStencilState)
{
m_depthDisabledStencilState->Release();
m_depthDisabledStencilState = 0;
}
if (m_rasterState)
{
m_rasterState->Release();
@ -598,4 +677,51 @@ void D3DClass::ResizeSwapChain(int newWidth, int newHeight)
m_viewport.Width = static_cast<float>(newWidth);
m_viewport.Height = static_cast<float>(newHeight);
m_deviceContext->RSSetViewports(1, &m_viewport);
}
}
void D3DClass::TurnZBufferOn()
{
m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);
return;
}
void D3DClass::TurnZBufferOff()
{
m_deviceContext->OMSetDepthStencilState(m_depthDisabledStencilState, 1);
return;
}
void D3DClass::EnableAlphaBlending()
{
float blendFactor[4];
// Setup the blend factor.
blendFactor[0] = 0.0f;
blendFactor[1] = 0.0f;
blendFactor[2] = 0.0f;
blendFactor[3] = 0.0f;
// Turn on the alpha blending.
m_deviceContext->OMSetBlendState(m_alphaEnableBlendingState, blendFactor, 0xffffffff);
return;
}
void D3DClass::DisableAlphaBlending()
{
float blendFactor[4];
// Setup the blend factor.
blendFactor[0] = 0.0f;
blendFactor[1] = 0.0f;
blendFactor[2] = 0.0f;
blendFactor[3] = 0.0f;
// Turn off the alpha blending.
m_deviceContext->OMSetBlendState(m_alphaDisableBlendingState, blendFactor, 0xffffffff);
return;
}

View File

@ -16,11 +16,13 @@
//////////////
// INCLUDES //
//////////////
#include <d3d11.h>
#include <directxmath.h>
#include "imguiManager.h"
using namespace DirectX;
#include "d3d11.h"
#include "fontshaderclass.h"
#include "fontclass.h"
#include "textclass.h"
using namespace DirectX;
////////////////////////////////////////////////////////////////////////////////
// Class name: D3DClass
@ -56,6 +58,12 @@ public:
void ReleaseResources();
void ResetResources(int newWidth, int newHeight);
void TurnZBufferOn();
void TurnZBufferOff();
void EnableAlphaBlending();
void DisableAlphaBlending();
private:
bool m_vsync_enabled;
@ -72,6 +80,9 @@ private:
XMMATRIX m_worldMatrix;
XMMATRIX m_orthoMatrix;
D3D11_VIEWPORT m_viewport;
ID3D11DepthStencilState* m_depthDisabledStencilState;
ID3D11BlendState* m_alphaEnableBlendingState;
ID3D11BlendState* m_alphaDisableBlendingState;
};
#endif

View File

@ -21,6 +21,7 @@
</ItemGroup>
<ItemGroup>
<ClCompile Include="applicationclass.cpp" />
<ClCompile Include="bitmapclass.cpp" />
<ClCompile Include="Cameraclass.cpp" />
<ClCompile Include="Colorshaderclass.cpp" />
<ClCompile Include="d3dclass.cpp" />
@ -32,18 +33,26 @@
<ClCompile Include="include\imgui_draw.cpp" />
<ClCompile Include="include\imgui_tables.cpp" />
<ClCompile Include="include\imgui_widgets.cpp" />
<ClCompile Include="fontclass.cpp" />
<ClCompile Include="fontshaderclass.cpp" />
<ClCompile Include="fpsclass.cpp" />
<ClCompile Include="inputclass.cpp" />
<ClCompile Include="lightclass.cpp" />
<ClCompile Include="lightshaderclass.cpp" />
<ClCompile Include="Lightclass.cpp" />
<ClCompile Include="Lightshaderclass.cpp" />
<ClCompile Include="Main.cpp" />
<ClCompile Include="modelclass.cpp" />
<ClCompile Include="object.cpp" />
<ClCompile Include="Multitextureshaderclass.cpp" />
<ClCompile Include="Spriteclass.cpp" />
<ClCompile Include="Systemclass.cpp" />
<ClCompile Include="textclass.cpp" />
<ClCompile Include="textureclass.cpp" />
<ClCompile Include="textureshaderclass.cpp" />
<ClCompile Include="Timerclass.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\dx11win10tut06_src\source\lightclass.h" />
<ClInclude Include="applicationclass.h" />
<ClInclude Include="bitmapclass.h" />
<ClInclude Include="Cameraclass.h" />
<ClInclude Include="Colorshaderclass.h" />
<ClInclude Include="d3dclass.h" />
@ -56,17 +65,32 @@
<ClInclude Include="include\imstb_rectpack.h" />
<ClInclude Include="include\imstb_textedit.h" />
<ClInclude Include="include\imstb_truetype.h" />
<ClInclude Include="fontclass.h" />
<ClInclude Include="fontshaderclass.h" />
<ClInclude Include="fpsclass.h" />
<ClInclude Include="inputclass.h" />
<ClInclude Include="lightclass.h" />
<ClInclude Include="lightshaderclass.h" />
<ClInclude Include="modelclass.h" />
<ClInclude Include="object.h" />
<ClInclude Include="Multitextureshaderclass.h" />
<ClInclude Include="Spriteclass.h" />
<ClInclude Include="systemclass.h" />
<ClInclude Include="textclass.h" />
<ClInclude Include="textureclass.h" />
<ClInclude Include="textureshaderclass.h" />
<ClInclude Include="Timerclass.h" />
</ItemGroup>
<ItemGroup>
<None Include="font.ps" />
<None Include="font.vs" />
<None Include="light.ps" />
<None Include="light.vs" />
<None Include="Multitexture.ps" />
<None Include="Multitexture.vs" />
<None Include="packages.config" />
<None Include="texture.ps" />
<None Include="texture.vs" />
</ItemGroup>
<ItemGroup>
<None Include="Color.ps">
@ -88,11 +112,18 @@
</ItemGroup>
<ItemGroup>
<Image Include="..\..\..\..\Downloads\grass.tga" />
<Image Include="font01.tga" />
<Image Include="moss01.tga" />
<Image Include="papier.tga" />
<Image Include="stone01.tga" />
<Image Include="wall.tga" />
</ItemGroup>
<ItemGroup>
<Text Include="..\..\..\..\Downloads\chunk.txt" />
<Text Include="cube.txt" />
<Text Include="font01.txt" />
<Text Include="plane.txt" />
<Text Include="sphere.txt" />
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>

47
enginecustom/font.ps Normal file
View File

@ -0,0 +1,47 @@
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture : register(t0);
SamplerState SampleType : register(s0);
cbuffer PixelBuffer
{
float4 pixelColor;
};
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
};
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 FontPixelShader(PixelInputType input) : SV_TARGET
{
float4 color;
// Sample the texture pixel at this location.
color = shaderTexture.Sample(SampleType, input.tex);
// If the color is black on the texture then treat this pixel as transparent.
if(color.r == 0.0f)
{
color.a = 0.0f;
}
// If the color is other than black on the texture then this is a pixel in the font so draw it using the font pixel color.
else
{
color.a = 1.0f;
color = color * pixelColor;
}
return color;
}

48
enginecustom/font.vs Normal file
View File

@ -0,0 +1,48 @@
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
};
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
};
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType FontVertexShader(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.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);
// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
return output;
}

BIN
enginecustom/font01.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

95
enginecustom/font01.txt Normal file
View File

@ -0,0 +1,95 @@
32 0.0 0.0 0
33 ! 0.0 0.00390625 4
34 " 0.0048828125 0.0107421875 6
35 # 0.01171875 0.025390625 14
36 $ 0.0263671875 0.0390625 13
37 % 0.0400390625 0.0546875 15
38 & 0.0556640625 0.0693359375 14
39 ' 0.0703125 0.0732421875 3
40 ( 0.07421875 0.0791015625 5
41 ) 0.080078125 0.0849609375 5
42 * 0.0859375 0.091796875 6
43 + 0.0927734375 0.103515625 11
44 , 0.1044921875 0.107421875 3
45 - 0.1083984375 0.1142578125 6
46 . 0.115234375 0.1181640625 3
47 / 0.119140625 0.126953125 8
48 0 0.1279296875 0.1416015625 14
49 1 0.142578125 0.146484375 4
50 2 0.1474609375 0.1591796875 12
51 3 0.16015625 0.1708984375 11
52 4 0.171875 0.1845703125 13
53 5 0.185546875 0.1962890625 11
54 6 0.197265625 0.2099609375 13
55 7 0.2109375 0.22265625 12
56 8 0.2236328125 0.236328125 13
57 9 0.2373046875 0.2490234375 12
58 : 0.25 0.2529296875 3
59 ; 0.25390625 0.2568359375 3
60 < 0.2578125 0.267578125 10
61 = 0.2685546875 0.279296875 11
62 > 0.2802734375 0.2900390625 10
63 ? 0.291015625 0.302734375 12
64 @ 0.3037109375 0.3173828125 14
65 A 0.318359375 0.33203125 14
66 B 0.3330078125 0.3447265625 12
67 C 0.345703125 0.3564453125 11
68 D 0.357421875 0.3701171875 13
69 E 0.37109375 0.3818359375 11
70 F 0.3828125 0.3935546875 11
71 G 0.39453125 0.40625 12
72 H 0.4072265625 0.41796875 11
73 I 0.4189453125 0.421875 3
74 J 0.4228515625 0.4326171875 10
75 K 0.43359375 0.4443359375 11
76 L 0.4453125 0.4541015625 9
77 M 0.455078125 0.4697265625 15
78 N 0.470703125 0.482421875 12
79 O 0.4833984375 0.49609375 13
80 P 0.4970703125 0.5078125 12
81 Q 0.509765625 0.5224609375 13
82 R 0.5234375 0.53515625 12
83 S 0.5361328125 0.548828125 13
84 T 0.5498046875 0.5615234375 12
85 U 0.5625 0.57421875 12
86 V 0.5751953125 0.5888671875 14
87 W 0.58984375 0.609375 20
88 X 0.6103515625 0.6220703125 12
89 Y 0.623046875 0.6357421875 13
90 Z 0.63671875 0.6474609375 11
91 [ 0.6484375 0.654296875 6
92 \ 0.6552734375 0.6630859375 8
93 ] 0.6640625 0.6689453125 5
94 ^ 0.669921875 0.6806640625 11
95 _ 0.681640625 0.6904296875 9
96 ` 0.69140625 0.6962890625 5
97 a 0.697265625 0.70703125 10
98 b 0.7080078125 0.7177734375 10
99 c 0.71875 0.7275390625 9
100 d 0.728515625 0.73828125 10
101 e 0.7392578125 0.748046875 9
102 f 0.7490234375 0.755859375 7
103 g 0.7568359375 0.7666015625 10
104 h 0.767578125 0.7763671875 9
105 i 0.77734375 0.7802734375 3
106 j 0.78125 0.7861328125 5
107 k 0.787109375 0.796875 10
108 l 0.7978515625 0.80078125 3
109 m 0.8017578125 0.8154296875 14
110 n 0.81640625 0.826171875 10
111 o 0.8271484375 0.8369140625 10
112 p 0.837890625 0.84765625 10
113 q 0.8486328125 0.8583984375 10
114 r 0.859375 0.8671875 8
115 s 0.8681640625 0.8779296875 10
116 t 0.87890625 0.8857421875 7
117 u 0.88671875 0.8955078125 9
118 v 0.896484375 0.908203125 12
119 w 0.9091796875 0.9248046875 16
120 x 0.92578125 0.935546875 10
121 y 0.9365234375 0.9453125 9
122 z 0.9462890625 0.9560546875 10
123 { 0.95703125 0.9638671875 7
124 | 0.96484375 0.966796875 2
125 } 0.9677734375 0.974609375 7
126 ~ 0.9755859375 0.986328125 11

252
enginecustom/fontclass.cpp Normal file
View File

@ -0,0 +1,252 @@
#include "fontclass.h"
FontClass::FontClass()
{
m_Font = 0;
m_Texture = 0;
}
FontClass::FontClass(const FontClass& other)
{
}
FontClass::~FontClass()
{
}
bool FontClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, int fontChoice)
{
char fontFilename[128];
char fontTextureFilename[128];
bool result;
// Choose one of the available fonts, and default to the first font otherwise.
switch (fontChoice)
{
case 0:
{
strcpy_s(fontFilename, "font01.txt");
strcpy_s(fontTextureFilename, "font01.tga");
m_fontHeight = 32.0f;
m_spaceSize = 3;
break;
}
default:
{
strcpy_s(fontFilename, "font01.txt");
strcpy_s(fontTextureFilename, "font01.tga");
m_fontHeight = 32.0f;
m_spaceSize = 3;
break;
}
}
// Load in the text file containing the font data.
result = LoadFontData(fontFilename);
if (!result)
{
return false;
}
// Load the texture that has the font characters on it.
result = LoadTexture(device, deviceContext, fontTextureFilename);
if (!result)
{
return false;
}
return true;
}
void FontClass::Shutdown()
{
// Release the font texture.
ReleaseTexture();
// Release the font data.
ReleaseFontData();
return;
}
bool FontClass::LoadFontData(char* filename)
{
std::ifstream fin;
int i;
char temp;
// Create the font spacing buffer.
m_Font = new FontType[95];
// Read in the font size and spacing between chars.
fin.open(filename);
if (fin.fail())
{
return false;
}
// Read in the 95 used ascii characters for text.
for (i = 0; i < 95; i++)
{
fin.get(temp);
while (temp != ' ')
{
fin.get(temp);
}
fin.get(temp);
while (temp != ' ')
{
fin.get(temp);
}
fin >> m_Font[i].left;
fin >> m_Font[i].right;
fin >> m_Font[i].size;
}
// Close the file.
fin.close();
return true;
}
void FontClass::ReleaseFontData()
{
// Release the font data array.
if (m_Font)
{
delete[] m_Font;
m_Font = 0;
}
return;
}
bool FontClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
{
bool result;
// Create and initialize the font texture object.
m_Texture = new TextureClass;
result = m_Texture->Initialize(device, deviceContext, filename);
if (!result)
{
return false;
}
return true;
}
void FontClass::ReleaseTexture()
{
// Release the texture object.
if (m_Texture)
{
m_Texture->Shutdown();
delete m_Texture;
m_Texture = 0;
}
return;
}
ID3D11ShaderResourceView* FontClass::GetTexture()
{
return m_Texture->GetTexture();
}
void FontClass::BuildVertexArray(void* vertices, char* sentence, float drawX, float drawY)
{
VertexType* vertexPtr;
int numLetters, index, i, letter;
// Coerce the input vertices into a VertexType structure.
vertexPtr = (VertexType*)vertices;
// Get the number of letters in the sentence.
numLetters = (int)strlen(sentence);
// Initialize the index to the vertex array.
index = 0;
// Draw each letter onto a quad.
for (i = 0; i < numLetters; i++)
{
letter = ((int)sentence[i]) - 32;
// If the letter is a space then just move over three pixels.
if (letter == 0)
{
drawX = drawX + m_spaceSize;
}
else
{
// First triangle in quad.
vertexPtr[index].position = XMFLOAT3(drawX, drawY, 0.0f); // Top left.
vertexPtr[index].texture = XMFLOAT2(m_Font[letter].left, 0.0f);
index++;
vertexPtr[index].position = XMFLOAT3((drawX + m_Font[letter].size), (drawY - m_fontHeight), 0.0f); // Bottom right.
vertexPtr[index].texture = XMFLOAT2(m_Font[letter].right, 1.0f);
index++;
vertexPtr[index].position = XMFLOAT3(drawX, (drawY - m_fontHeight), 0.0f); // Bottom left.
vertexPtr[index].texture = XMFLOAT2(m_Font[letter].left, 1.0f);
index++;
// Second triangle in quad.
vertexPtr[index].position = XMFLOAT3(drawX, drawY, 0.0f); // Top left.
vertexPtr[index].texture = XMFLOAT2(m_Font[letter].left, 0.0f);
index++;
vertexPtr[index].position = XMFLOAT3(drawX + m_Font[letter].size, drawY, 0.0f); // Top right.
vertexPtr[index].texture = XMFLOAT2(m_Font[letter].right, 0.0f);
index++;
vertexPtr[index].position = XMFLOAT3((drawX + m_Font[letter].size), (drawY - m_fontHeight), 0.0f); // Bottom right.
vertexPtr[index].texture = XMFLOAT2(m_Font[letter].right, 1.0f);
index++;
// Update the x location for drawing by the size of the letter and one pixel.
drawX = drawX + m_Font[letter].size + 1.0f;
}
}
return;
}
int FontClass::GetSentencePixelLength(char* sentence)
{
int pixelLength, numLetters, i, letter;
pixelLength = 0;
numLetters = (int)strlen(sentence);
for (i = 0; i < numLetters; i++)
{
letter = ((int)sentence[i]) - 32;
// If the letter is a space then count it as three pixels.
if (letter == 0)
{
pixelLength += m_spaceSize;
}
else
{
pixelLength += (m_Font[letter].size + 1);
}
}
return pixelLength;
}
int FontClass::GetFontHeight()
{
return (int)m_fontHeight;
}

64
enginecustom/fontclass.h Normal file
View File

@ -0,0 +1,64 @@
#ifndef _FONTCLASS_H_
#define _FONTCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <directxmath.h>
#include <fstream>
using namespace DirectX;
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "textureclass.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: FontClass
////////////////////////////////////////////////////////////////////////////////
class FontClass
{
private:
struct FontType
{
float left, right;
int size;
};
struct VertexType
{
XMFLOAT3 position;
XMFLOAT2 texture;
};
public:
FontClass();
FontClass(const FontClass&);
~FontClass();
bool Initialize(ID3D11Device*, ID3D11DeviceContext*, int);
void Shutdown();
ID3D11ShaderResourceView* GetTexture();
void BuildVertexArray(void*, char*, float, float);
int GetSentencePixelLength(char*);
int GetFontHeight();
private:
bool LoadFontData(char*);
void ReleaseFontData();
bool LoadTexture(ID3D11Device*, ID3D11DeviceContext*, char*);
void ReleaseTexture();
private:
FontType* m_Font;
TextureClass* m_Texture;
float m_fontHeight;
int m_spaceSize;
};
#endif

View File

@ -0,0 +1,408 @@
#include "fontshaderclass.h"
FontShaderClass::FontShaderClass()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_matrixBuffer = 0;
m_sampleState = 0;
m_pixelBuffer = 0;
}
FontShaderClass::FontShaderClass(const FontShaderClass& other)
{
}
FontShaderClass::~FontShaderClass()
{
}
bool FontShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
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"font.vs");
if (error != 0)
{
return false;
}
// Set the filename of the pixel shader.
error = wcscpy_s(psFilename, 128, L"font.ps");
if (error != 0)
{
return false;
}
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, vsFilename, psFilename);
if (!result)
{
return false;
}
return true;
}
void FontShaderClass::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
return;
}
bool FontShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, XMFLOAT4 pixelColor)
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, pixelColor);
if (!result)
{
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
}
bool FontShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* pixelShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC pixelBufferDesc;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
pixelShaderBuffer = 0;
// Compile the vertex shader code.
result = D3DCompileFromFile(vsFilename, NULL, NULL, "FontVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
&vertexShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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, NULL, NULL, "FontPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
&pixelShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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(), NULL, &m_vertexShader);
if (FAILED(result))
{
return false;
}
// Create the pixel shader from the buffer.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
if (FAILED(result))
{
return false;
}
// Create the vertex input layout description.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].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 = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
// 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, NULL, &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 dynamic pixel constant buffer that is in the pixel shader.
pixelBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
pixelBufferDesc.ByteWidth = sizeof(PixelBufferType);
pixelBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
pixelBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
pixelBufferDesc.MiscFlags = 0;
pixelBufferDesc.StructureByteStride = 0;
// Create the pixel constant buffer pointer so we can access the pixel shader constant buffer from within this class.
result = device->CreateBuffer(&pixelBufferDesc, NULL, &m_pixelBuffer);
if (FAILED(result))
{
return false;
}
return true;
}
void FontShaderClass::ShutdownShader()
{
// Release the pixel constant buffer.
if (m_pixelBuffer)
{
m_pixelBuffer->Release();
m_pixelBuffer = 0;
}
// Release the sampler state.
if (m_sampleState)
{
m_sampleState->Release();
m_sampleState = 0;
}
// Release the matrix constant buffer.
if (m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the layout.
if (m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the pixel shader.
if (m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the vertex shader.
if (m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
return;
}
void FontShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned long long bufferSize, i;
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 = 0;
// 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);
return;
}
bool FontShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, XMFLOAT4 pixelColor)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBufferType* dataPtr;
unsigned int bufferNumber;
PixelBufferType* dataPtr2;
// 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);
// Set shader texture resource in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &texture);
// Lock the pixel constant buffer so it can be written to.
result = deviceContext->Map(m_pixelBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the pixel constant buffer.
dataPtr2 = (PixelBufferType*)mappedResource.pData;
// Copy the pixel color into the pixel constant buffer.
dataPtr2->pixelColor = pixelColor;
// Unlock the pixel constant buffer.
deviceContext->Unmap(m_pixelBuffer, 0);
// Set the position of the pixel constant buffer in the pixel shader.
bufferNumber = 0;
// Now set the pixel constant buffer in the pixel shader with the updated value.
deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_pixelBuffer);
return true;
}
void FontShaderClass::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, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
return;
}

View File

@ -0,0 +1,60 @@
#ifndef _FONTSHADERCLASS_H_
#define _FONTSHADERCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <d3d11.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <fstream>
using namespace DirectX;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Class name: FontShaderClass
////////////////////////////////////////////////////////////////////////////////
class FontShaderClass
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
struct PixelBufferType
{
XMFLOAT4 pixelColor;
};
public:
FontShaderClass();
FontShaderClass(const FontShaderClass&);
~FontShaderClass();
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4);
private:
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4);
void RenderShader(ID3D11DeviceContext*, int);
private:
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11Buffer* m_matrixBuffer;
ID3D11SamplerState* m_sampleState;
ID3D11Buffer* m_pixelBuffer;
};
#endif

46
enginecustom/fpsclass.cpp Normal file
View File

@ -0,0 +1,46 @@
#include "fpsclass.h"
FpsClass::FpsClass()
{
}
FpsClass::FpsClass(const FpsClass& other)
{
}
FpsClass::~FpsClass()
{
}
void FpsClass::Initialize()
{
m_fps = 0;
m_count = 0;
m_startTime = timeGetTime();
return;
}
void FpsClass::Frame()
{
m_count++;
if (timeGetTime() >= (m_startTime + 1000))
{
m_fps = m_count;
m_count = 0;
m_startTime = timeGetTime();
}
return;
}
int FpsClass::GetFps()
{
return m_fps;
}

36
enginecustom/fpsclass.h Normal file
View File

@ -0,0 +1,36 @@
#ifndef _FPSCLASS_H_
#define _FPSCLASS_H_
/////////////
// LINKING //
/////////////
#pragma comment(lib, "winmm.lib")
//////////////
// INCLUDES //
//////////////
#include <windows.h>
#include <mmsystem.h>
////////////////////////////////////////////////////////////////////////////////
// Class name: FpsClass
////////////////////////////////////////////////////////////////////////////////
class FpsClass
{
public:
FpsClass();
FpsClass(const FpsClass&);
~FpsClass();
void Initialize();
void Frame();
int GetFps();
private:
int m_fps, m_count;
unsigned long m_startTime;
};
#endif

View File

@ -2,18 +2,24 @@
// Filename: light.ps
////////////////////////////////////////////////////////////////////////////////
/////////////
// DEFINES //
/////////////
#define NUM_LIGHTS 4
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture : register(t0);
SamplerState SampleType : register(s0);
cbuffer LightBuffer
{
float4 ambientColor;
float3 lightDirection;
float padding;
float specularPower;
float4 specularColor;
};
cbuffer LightColorBuffer
{
@ -38,27 +44,29 @@ struct PixelInputType
////////////////////////////////////////////////////////////////////////////////
float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
float4 textureColor;
float lightIntensity[NUM_LIGHTS];
float4 colorArray[NUM_LIGHTS];
float4 colorSum;
float4 textureColor;
float3 lightDir;
float4 color;
int i;
float3 reflection;
float4 specular;
float lightIntensity[NUM_LIGHTS];
float4 colorArray[NUM_LIGHTS];
float4 colorSum;
int i;
// Sample the texture pixel at this location.
// Sample the pixel color from the texture using the sampler at this texture coordinate location.
textureColor = shaderTexture.Sample(SampleType, input.tex);
for(i=0; i<NUM_LIGHTS; i++)
{
// Calculate the different amounts of light on this pixel based on the positions of the lights.
lightIntensity[i] = saturate(dot(input.normal, input.lightPos[i]));
for(i=0; i<NUM_LIGHTS; i++)
{
// Calculate the different amounts of light on this pixel based on the positions of the lights.
lightIntensity[i] = saturate(dot(input.normal, input.lightPos[i]));
// Determine the diffuse color amount of each of the four lights.
colorArray[i] = diffuseColor[i] * lightIntensity[i];
}
// Determine the diffuse color amount of each of the four lights.
colorArray[i] = diffuseColor[i] * lightIntensity[i];
}
// Initialize the sum of colors.
// Initialize the sum of colors.
colorSum = float4(0.0f, 0.0f, 0.0f, 1.0f);
// Add all of the light colors up.
@ -69,8 +77,8 @@ float4 LightPixelShader(PixelInputType input) : SV_TARGET
colorSum.b += colorArray[i].b;
}
// Multiply the texture pixel by the combination of all four light colors to get the final result.
// Multiply the texture pixel by the combination of all four light colors to get the final result.
color = saturate(colorSum) * textureColor;
return color;
}
return color;
}

View File

@ -2,21 +2,25 @@
// Filename: light.vs
////////////////////////////////////////////////////////////////////////////////
/////////////
// DEFINES //
/////////////
#define NUM_LIGHTS 4
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};
cbuffer CameraBuffer
{
float3 cameraPosition;
float padding;
};
cbuffer LightPositionBuffer
@ -24,7 +28,6 @@ cbuffer LightPositionBuffer
float4 lightPosition[NUM_LIGHTS];
};
//////////////
// TYPEDEFS //
//////////////
@ -32,16 +35,16 @@ struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 normal : NORMAL;
};
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 lightPos[NUM_LIGHTS] : TEXCOORD1;
};
float3 normal : NORMAL;
float3 lightPos[NUM_LIGHTS] : TEXCOORD1;
};
////////////////////////////////////////////////////////////////////////////////
@ -51,37 +54,36 @@ PixelInputType LightVertexShader(VertexInputType input)
{
PixelInputType output;
float4 worldPosition;
int i;
int i;
// Change the position vector to be 4 units for proper matrix calculations.
// 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.
// Calculate the position of the vertex against the world, view, and projection matrices.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);
// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
// Calculate the normal vector against the world matrix only.
// Calculate the normal vector against the world matrix only.
output.normal = mul(input.normal, (float3x3)worldMatrix);
// Normalize the normal vector.
output.normal = normalize(output.normal);
// Calculate the position of the vertex in the world.
// Calculate the position of the vertex in the world.
worldPosition = mul(input.position, worldMatrix);
for(i=0; i<NUM_LIGHTS; i++)
{
// Determine the light positions based on the position of the lights and the position of the vertex in the world.
output.lightPos[i] = lightPosition[i].xyz - worldPosition.xyz;
for(i=0; i<NUM_LIGHTS; i++)
{
// Determine the light positions based on the position of the lights and the position of the vertex in the world.
output.lightPos[i] = lightPosition[i].xyz - worldPosition.xyz;
// Normalize the light position vectors.
output.lightPos[i] = normalize(output.lightPos[i]);
}
// Normalize the light position vectors.
output.lightPos[i] = normalize(output.lightPos[i]);
}
return output;
}

View File

@ -24,29 +24,38 @@ void LightClass::SetAmbientColor(float red, float green, float blue, float alpha
return;
}
void LightClass::SetDiffuseColor(float red, float green, float blue, float alpha)
{
m_diffuseColor = XMFLOAT4(red, green, blue, alpha);
return;
m_diffuseColor = XMFLOAT4(red, green, blue, alpha);
return;
}
void LightClass::SetDirection(float x, float y, float z)
{
m_direction = XMFLOAT3(x, y, z);
return;
m_direction = XMFLOAT3(x, y, z);
return;
}
void LightClass::SetSpecularColor(float red, float green, float blue, float alpha)
{
m_specularColor = XMFLOAT4(red, green, blue, alpha);
return;
m_specularColor = XMFLOAT4(red, green, blue, alpha);
return;
}
void LightClass::SetSpecularPower(float power)
{
m_specularPower = power;
return;
}
void LightClass::SetPosition(float x, float y, float z)
{
m_position = XMFLOAT4(x, y, z, 1.0f);
return;
m_position = XMFLOAT4(x, y, z, 1.0f);
return;
}
XMFLOAT4 LightClass::GetAmbientColor()
@ -57,29 +66,26 @@ XMFLOAT4 LightClass::GetAmbientColor()
XMFLOAT4 LightClass::GetDiffuseColor()
{
return m_diffuseColor;
return m_diffuseColor;
}
XMFLOAT3 LightClass::GetDirection()
{
return m_direction;
return m_direction;
}
XMFLOAT4 LightClass::GetSpecularColor()
{
return m_specularColor;
return m_specularColor;
}
float LightClass::GetSpecularPower()
{
return m_specularPower;
return m_specularPower;
}
XMFLOAT4 LightClass::GetPosition()
{
return m_position;
return m_position;
}

View File

@ -1,3 +1,4 @@
#pragma once
////////////////////////////////////////////////////////////////////////////////
// Filename: lightclass.h
////////////////////////////////////////////////////////////////////////////////
@ -18,9 +19,9 @@ using namespace DirectX;
class LightClass
{
public:
LightClass();
LightClass(const LightClass&);
~LightClass();
LightClass();
LightClass(const LightClass&);
~LightClass();
void SetAmbientColor(float, float, float, float);
void SetDiffuseColor(float, float, float, float);
@ -28,13 +29,14 @@ public:
void SetSpecularColor(float, float, float, float);
void SetSpecularPower(float);
void SetPosition(float, float, float);
XMFLOAT4 GetAmbientColor();
XMFLOAT4 GetDiffuseColor();
XMFLOAT3 GetDirection();
XMFLOAT4 GetSpecularColor();
float GetSpecularPower();
XMFLOAT4 GetPosition();
private:
XMFLOAT4 m_ambientColor;
XMFLOAT4 m_diffuseColor;

View File

@ -6,15 +6,15 @@
LightShaderClass::LightShaderClass()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_sampleState = 0;
m_matrixBuffer = 0;
m_lightBuffer = 0;
m_lightColorBuffer = 0;
m_lightPositionBuffer = 0;
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_sampleState = 0;
m_matrixBuffer = 0;
m_cameraBuffer = 0;
m_lightBuffer = 0;
m_lightColorBuffer = 0;
m_lightPositionBuffer = 0;
}
@ -30,181 +30,178 @@ LightShaderClass::~LightShaderClass()
bool LightShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
wchar_t vsFilename[128];
wchar_t psFilename[128];
int error;
bool result;
wchar_t vsFilename[128];
wchar_t psFilename[128];
int error;
bool result;
// Set the filename of the vertex shader.
error = wcscpy_s(vsFilename, 128, L"../enginecustom/light.vs");
error = wcscpy_s(vsFilename, 128, L"light.vs");
if (error != 0)
{
return false;
}
// Set the filename of the pixel shader.
error = wcscpy_s(psFilename, 128, L"../enginecustom/light.ps");
error = wcscpy_s(psFilename, 128, L"light.ps");
if (error != 0)
{
return false;
}
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, vsFilename, psFilename);
if (!result)
{
return false;
}
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, vsFilename, psFilename);
if(!result)
{
return false;
}
return true;
return true;
}
void LightShaderClass::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
return;
return;
}
bool LightShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
ID3D11ShaderResourceView* texture, XMFLOAT4 diffuseColor[], XMFLOAT4 lightPosition[])
ID3D11ShaderResourceView* texture, XMFLOAT4 diffuseColor[], XMFLOAT4 lightPosition[])
{
bool result;
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, diffuseColor, lightPosition);
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, diffuseColor, lightPosition);
if(!result)
{
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
return true;
}
bool LightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* pixelShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
unsigned int numElements;
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* pixelShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
unsigned int numElements;
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_BUFFER_DESC lightBufferDesc;
D3D11_BUFFER_DESC lightColorBufferDesc;
D3D11_BUFFER_DESC lightPositionBufferDesc;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_BUFFER_DESC cameraBufferDesc;
D3D11_BUFFER_DESC lightColorBufferDesc;
D3D11_BUFFER_DESC lightPositionBufferDesc;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
pixelShaderBuffer = 0;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
pixelShaderBuffer = 0;
// Compile the vertex shader code.
result = D3DCompileFromFile(vsFilename, NULL, NULL, "LightVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage);
if(FAILED(result))
{
// If the shader failed to compile it should have writen 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);
}
result = D3DCompileFromFile(vsFilename, NULL, NULL, "LightVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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;
}
return false;
}
// Compile the pixel shader code.
result = D3DCompileFromFile(psFilename, NULL, NULL, "LightPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage);
if(FAILED(result))
{
// If the shader failed to compile it should have writen 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);
}
result = D3DCompileFromFile(psFilename, NULL, NULL, "LightPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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;
}
return false;
}
// Create the vertex shader from the buffer.
result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader);
if(FAILED(result))
{
return false;
}
if (FAILED(result))
{
return false;
}
// Create the pixel shader from the buffer.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
if(FAILED(result))
{
return false;
}
if (FAILED(result))
{
return false;
}
// Create the vertex input layout description.
// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
// Create the vertex input layout description.
// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_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[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_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 = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[2].InputSlot = 0;
polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;
polygonLayout[2].SemanticName = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_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.
// 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;
}
// 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 = 0;
// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
vertexShaderBuffer->Release();
vertexShaderBuffer = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
// Create a texture sampler state description.
// 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;
@ -213,289 +210,307 @@ bool LightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR*
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.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
// Create the texture sampler state.
result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
if(FAILED(result))
{
return false;
}
if (FAILED(result))
{
return false;
}
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
// 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.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 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, NULL, &m_matrixBuffer);
if(FAILED(result))
{
return false;
}
// Setup the description of the dynamic constant buffer that is in the pixel shader.
lightColorBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightColorBufferDesc.ByteWidth = sizeof(LightColorBufferType);
lightColorBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightColorBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightColorBufferDesc.MiscFlags = 0;
lightColorBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
if (FAILED(result))
{
return false;
}
// Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
result = device->CreateBuffer(&lightColorBufferDesc, NULL, &m_lightColorBuffer);
if (FAILED(result))
{
return false;
}
// Setup the description of the dynamic constant buffer that is in the vertex shader.
lightPositionBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightPositionBufferDesc.ByteWidth = sizeof(LightPositionBufferType);
lightPositionBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightPositionBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightPositionBufferDesc.MiscFlags = 0;
lightPositionBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&lightPositionBufferDesc, NULL, &m_lightPositionBuffer);
if (FAILED(result))
{
return false;
}
// Setup the description of the light dynamic constant buffer that is in the pixel shader.
// Note that ByteWidth always needs to be a multiple of 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail.
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;
// Setup the description of the camera dynamic constant buffer that is in the vertex shader.
cameraBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
cameraBufferDesc.ByteWidth = sizeof(CameraBufferType);
cameraBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cameraBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cameraBufferDesc.MiscFlags = 0;
cameraBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&lightBufferDesc, NULL, &m_lightBuffer);
if(FAILED(result))
{
return false;
}
// Create the camera constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&cameraBufferDesc, NULL, &m_cameraBuffer);
if (FAILED(result))
{
return false;
}
return true;
// Setup the description of the dynamic constant buffer that is in the pixel shader.
lightColorBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightColorBufferDesc.ByteWidth = sizeof(LightColorBufferType);
lightColorBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightColorBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightColorBufferDesc.MiscFlags = 0;
lightColorBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
result = device->CreateBuffer(&lightColorBufferDesc, NULL, &m_lightColorBuffer);
if (FAILED(result))
{
return false;
}
// Setup the description of the dynamic constant buffer that is in the vertex shader.
lightPositionBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightPositionBufferDesc.ByteWidth = sizeof(LightPositionBufferType);
lightPositionBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightPositionBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightPositionBufferDesc.MiscFlags = 0;
lightPositionBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&lightPositionBufferDesc, NULL, &m_lightPositionBuffer);
if (FAILED(result))
{
return false;
}
return true;
}
void LightShaderClass::ShutdownShader()
{
// Release the light constant buffers.
if (m_lightColorBuffer)
{
m_lightColorBuffer->Release();
m_lightColorBuffer = 0;
}
// Release the light constant buffers.
if (m_lightColorBuffer)
{
m_lightColorBuffer->Release();
m_lightColorBuffer = 0;
}
if (m_lightPositionBuffer)
{
m_lightPositionBuffer->Release();
m_lightPositionBuffer = 0;
}
// Release the light constant buffer.
if(m_lightBuffer)
{
m_lightBuffer->Release();
m_lightBuffer = 0;
}
if (m_lightPositionBuffer)
{
m_lightPositionBuffer->Release();
m_lightPositionBuffer = 0;
}
// Release the matrix constant buffer.
if(m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the light constant buffer.
if (m_lightBuffer)
{
m_lightBuffer->Release();
m_lightBuffer = 0;
}
// Release the sampler state.
if(m_sampleState)
{
m_sampleState->Release();
m_sampleState = 0;
}
// Release the camera constant buffer.
if (m_cameraBuffer)
{
m_cameraBuffer->Release();
m_cameraBuffer = 0;
}
// Release the layout.
if(m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the matrix constant buffer.
if (m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the pixel shader.
if(m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the sampler state.
if (m_sampleState)
{
m_sampleState->Release();
m_sampleState = 0;
}
// Release the vertex shader.
if(m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
// Release the layout.
if (m_layout)
{
m_layout->Release();
m_layout = 0;
}
return;
// Release the pixel shader.
if (m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the vertex shader.
if (m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
return;
}
void LightShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned __int64 bufferSize, i;
ofstream fout;
char* compileErrors;
unsigned __int64 bufferSize, i;
ofstream fout;
// Get a pointer to the error message text buffer.
compileErrors = (char*)(errorMessage->GetBufferPointer());
// Get a pointer to the error message text buffer.
compileErrors = (char*)(errorMessage->GetBufferPointer());
// Get the length of the message.
bufferSize = errorMessage->GetBufferSize();
// Get the length of the message.
bufferSize = errorMessage->GetBufferSize();
// Open a file to write the error message to.
fout.open("shader-error.txt");
// 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];
}
// Write out the error message.
for (i = 0; i < bufferSize; i++)
{
fout << compileErrors[i];
}
// Close the file.
fout.close();
// Close the file.
fout.close();
// Release the error message.
errorMessage->Release();
errorMessage = 0;
// Release the error message.
errorMessage->Release();
errorMessage = 0;
// 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);
// 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);
return;
return;
}
bool LightShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
ID3D11ShaderResourceView* texture, XMFLOAT4 diffuseColor[], XMFLOAT4 lightPosition[])
ID3D11ShaderResourceView* texture, XMFLOAT4 diffuseColor[], XMFLOAT4 lightPosition[])
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
unsigned int bufferNumber;
MatrixBufferType* dataPtr;
LightPositionBufferType* dataPtr2;
LightColorBufferType* dataPtr3;
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
unsigned int bufferNumber;
MatrixBufferType* dataPtr;
LightPositionBufferType* dataPtr2;
LightColorBufferType* dataPtr3;
// 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;
// Now set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
// Lock the camera constant buffer so it can be written to.
result = deviceContext->Map(m_cameraBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Lock the light position constant buffer so it can be written to.
result = deviceContext->Map(m_lightPositionBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr2 = (LightPositionBufferType*)mappedResource.pData;
// Copy the light position variables into the constant buffer.
dataPtr2->lightPosition[0] = lightPosition[0];
dataPtr2->lightPosition[1] = lightPosition[1];
dataPtr2->lightPosition[2] = lightPosition[2];
dataPtr2->lightPosition[3] = lightPosition[3];
// Unlock the constant buffer.
deviceContext->Unmap(m_lightPositionBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 1;
// Finally set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_lightPositionBuffer);
// Set shader texture resource in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &texture);
// Lock the light color constant buffer so it can be written to.
result = deviceContext->Map(m_lightColorBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr3 = (LightColorBufferType*)mappedResource.pData;
// Copy the light color variables into the constant buffer.
dataPtr3->diffuseColor[0] = diffuseColor[0];
dataPtr3->diffuseColor[1] = diffuseColor[1];
dataPtr3->diffuseColor[2] = diffuseColor[2];
dataPtr3->diffuseColor[3] = diffuseColor[3];
// Unlock the constant buffer.
deviceContext->Unmap(m_lightColorBuffer, 0);
// Set the position of the constant buffer in the pixel shader.
bufferNumber = 0;
// Finally set the constant buffer in the pixel shader with the updated values.
deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightColorBuffer);
// 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;
// Now set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
// Lock the light position constant buffer so it can be written to.
result = deviceContext->Map(m_lightPositionBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr2 = (LightPositionBufferType*)mappedResource.pData;
// Copy the light position variables into the constant buffer.
dataPtr2->lightPosition[0] = lightPosition[0];
dataPtr2->lightPosition[1] = lightPosition[1];
dataPtr2->lightPosition[2] = lightPosition[2];
dataPtr2->lightPosition[3] = lightPosition[3];
// Unlock the constant buffer.
deviceContext->Unmap(m_lightPositionBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 1;
// Finally set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_lightPositionBuffer);
// Set shader texture resource in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &texture);
// Lock the light color constant buffer so it can be written to.
result = deviceContext->Map(m_lightColorBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr3 = (LightColorBufferType*)mappedResource.pData;
// Copy the light color variables into the constant buffer.
dataPtr3->diffuseColor[0] = diffuseColor[0];
dataPtr3->diffuseColor[1] = diffuseColor[1];
dataPtr3->diffuseColor[2] = diffuseColor[2];
dataPtr3->diffuseColor[3] = diffuseColor[3];
// Unlock the constant buffer.
deviceContext->Unmap(m_lightColorBuffer, 0);
// Set the position of the constant buffer in the pixel shader.
bufferNumber = 0;
// Finally set the constant buffer in the pixel shader with the updated values.
deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightColorBuffer);
return true;
return true;
}
void LightShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
// Set the vertex input layout.
deviceContext->IASetInputLayout(m_layout);
// 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, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
return;
}
return;
}

View File

@ -4,12 +4,12 @@
#ifndef _LIGHTSHADERCLASS_H_
#define _LIGHTSHADERCLASS_H_
/////////////
// GLOBALS //
/////////////
const int NUM_LIGHTS = 4;
//////////////
// INCLUDES //
//////////////
@ -27,58 +27,66 @@ using namespace std;
class LightShaderClass
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
struct LightColorBufferType
{
XMFLOAT4 diffuseColor[NUM_LIGHTS];
};
struct LightPositionBufferType
{
XMFLOAT4 lightPosition[NUM_LIGHTS];
};
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
struct CameraBufferType
{
XMFLOAT3 cameraPosition;
float padding;
};
struct LightBufferType
{
XMFLOAT4 ambientColor;
XMFLOAT4 diffuseColor;
XMFLOAT3 lightDirection;
float padding; // Added extra padding so structure is a multiple of 16 for CreateBuffer function requirements.
float specularPower;
XMFLOAT4 specularColor;
};
struct LightColorBufferType
{
XMFLOAT4 diffuseColor[NUM_LIGHTS];
};
struct LightPositionBufferType
{
XMFLOAT4 lightPosition[NUM_LIGHTS];
};
public:
LightShaderClass();
LightShaderClass(const LightShaderClass&);
~LightShaderClass();
LightShaderClass();
LightShaderClass(const LightShaderClass&);
~LightShaderClass();
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4[], XMFLOAT4[]);
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4[], XMFLOAT4[]);
private:
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4[], XMFLOAT4[]);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT4[], XMFLOAT4[]);
void RenderShader(ID3D11DeviceContext*, int);
private:
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11SamplerState* m_sampleState;
ID3D11Buffer* m_matrixBuffer;
ID3D11Buffer* m_lightBuffer;
ID3D11Buffer* m_lightColorBuffer;
ID3D11Buffer* m_lightPositionBuffer;
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11SamplerState* m_sampleState;
ID3D11Buffer* m_matrixBuffer;
ID3D11Buffer* m_cameraBuffer;
ID3D11Buffer* m_lightBuffer;
ID3D11Buffer* m_lightColorBuffer;
ID3D11Buffer* m_lightPositionBuffer;
};
#endif

View File

@ -5,7 +5,7 @@ ModelClass::ModelClass()
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
m_Texture = 0;
m_Textures = 0;
m_model = 0;
}
@ -19,7 +19,7 @@ ModelClass::~ModelClass()
{
}
bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* modelFilename, char* textureFilename)
bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* modelFilename, char* textureFilename1, char* textureFilename2)
{
bool result;
@ -36,8 +36,8 @@ bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceCon
{
return false;
}
// Load the texture for this model.
result = LoadTexture(device, deviceContext, textureFilename);
// Load the textures for this model.
result = LoadTextures(device, deviceContext, textureFilename1, textureFilename2);
if (!result)
{
return false;
@ -49,8 +49,8 @@ bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceCon
void ModelClass::Shutdown()
{
// Release the model texture.
ReleaseTexture();
// Release the model textures.
ReleaseTextures();
// Shutdown the vertex and index buffers.
ShutdownBuffers();
@ -76,9 +76,9 @@ int ModelClass::GetIndexCount()
return m_indexCount;
}
ID3D11ShaderResourceView* ModelClass::GetTexture()
ID3D11ShaderResourceView* ModelClass::GetTexture(int index)
{
return m_Texture->GetTexture();
return m_Textures[index].GetTexture();
}
@ -89,7 +89,7 @@ bool ModelClass::InitializeBuffers(ID3D11Device* device)
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
int i;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
@ -98,7 +98,7 @@ bool ModelClass::InitializeBuffers(ID3D11Device* device)
indices = new unsigned long[m_indexCount];
// Load the vertex array and index array with data.
for (int i = 0; i < m_vertexCount; i++)
for (i = 0; i < m_vertexCount; i++)
{
vertices[i].position = XMFLOAT3(m_model[i].x, m_model[i].y, m_model[i].z);
vertices[i].texture = XMFLOAT2(m_model[i].tu, m_model[i].tv);
@ -107,31 +107,6 @@ bool ModelClass::InitializeBuffers(ID3D11Device* device)
indices[i] = i;
}
//// Create the vertex array.
//vertices = new VertexType[m_vertexCount];
//// Create the index array.
//indices = new unsigned long[m_indexCount];
//// Load the vertex array with data.
//vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f); // Bottom left.
//vertices[0].texture = XMFLOAT2(0.0f, 1.0f);
//vertices[0].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
//vertices[1].position = XMFLOAT3(0.0f, 1.0f, 0.0f); // Top middle.
//vertices[1].texture = XMFLOAT2(0.5f, 0.0f);
//vertices[1].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
//vertices[2].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // Bottom right.
//vertices[2].texture = XMFLOAT2(1.0f, 1.0f);
//vertices[2].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
//// Load the index array with data.
//indices[0] = 0; // Bottom left.
//indices[1] = 1; // Top middle.
//indices[2] = 2; // Bottom right.
// Set up the description of the static vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
@ -225,15 +200,21 @@ void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
return;
}
bool ModelClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
bool ModelClass::LoadTextures(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename1, char* filename2)
{
bool result;
// Create and initialize the texture object.
m_Texture = new TextureClass;
// Create and initialize the texture object array.
m_Textures = new TextureClass[2];
result = m_Texture->Initialize(device, deviceContext, filename);
result = m_Textures[0].Initialize(device, deviceContext, filename1);
if (!result)
{
return false;
}
result = m_Textures[1].Initialize(device, deviceContext, filename2);
if (!result)
{
return false;
@ -242,14 +223,16 @@ bool ModelClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceCo
return true;
}
void ModelClass::ReleaseTexture()
void ModelClass::ReleaseTextures()
{
// Release the texture object.
if (m_Texture)
// Release the texture object array.
if (m_Textures)
{
m_Texture->Shutdown();
delete m_Texture;
m_Texture = 0;
m_Textures[0].Shutdown();
m_Textures[1].Shutdown();
delete[] m_Textures;
m_Textures = 0;
}
return;

View File

@ -8,7 +8,9 @@
#include <d3d11.h>
#include <directxmath.h>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace DirectX;
using namespace std;
@ -39,35 +41,50 @@ protected:
float nx, ny, nz;
};
struct Vertex {
float x, y, z;
};
struct Texture {
float u, v;
};
struct Normal {
float nx, ny, nz;
};
struct Face {
int v1, v2, v3;
int t1, t2, t3;
int n1, n2, n3;
};
public:
ModelClass();
ModelClass(const ModelClass&);
~ModelClass();
bool Initialize(ID3D11Device*, ID3D11DeviceContext*, char*, char*);
bool Initialize(ID3D11Device*, ID3D11DeviceContext*, char*, char*, char*);
void Shutdown();
void Render(ID3D11DeviceContext*);
int GetIndexCount();
ID3D11ShaderResourceView* GetTexture();
ID3D11ShaderResourceView* GetTexture(int);
private:
bool InitializeBuffers(ID3D11Device*);
void ShutdownBuffers();
void RenderBuffers(ID3D11DeviceContext*);
bool LoadTexture(ID3D11Device*, ID3D11DeviceContext*, char*);
void ReleaseTexture();
bool LoadTextures(ID3D11Device*, ID3D11DeviceContext*, char*, char*);
void ReleaseTextures();
bool LoadModel(char*);
void ReleaseModel();
private:
ID3D11Buffer* m_vertexBuffer, * m_indexBuffer;
TextureClass* m_Texture;
protected:
int m_vertexCount, m_indexCount;
TextureClass* m_Textures;
ModelType* m_model;
int m_vertexCount, m_indexCount;
};

BIN
enginecustom/moss01.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 MiB

BIN
enginecustom/papier.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1020 KiB

3754
enginecustom/plane.txt Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

14704
enginecustom/sphere.txt Normal file

File diff suppressed because it is too large Load Diff

BIN
enginecustom/sprite01.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
enginecustom/sprite02.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
enginecustom/sprite03.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
enginecustom/sprite04.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -0,0 +1,6 @@
4
sprite01.tga
sprite02.tga
sprite03.tga
sprite04.tga
250

250
enginecustom/textclass.cpp Normal file
View File

@ -0,0 +1,250 @@
#include "textclass.h"
TextClass::TextClass()
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
}
TextClass::TextClass(const TextClass& other)
{
}
TextClass::~TextClass()
{
}
bool TextClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, int screenWidth, int screenHeight, int maxLength, FontClass* Font, char* text,
int positionX, int positionY, float red, float green, float blue)
{
bool result;
// Store the screen width and height.
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
// Store the maximum length of the sentence.
m_maxLength = maxLength;
// Initalize the sentence.
result = InitializeBuffers(device, deviceContext, Font, text, positionX, positionY, red, green, blue);
if (!result)
{
return false;
}
return true;
}
void TextClass::Shutdown()
{
// Release the vertex and index buffers.
ShutdownBuffers();
return;
}
void TextClass::Render(ID3D11DeviceContext* deviceContext)
{
// Put the vertex and index buffers on the graphics pipeline to prepare them for drawing.
RenderBuffers(deviceContext);
return;
}
int TextClass::GetIndexCount()
{
return m_indexCount;
}
bool TextClass::InitializeBuffers(ID3D11Device* device, ID3D11DeviceContext* deviceContext, FontClass* Font, char* text, int positionX, int positionY, float red, float green, float blue)
{
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
int i;
// Set the vertex and index count.
m_vertexCount = 6 * m_maxLength;
m_indexCount = m_vertexCount;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
// Create the index array.
indices = new unsigned long[m_indexCount];
// Initialize vertex array to zeros at first.
memset(vertices, 0, (sizeof(VertexType) * m_vertexCount));
// Initialize the index array.
for (i = 0; i < m_indexCount; i++)
{
indices[i] = i;
}
// Set up the description of the dynamic vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Create the vertex buffer.
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer);
if (FAILED(result))
{
return false;
}
// Set up the description of the static index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer);
if (FAILED(result))
{
return false;
}
// Release the vertex array as it is no longer needed.
delete[] vertices;
vertices = 0;
// Release the index array as it is no longer needed.
delete[] indices;
indices = 0;
// Now add the text data to the sentence buffers.
result = UpdateText(deviceContext, Font, text, positionX, positionY, red, green, blue);
if (!result)
{
return false;
}
return true;
}
void TextClass::ShutdownBuffers()
{
// Release the index buffer.
if (m_indexBuffer)
{
m_indexBuffer->Release();
m_indexBuffer = 0;
}
// Release the vertex buffer.
if (m_vertexBuffer)
{
m_vertexBuffer->Release();
m_vertexBuffer = 0;
}
return;
}
bool TextClass::UpdateText(ID3D11DeviceContext* deviceContext, FontClass* Font, char* text, int positionX, int positionY, float red, float green, float blue)
{
int numLetters;
VertexType* vertices;
float drawX, drawY;
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
VertexType* verticesPtr;
// Store the color of the sentence.
m_pixelColor = XMFLOAT4(red, green, blue, 1.0f);
// Get the number of letters in the sentence.
numLetters = (int)strlen(text);
// Check for possible buffer overflow.
if (numLetters > m_maxLength)
{
return false;
}
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
// Initialize vertex array to zeros at first.
memset(vertices, 0, (sizeof(VertexType) * m_vertexCount));
// Calculate the X and Y pixel position on the screen to start drawing to.
drawX = (float)(((m_screenWidth / 2) * -1) + positionX);
drawY = (float)((m_screenHeight / 2) - positionY);
// Use the font class to build the vertex array from the sentence text and sentence draw location.
Font->BuildVertexArray((void*)vertices, text, drawX, drawY);
// Lock the vertex buffer so it can be written to.
result = deviceContext->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// Get a pointer to the data in the vertex buffer.
verticesPtr = (VertexType*)mappedResource.pData;
// Copy the data into the vertex buffer.
memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * m_vertexCount));
// Unlock the vertex buffer.
deviceContext->Unmap(m_vertexBuffer, 0);
// Release the vertex array as it is no longer needed.
delete[] vertices;
vertices = 0;
return true;
}
void TextClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
unsigned int stride, offset;
// Set vertex buffer stride and offset.
stride = sizeof(VertexType);
offset = 0;
// Set the vertex buffer to active in the input assembler so it can be rendered.
deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
// Set the index buffer to active in the input assembler so it can be rendered.
deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
return;
}
XMFLOAT4 TextClass::GetPixelColor()
{
return m_pixelColor;
}

48
enginecustom/textclass.h Normal file
View File

@ -0,0 +1,48 @@
#ifndef _TEXTCLASS_H_
#define _TEXTCLASS_H_
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "fontclass.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: TextClass
////////////////////////////////////////////////////////////////////////////////
class TextClass
{
private:
struct VertexType
{
XMFLOAT3 position;
XMFLOAT2 texture;
};
public:
TextClass();
TextClass(const TextClass&);
~TextClass();
bool Initialize(ID3D11Device*, ID3D11DeviceContext*, int, int, int, FontClass*, char*, int, int, float, float, float);
void Shutdown();
void Render(ID3D11DeviceContext*);
int GetIndexCount();
bool UpdateText(ID3D11DeviceContext*, FontClass*, char*, int, int, float, float, float);
XMFLOAT4 GetPixelColor();
private:
bool InitializeBuffers(ID3D11Device*, ID3D11DeviceContext*, FontClass*, char*, int, int, float, float, float);
void ShutdownBuffers();
void RenderBuffers(ID3D11DeviceContext*);
private:
ID3D11Buffer* m_vertexBuffer, * m_indexBuffer;
int m_screenWidth, m_screenHeight, m_maxLength, m_vertexCount, m_indexCount;
XMFLOAT4 m_pixelColor;
};
#endif

28
enginecustom/texture.ps Normal file
View File

@ -0,0 +1,28 @@
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture : register(t0);
SamplerState SampleType : register(s0);
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
};
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 TexturePixelShader(PixelInputType input) : SV_TARGET
{
float4 textureColor;
// Sample the pixel color from the texture using the sampler at this texture coordinate location.
textureColor = shaderTexture.Sample(SampleType, input.tex);
return textureColor;
}

47
enginecustom/texture.vs Normal file
View File

@ -0,0 +1,47 @@
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
};
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
};
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType TextureVertexShader(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.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);
// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
return output;
}

View File

@ -0,0 +1,357 @@
#include "textureshaderclass.h"
TextureShaderClass::TextureShaderClass()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_matrixBuffer = 0;
m_sampleState = 0;
}
TextureShaderClass::TextureShaderClass(const TextureShaderClass& other)
{
}
TextureShaderClass::~TextureShaderClass()
{
}
bool TextureShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
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"texture.vs");
if (error != 0)
{
return false;
}
// Set the filename of the pixel shader.
error = wcscpy_s(psFilename, 128, L"texture.ps");
if (error != 0)
{
return false;
}
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, vsFilename, psFilename);
if (!result)
{
return false;
}
return true;
}
void TextureShaderClass::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
return;
}
bool TextureShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture);
if (!result)
{
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
}
bool TextureShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* pixelShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_SAMPLER_DESC samplerDesc;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
pixelShaderBuffer = 0;
// Compile the vertex shader code.
result = D3DCompileFromFile(vsFilename, NULL, NULL, "TextureVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
&vertexShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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, NULL, NULL, "TexturePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
&pixelShaderBuffer, &errorMessage);
if (FAILED(result))
{
// If the shader failed to compile it should have writen 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(), NULL, &m_vertexShader);
if (FAILED(result))
{
return false;
}
// Create the pixel shader from the buffer.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
if (FAILED(result))
{
return false;
}
// Create the vertex input layout description.
// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].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 = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
// 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, NULL, &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;
}
return true;
}
void TextureShaderClass::ShutdownShader()
{
// Release the sampler state.
if (m_sampleState)
{
m_sampleState->Release();
m_sampleState = 0;
}
// Release the matrix constant buffer.
if (m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the layout.
if (m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the pixel shader.
if (m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the vertex shader.
if (m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
return;
}
void TextureShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned long long bufferSize, i;
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 = 0;
// 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);
return;
}
bool TextureShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBufferType* dataPtr;
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;
// Finanly set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
// Set shader texture resource in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &texture);
return true;
}
void TextureShaderClass::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, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
return;
}

View File

@ -0,0 +1,54 @@
#ifndef _TEXTURESHADERCLASS_H_
#define _TEXTURESHADERCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <d3d11.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <fstream>
using namespace DirectX;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Class name: TextureShaderClass
////////////////////////////////////////////////////////////////////////////////
class TextureShaderClass
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
public:
TextureShaderClass();
TextureShaderClass(const TextureShaderClass&);
~TextureShaderClass();
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*);
private:
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*);
void RenderShader(ID3D11DeviceContext*, int);
private:
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11Buffer* m_matrixBuffer;
ID3D11SamplerState* m_sampleState;
};
#endif

BIN
enginecustom/wall.tga Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 768 KiB