텍스쳐를 사용하면 도형 표면에 사진과 다른 이미즐ㄹ 적용하여 더욱 현실적인 장면을 연출할 수 있습니다. 아래와 같은 사진을 이용하여 작성해보겠습니다.
이 이미지를 지난 삼각형에 덮어씌어주면 아래와 같은 이미지로 도형 표면이 변하게 됩니다.
이번에 사용할 이미지 형식은 .tga 파일입니다. 이것은 R,G,B 그리고 A(알파채널)을 지원하는 일반적인 그래픽 형식입니다. 일반적으로 모든 이미지 편집 소프트웨어를 사용하여 targa 파일을 만들고 편집 할 수 있습니다. 그리고 파일 형식은 대부분 간단합니다.
코드에 들어가기 전에 텍스쳐 매핑이 어떻게 작동하고 있는지 구조를 확인해야 합니다. .tga 이미지의 픽셀을 도형에 매핑하기 위해 텍셀 좌표계(Texel Coordinate System)를 사용합니다. 이 시스템은 픽셀 정수값을 0.0f에서 1.0f 사이의 부동소수점 값으로 변환합니다. 예를 들어, 텍스처 폭이 256 픽셀의 경우, 최초의 픽셀은 0.0f, 256 번째은 1.0f, 128 중간 픽셀은 0.5f에 매핑됩니다.
텍셀 좌표계의 이해
텍셀 좌표계의 이해를 돕기위해 아래 그림을 통해 설명 하도록 하겠습니다.
텍셀 좌표계에서 너비(가로)의 값의 이름은 "U"이고 높이(세로) 값의 이름은 "V" 입니다. 너비는 왼쪽에서 0.0, 오른쪽으로 1.0이 됩니다. 높이는 맨 위의 0.0ㄹ에서 맨 아래의 1.0ㄹ까지 아래쪽으로 높아집니다. 예를 들어 왼쪽 상단은 U 0.0 V 0.0 으로 표시되고 오른쪽 하단은 U 1.0, V1.0 으로 표시됩니다.
프레임워크 업데이트
지난번 때와 달라진 점은 ModelClass 안에 TextureClass라는 클래스가 들어왔고, ColorShaderClass를 TextureShaderClass라는 클래스가 대체했다는 것입니다. 우선 텍스쳐 쉐이더를 보겠습니다.
TextureVertex.hlsl
/////////////
// 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;
};
////////////////////
// Vertext Shader //
////////////////////
PixelInputType TextureVertexShader(VertexInputType input)
{
PixelInputType output;
// 적절한 행렬 계산을 위해 위치 벡터를 4 단위로 변경합니다.
input.position.w = 1.0f;
// 월드, 뷰 및 투영 행렬에 대한 정점의 위치를 계산합니다.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);
// 픽셀 쉐이더의 텍스쳐 좌표를 저장합니다.
output.tex = input.tex;
return output;
}
이제 더이상 정점에 색상을 사용하지 않고 텍스쳐 좌표를 사용하게 될 것입니다. 텍스쳐에서는 U와 V좌표만을 사용하기 때문에 이를 표현하기 위해 float2 자료형을 이용합니다. 정점 쉐이더와 픽셀 쉐이더에서 텍스쳐 좌표를 나타내기 위해 TEXCOORD0 이라는 것을 사용합니다. 여러 개의 텍스쳐 좌표가 가능하다면 그 값을 0부터 아무 숫자로나 지정할 수도 있습니다.
이전에 컬러 버텍스 쉐이더와 비교하여 텍스처 버텍스 쉐이더의 유일한 차이점은 입력 버텍스에서 색상의 복사본을 얻는 대신 테스쳐 좌표의 복사본을 가져 와서 픽셀 쉐이더로 전달한다는 것입니다.
TexturePixel.hlsl
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture;
SamplerState SampleType;
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
};
//////////////////
// Pixel Shader //
//////////////////
float4 TexturePixelShader(PixelInputType input) : SV_Target
{
float4 textureColor;
// 이 텍스쳐 좌표를 위치에서 샘플러를 사용하여 텍스처에서 픽셀 색상을 샘플링합니다.
textureColor = shaderTexture.Sample(SampleType, input.tex);
return textureColor;
}
텍스쳐 픽셀 쉐이더에는 두개의 전역변수가 있습니다. 첫번째는 텍스쳐 그 자체인 Texture2D shaderTexture입니다. 이것은 텍스쳐 자원으로서 모델에 텍스쳐를 그릴 때 사용될 것입니다. 두번째 새 변수는 SaplerState SampleType 입니다. 샘플러 상태(SamplerState)는 도형에 쉐이딩이 이루어질 때 어떻게 텍스쳐의 픽셀이 씌어지는 지를 수정할 수 있게 해 줍니다. 일례로 너무 멀리 있어 겨우 8픽셀 만큼의 영역을 차지하는 도형의 경우 이 샘플러 상태를 사용하여, 원래 텍스쳐의 어떤 픽셀 혹은 어떤 픽셀 조합을 사용해야 할지 결정합니다. 그 원본 텍스쳐는 256x256 픽셀의 크기일 수도 있으므로 매우 작아보이는 도형의 품질과 관련하여 이 결정은 매우 중요합니다. 이 샘플러 상태를 TextureShaderClass 클래스에 만들고 연결하여 픽셀 쉐이더에서 이를 이용할 수 있게 할 것입니다.
픽셀 쉐이더가 HLSL의 샘플링 함수를 사용하도록 수정되었습니다. 샘플링 함수(Sample Funtion)은 위에서 정의한 샘플러 상태와 텍스쳐 좌표를 사용합니다. 도형의 표면 UV좌표 위치에 들어갈 픽셀 값을 결정하고 반환하기 위해 이 두 변수를 사용합니다.
다음은 TExtureShaderClass에 대해 알아보겠습니다. TextureShaderClass는 이전 ColorShaderClass의 업데이트 된 버전입니다. 이 클래스는 정점 및 픽셀 쉐이더르 사용하여 3D 모델을 그리는 데 사용됩니다.
TextureShaderClass
#pragma once
class TextureShaderClass : public AlignedAllocationPolicy<16>
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
public:
TextureShaderClass();
TextureShaderClass(const TextureShaderClass& other);
~TextureShaderClass();
bool Initialize(ID3D11Device* device, HWND hwnd);
void ShutDown();
bool Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture);
private:
bool InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFileName, WCHAR* psFileName);
void ShutdownShader();
bool OutputShaderErrorMessage(ID3D10Blob* blob, HWND hwnd, WCHAR* shaderFileName);
bool SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture);
void RenderShader(ID3D11DeviceContext* deviceContext, int indexCount);
private:
ID3D11VertexShader* _vertexShader = nullptr;
ID3D11PixelShader* _pixelShader = nullptr;
ID3D11InputLayout* _layout = nullptr;
ID3D11Buffer* _matrixBuffer = nullptr;
ID3D11SamplerState* _sampleState = nullptr;
};
#include "stdafx.h"
#include "TextureShaderClass.h"
TextureShaderClass::TextureShaderClass()
{
}
TextureShaderClass::TextureShaderClass(const TextureShaderClass& other)
{
}
TextureShaderClass::~TextureShaderClass()
{
}
bool TextureShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
// 정점 및 픽셀 쉐이더를 초기화합니다.
return InitializeShader(device, hwnd, L"Shader/TextureVertex.hlsl", L"Shader/TexturePixel.hlsl");
}
void TextureShaderClass::ShutDown()
{
// 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
ShutdownShader();
}
bool TextureShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
{
// 렌더링에 사용할 쉐이더 매개 변수를 설정합니다.
if (SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture) == false)
{
return false;
}
// 설정된 버퍼를 쉐이더로 렌더링합니다.
RenderShader(deviceContext, indexCount);
return true;
}
bool TextureShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFileName, WCHAR* psFileName)
{
HRESULT result;
ID3D10Blob* errorMessage = nullptr;
// 버텍스 쉐이더 코드를 컴파일 합니다.
ID3D10Blob* vertexShaderBuffer = nullptr;
result = D3DCompileFromFile(vsFileName, NULL, NULL, "TextureVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage);
if (FAILED(result))
{
// 셰이더 컴파일 실패시 오류메시지를 출력합니다.
if (errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, vsFileName);
}
// 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
else
{
MessageBox(hwnd, vsFileName, L"Missing Shader File", MB_OK);
}
return false;
}
// 픽셀 쉐이더 코드를 컴파일합니다.
ID3D10Blob* pixelShaderBuffer = nullptr;
result = D3DCompileFromFile(psFileName, NULL, NULL, "TexturePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage);
if (FAILED(result))
{
// 셰이더 컴파일 실패시 오류메시지를 출력합니다.
if (errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, psFileName);
}
// 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
else
{
MessageBox(hwnd, psFileName, L"Missing Shader File", MB_OK);
}
return false;
}
// 버퍼에서 정점 쉐이더를 생성합니다.
result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &_vertexShader);
if (FAILED(result))
{
return false;
}
// 버퍼에서 픽셀 쉐이더를 생성합니다.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &_pixelShader);
if (FAILED(result))
{
return false;
}
// 정점 입력 레이아웃 구조체를 설정합니다.
// 이 설정은 ModelCalss 와 쉐이더의 VertexType 구조와 일치해야 합니다.
D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
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;
// 레이아웃의 요소 수를 가져옵니다.
UINT numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// 정점 입력 레이아웃을 만듭니다.
result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &_layout);
if (FAILED(result))
{
return false;
}
// 더 이상 사용되지 않는 정점 쉐이더 버퍼와 픽셀 쉐이더 버퍼를 해제합니다.
SAFE_RELEASE(vertexShaderBuffer);
SAFE_RELEASE(pixelShaderBuffer);
// 정점 쉐이더에 있는 행렬 상수 버퍼의 구조체를 작성합니다.
D3D11_BUFFER_DESC matrixBufferDesc;
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;
// 상수 버퍼 포인터를 만들어 이 클래스에서 정점 쉐이더 상수 버퍼에 접근할 수 있게 합니다.
result = device->CreateBuffer(&matrixBufferDesc, NULL, &_matrixBuffer);
if (FAILED(result))
{
return false;
}
// 텍스쳐 샘플러 상태 구조체를 생성 및 설정합니다.
D3D11_SAMPLER_DESC samplerDesc;
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;
// 텍스처 샘플러 상태를 만듭니다.
result = device->CreateSamplerState(&samplerDesc, &_sampleState);
if (FAILED(result))
{
return false;
}
return true;
}
void TextureShaderClass::ShutdownShader()
{
SAFE_RELEASE(_sampleState);
SAFE_RELEASE(_matrixBuffer);
SAFE_RELEASE(_layout);
SAFE_RELEASE(_pixelShader);
SAFE_RELEASE(_vertexShader);
}
bool TextureShaderClass::OutputShaderErrorMessage(ID3D10Blob* blob, HWND hwnd, WCHAR* shaderFileName)
{
// 에러 메시지를 출력창에 표시합니다.
OutputDebugStringA(reinterpret_cast<const char*>(blob->GetBufferPointer()));
// 에러 메시지를 반환합니다.
SAFE_RELEASE(blob);
// 파일 에러가 있음을 팝업 메시지로 알려줍니다.
MessageBox(hwnd, L"Error Compiling Shader.", shaderFileName, MB_OK);
return false;
}
bool TextureShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
{
// 행렬을 transpose하여 쉐이더에서 사용할 수 있게 합니다.
worldMatrix = XMMatrixTranspose(worldMatrix);
viewMatrix = XMMatrixTranspose(viewMatrix);
projectionMatrix = XMMatrixTranspose(projectionMatrix);
// 상수 버퍼의 내용을 쓸 수 있도록 잠급니다.
D3D11_MAPPED_SUBRESOURCE mappedResource;
if (FAILED(deviceContext->Map(_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
{
return false;
}
// 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
MatrixBufferType* dataPtr = (MatrixBufferType*)mappedResource.pData;
// 상수 버퍼에 행렬을 복사합니다.
dataPtr->world = worldMatrix;
dataPtr->view = viewMatrix;
dataPtr->projection = projectionMatrix;
// 상수 버퍼의 점금을 풉니다.
deviceContext->Unmap(_matrixBuffer, 0);
// 정점 쉐이더에서의 상수 버퍼의 위치를 설정합니다.
unsigned int bufferNumber = 0;
// 마지막으로 정점 쉐이더의 상수 버퍼를 바뀐 값으로 바꿉니다.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &_matrixBuffer);
// 픽셀 쉐이더에서 쉐이더 텍스처 리소스를 설정합니다.
deviceContext->PSSetShaderResources(0, 1, &texture);
return true;
}
void TextureShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
// 정점 입력 레이아웃을 설정합니다.
deviceContext->IASetInputLayout(_layout);
// 삼각형을 그릴 정점 쉐이더와 픽셀 쉐이더를 설정합니다.
deviceContext->VSSetShader(_vertexShader, NULL, 0);
deviceContext->PSSetShader(_pixelShader, NULL, 0);
// 픽셀 쉐이더에서 샘플러 상태를 설정합니다.
deviceContext->PSSetSamplers(0, 1, &_sampleState);
// 삼각형을 그립니다
deviceContext->DrawIndexed(indexCount, 0, 0);
}
다음은 TextureClass입니다. TextureClass는 텍스쳐 자원을 불러오고, 접근하는 작업을 캡슐화 합니다. 모든 텍스쳐에 대해 각각 이 클래스가 만들어져 있어야 합니다.
TextureClass
#pragma once
class TextureClass
{
private:
struct TargaHeader
{
unsigned char data1[12];
unsigned short width;
unsigned short height;
unsigned char bpp;
unsigned char data2;
};
public:
TextureClass();
TextureClass(TextureClass& other);
~TextureClass();
bool Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* fileName);
void Shutdown();
ID3D11ShaderResourceView* GetTexture();
private:
bool LoadTarga(char* fileName, int& height, int& width);
private:
unsigned char* _targaData = nullptr;
ID3D11Texture2D* _texture = nullptr;
ID3D11ShaderResourceView* _textureView = nullptr;
};
#include "stdafx.h"
#include "TextureClass.h"
TextureClass::TextureClass()
{
}
TextureClass::TextureClass(TextureClass& other)
{
}
TextureClass::~TextureClass()
{
}
bool TextureClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* fileName)
{
int width = 0;
int height = 0;
// targa 이미지 데이터를 메모리에 로드합니다.
if (!LoadTarga(fileName, height, width))
{
return false;
}
// 텍스쳐의 구조체를 설정합니다.
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.Height = height;
textureDesc.Width = width;
textureDesc.MipLevels = 0;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
// 빈 텍스쳐를 생성합니다.
HRESULT hResult = device->CreateTexture2D(&textureDesc, NULL, &_texture);
if (FAILED(hResult))
{
return false;
}
// targa 이미지 데이터의 너비 사이즐르 설정합니다.
UINT rowPitch = (width * 4) * sizeof(unsigned char);
// targa 이미지 데이터를 텍스처에 복사합니다.
deviceContext->UpdateSubresource(_texture, 0, NULL, _targaData, rowPitch, 0);
// 쉐이더 리소스 뷰 구조체를 설정합니다.
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = textureDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = -1;
// 텍스처의 쉐이더 리소스 뷰를 만듭니다.
hResult = device->CreateShaderResourceView(_texture, &srvDesc, &_textureView);
if (FAILED(hResult))
{
return false;
}
// 이 텍스처에 대해 밉맵을 생성합니다.
deviceContext->GenerateMips(_textureView);
// 이미지 데이터가 텍스처에 로드 되었으므로 targa 이미지 데이터를 해제합니다.
SAFE_DELETE_ARRAY(_targaData);
return true;
}
void TextureClass::Shutdown()
{
SAFE_RELEASE(_textureView);
SAFE_RELEASE(_texture);
SAFE_DELETE_ARRAY(_targaData);
}
ID3D11ShaderResourceView* TextureClass::GetTexture()
{
return _textureView;
}
bool TextureClass::LoadTarga(char* fileName, int& height, int& width)
{
// targa 파일을 바이너리 모드로 파일을 엽니다
FILE* filePtr;
if (fopen_s(&filePtr, fileName, "rb") != 0)
{
return false;
}
// 파일 헤더를 읽어옵니다.
TargaHeader targaFileHeader;
unsigned int count = (unsigned int)fread(&targaFileHeader, sizeof(TargaHeader), 1, filePtr);
if (count != 1)
{
return false;
}
// 파일 헤더에서 중요 정보를 얻어옵니다
height = (int)targaFileHeader.height;
width = (int)targaFileHeader.width;
int bpp = (int)targaFileHeader.bpp;
// 파일이 32bit 인지 24 비트인지 체크합니다.
if (bpp != 32)
{
return false;
}
// 32bit 이미지 데이터의 크기를 계산합니다.
int imageSize = width * height * 4;
// Targa 이미지 데이터 용 메모리를 할당합니다.
unsigned char* targaImage = new unsigned char[imageSize];
if (targaImage == nullptr)
{
return false;
}
// targa 이미지 데이터를 읽습니다.
count = (unsigned int)fread(targaImage, 1, imageSize, filePtr);
if (count != imageSize)
{
return false;
}
// 파일을 닫습니다.
if (fclose(filePtr) != 0)
{
return false;
}
// targa 대상 데이터에 대한 메모리를 할당합니다.
_targaData = new unsigned char[imageSize];
if (!_targaData)
{
return false;
}
// targa 대상 데이터 배열에 인덱스를 초기화합니다.
int index = 0;
// targa 이미지 데이터 배열에 인덱스를 초기화합니다.
int k = (width * height * 4) - (width * 4);
// 이제 targa 형식이 거꾸로 저장되었으므로 올바른 순서로 targa 이미지 데이터를 targa 대상 배열에 복사합니다.
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
_targaData[index + 0] = targaImage[k + 2]; // 빨강
_targaData[index + 1] = targaImage[k + 1]; // 노랑
_targaData[index + 2] = targaImage[k + 0]; // 파랑
_targaData[index + 3] = targaImage[k + 3]; // 알파
// 인덱스를 targa 데이터로 증가시킵니다.
k += 4;
index += 4;
}
// targa 이미지 데이터 인덱스를 역순으로 읽은 후 열의 시작 부분에서 이전 행으로 다시 설정합니다.
k -= (width * 8);
}
// 대상 배열에 복사 된 targa 이미지 데이터를 해제합니다.
SAFE_DELETE_ARRAY(targaImage);
return true;
}
ModelClass는 지난번 내용에 더해 텍스쳐를 지원하는 내용이 추가됐습니다.
ModelClass.h
#pragma once
#include "TextureClass.h"
class ModelClass : public AlignedAllocationPolicy<16>
{
private:
struct VertexType
{
XMFLOAT3 position;
XMFLOAT2 texture;
};
public:
ModelClass();
ModelClass(const ModelClass& modelClass);
~ModelClass();
bool Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* fileName);
void ShutDown();
void Render(ID3D11DeviceContext* deviceContext);
int GetIndexCount();
ID3D11ShaderResourceView* GetTexture();
private:
bool InitializeBuffers(ID3D11Device* device);
void ShutdownBuffers();
void RenderBuffers(ID3D11DeviceContext* deviceContext);
bool LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filePath);
void ReleaseTexture();
private:
ID3D11Buffer* _vertexBuffer = nullptr;
ID3D11Buffer* _indexBuffer = nullptr;
int _vertexCount = 0;
int _indexCount = 0;
TextureClass* _texture = nullptr;
};
#include "stdafx.h"
#include "TextureClass.h"
#include "ModelClass.h"
ModelClass::ModelClass()
{
}
ModelClass::ModelClass(const ModelClass& modelClass)
{
}
ModelClass::~ModelClass()
{
}
bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* fileName)
{
// 정점 및 인덱스 버퍼를 초기화 합니다.
if (InitializeBuffers(device) == false)
{
return false;
}
// 이 모델의 텍스처를 로드합니다.
return LoadTexture(device,deviceContext, fileName);
}
void ModelClass::ShutDown()
{
// 모델 텍스처를 반환합니다.
ReleaseTexture();
// 버텍스 및 인덱스 버퍼를 종료합니다.
ShutdownBuffers();
}
void ModelClass::Render(ID3D11DeviceContext* deviceContext)
{
// 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓습니다.
RenderBuffers(deviceContext);
}
int ModelClass::GetIndexCount()
{
return _indexCount;
}
ID3D11ShaderResourceView* ModelClass::GetTexture()
{
return _texture->GetTexture();
}
bool ModelClass::InitializeBuffers(ID3D11Device* device)
{
// 정점 배열의 정점 수를 설정합니다.
_vertexCount = 3;
// 인덱스 배열의 인덱스 수를 설정합니다.
_indexCount = 3;
// 정점 배열을 만듭니다.
VertexType* vertices = new VertexType[_vertexCount];
if (vertices == nullptr)
{
return false;
}
// 인ㄷㄱ스 배열을 만듭니다.
unsigned long* indices = new unsigned long[_indexCount];
if (indices == nullptr)
{
return false;
}
// 정점 배열에 데이터를 설정합니다.
vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f); // Botton Left
vertices[0].texture = XMFLOAT2(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[2].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // Botton Right
vertices[2].texture = XMFLOAT2(1.0f, 1.0f);
// 인덱스 배열의 값을 설정합니다.
indices[0] = 0; // Botton Left
indices[1] = 1; // Top Middle
indices[2] = 2; // Botton Right
// 정적 정점 버퍼의 구조체를 설정합니다.
D3D11_BUFFER_DESC vertexBufferDesc;
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * _vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Subresource 구조에 정점 데이터에 대한 포인터를 제공합니다.
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// 이제 정점 버퍼를 만듭니다.
if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexData, &_vertexBuffer)))
{
return false;
}
// 정점 인덱스 버퍼의 구조체를 설정합니다.
D3D11_BUFFER_DESC indexBufferDesc;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * _indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// 인덱스 데이터를 가르키는 보조 리소스 구조체를 작성합니다.
D3D11_SUBRESOURCE_DATA indexData;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// 인덱스 버퍼를 생성합니다.
if (FAILED(device->CreateBuffer(&indexBufferDesc, &indexData, &_indexBuffer)))
{
return false;
}
// 생성되고 값이 할당된 정점 버퍼와 인덱스 버퍼를 해제합니다.
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
void ModelClass::ShutdownBuffers()
{
// 인덱스 버퍼를 해제합니다.
if (_indexBuffer)
{
_indexBuffer->Release();
_indexBuffer = 0;
}
// 정점 버퍼를 해제합니다.
if (_vertexBuffer)
{
_vertexBuffer->Release();
_vertexBuffer = 0;
}
}
void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
// 정점 버퍼의 단위와 오프셋을 설정합니다.
UINT stride = sizeof(VertexType);
UINT offset = 0;
// 렌더링 할 수 있도록 입력 어셈들러에서 정점 버퍼를 활성으로 설정합니다.
deviceContext->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);
// 렌더링 할 수 있도록 입력 어셈블러에서 인덱스 버퍼를 활성으로 설정합니다.
deviceContext->IASetIndexBuffer(_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// 정점 버퍼로 그릴 기본형을 설정합니다. 여기서는 삼각형으로 설정합니다.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
bool ModelClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filePath)
{
_texture = new TextureClass();
if (_texture == nullptr)
{
return false;
}
// 텍스쳐 오브젝트를 초기화한다.
return _texture->Initialize(device, deviceContext, filePath);
}
void ModelClass::ReleaseTexture()
{
// 텍스쳐 오브젝트를 릴리즈한다.
if (_texture)
{
_texture->Shutdown();
SAFE_DELETE(_texture);
}
}
다은은 GraphicsClass 입니다. GraphicsClass 클래스는 ColorShaderClass의 멤버 변수를 TextureShaderClass멤버 변수 사용으로 변경되었습니다.
GraphicsClass
#pragma once
/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
class D3DClass;
class CameraClass;
class ModelClass;
class TextureShaderClass;
class GraphicsClass
{
public:
GraphicsClass();
GraphicsClass(const GraphicsClass& other);
~GraphicsClass();
bool Initialize(int screenWidth, int screenHeight, HWND hwnd);
void Shutdown();
bool Frame();
private:
bool Render();
private:
D3DClass* _direct3D = nullptr;
CameraClass* _camera = nullptr;
ModelClass* _model = nullptr;
TextureShaderClass* _textureShader = nullptr;
};
#include "stdafx.h"
#include "d3dclass.h"
#include "CameraClass.h"
#include "ModelClass.h"
#include "TextureShaderClass.h"
#include "GraphicsClass.h"
GraphicsClass::GraphicsClass()
{
}
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
GraphicsClass::~GraphicsClass()
{
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
// Direct3D 객체 생성
//_direct3D = (D3DClass*) SAFE_ALIGNED_NEW(sizeof(D3DClass), 16);
_direct3D = new D3DClass();
if (!_direct3D)
{
return false;
}
// Direct3D 객체 초기화
if (!_direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
{
MessageBox(hwnd, L"Could not initialze Direct3D", L"Error", MB_OK);
return false;
}
// _camera 객체 생성
_camera = new CameraClass();
if (_camera == nullptr)
{
return false;
}
// 카메라 포지션 변경
_camera->SetPosition(0.0f, 0.0f, -5.0f);
// _model 객체 생성
_model = new ModelClass();
if (_model == nullptr)
{
return false;
}
// _model 객체 초기화
if (!_model->Initialize(_direct3D->GetDevice(), _direct3D->GetDeviceContext(), "Texture/stone01.tga"))
{
MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
return false;
}
// _textureShader 생성
_textureShader = new TextureShaderClass();
if (_textureShader == nullptr)
{
return false;
}
// _textureShader 객체 초기화
if (!_textureShader->Initialize(_direct3D->GetDevice(), hwnd))
{
MessageBox(hwnd, L"Could not initialize the color shader object.", L"Error", MB_OK);
return false;
}
return true;
}
void GraphicsClass::Shutdown()
{
if (_textureShader)
{
_textureShader->ShutDown();
SAFE_DELETE(_textureShader);
}
if (_model)
{
_model->ShutDown();
SAFE_DELETE(_model);
}
// _camera 객체 반환
SAFE_DELETE(_camera);
// Direct3D 객체 반환
if (_direct3D)
{
_direct3D->Shutdown();
SAFE_DELETE(_direct3D);
}
}
bool GraphicsClass::Frame()
{
// 그래픽 랜더링 처리
return Render();
}
bool GraphicsClass::Render()
{
// 씬을 그리기 위해 버퍼를 지웁니다.
_direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
// 카메라의 위치에 따라 뷰 행렬을 생성합니다.
_camera->Render();
// 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다.
XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
_direct3D->GetWorldMatrix(worldMatrix);
_camera->GetViewMatrix(viewMatrix);
_direct3D->GetProjectionMatrix(projectionMatrix);
// 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비합니다.
_model->Render(_direct3D->GetDeviceContext());
// 텍스처 쉐이더를 사용하여 모델을 렌더링 합니다.
if (!_textureShader->Render(_direct3D->GetDeviceContext(), _model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, _model->GetTexture()))
{
return false;
}
// 버퍼의 내용을 화면에 출력합니다.
_direct3D->EndScene();
return true;
}
출력화면
후... 버그 잡는데 일주일 넘게 걸렸다... 후....
'DirectX' 카테고리의 다른 글
6. 3D 모델 렌더링 (0) | 2022.11.26 |
---|---|
5. 조명 (0) | 2022.11.21 |
3. 버퍼, 쉐이더 및 HLSL (0) | 2022.10.10 |
번외) Warning - warning C4316 에러 문제 (0) | 2022.10.03 |
2. DirectX 초기화 (0) | 2022.10.03 |