DirectX 10 教程17:多重纹理和纹理数组
原文地址:Tutorial 17: Multitexturing and Texture Arrays(http://www.rastertek.com/dx10tut17.html)。
源代码下载:dx10tut17.zip。
本教程介绍了如何在DirectX 10中实现多重纹理(Multitexturing)以及如何实现纹理数组。多重纹理是混合两张不同的纹理生成新纹理的处理过程。根据你想要实现的效果的不同,可以使用不同的公式混合两张纹理。本教程中我们只是取两张纹理像素的平均颜色创建一张混合纹理。
纹理数组是DirectX 10中的新功能,让你可以在GPU中同时激活多张纹理,而使用以前的方法一次只能激活一张纹理,需要花许多额外的开销用于加载卸载纹理。大多数人将一组纹理拼接成一张纹理并使用不同的纹理坐标使用其中的一张纹理,但使用DirectX 10中的这个新功能就无需如此了。
我们将第一张纹理称为基纹理(base texture),如下图所示:

与第一张进行组合的第二张纹理称为颜色纹理(color texture),如下图所示:

这两张纹理会在像素着色器中一个一个像素组合起来。使用的混合方程如下:
blendColor = basePixel * colorPixel * gammaCorrection;
使用上面的方程显示的结果如下图所示:

你可能想知道为什么我没有用如下公式取像素颜色的平均值:
blendColor = (basePixel * 0.5) + (colorPixel * 0.5);
理由是像素颜色会修正到显示器的gamma值,这会让像素颜色遵循非线性曲线落在0.0到1.0之间,所以我们需要使用像素着色器进行gamma校正。如果不进行gamma校正直接平均相加,则会获得如下效果,而这个效果并不是我们想要达到的:

值得注意的是,大多数设备有不同的gamma值,想要一个查询表格或一个gamma slider,这样用户才能选择设备的gamma设置。本教程中我选择了2.0作为gamma值,使教程保持简单。
下面我们首先看一下multitexture shader的代码,这个代码基于texture shader,但有所修改。
Multitexture.fx
//////////////////////////////////////////////////////////////////////////////// // Filename: multitexture.fx //////////////////////////////////////////////////////////////////////////////// ///////////// // GLOBALS // ///////////// matrix worldMatrix; matrix viewMatrix; matrix projectionMatrix;
我们添加了一个有两个元素的纹理数组资源表示要混合的两张纹理,比起使用单张纹理,纹理数组效率更高。在以前版本的DirectX中,切换纹理是非常耗费资源的操作,它强迫显卡切换,而纹理数组可以减少这种开销。
Texture2D shaderTextures[2];
///////////////////
// SAMPLE STATES //
///////////////////
SamplerState SampleType
{
Filter = MIN_MAG_MIP_LINEAR;
AddressU = Wrap;
AddressV = Wrap;
};
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
};
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;
}
像素着色器的代码是本教程的关键。我们根据纹理坐标从两张纹理中采样颜色,之后使用乘法组合起来,我们还想乘以一个gamma值,这里我使用的是2.0,这个值接近于大多数显示器的gamma值。获取了混合后的像素后将它作为最终颜色输出。注意我们使用索引值访问纹理数组中的纹理。
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 MultiTexturePixelShader(PixelInputType input) : SV_Target
{
float4 color1;
float4 color2;
float4 blendColor;
// Get the pixel color from the first texture.
color1 = shaderTextures[0].Sample(SampleType, input.tex);
// Get the pixel color from the second texture.
color2 = shaderTextures[1].Sample(SampleType, input.tex);
// Blend the two pixels together and multiply by the gamma value.
blendColor = color1 * color2 * 2.0;
return blendColor;
}
////////////////////////////////////////////////////////////////////////////////
// Technique
////////////////////////////////////////////////////////////////////////////////
technique10 MultiTextureTechnique
{
pass pass0
{
SetVertexShader(CompileShader(vs_4_0, MultiTextureVertexShader()));
SetPixelShader(CompileShader(ps_4_0, MultiTexturePixelShader()));
SetGeometryShader(NULL);
}
}
Multitextureshaderclass.h
multitexture shader的代码基于TextureShaderClass,但有微小的修改。
////////////////////////////////////////////////////////////////////////////////
// Filename: multitextureshaderclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _MULTITEXTURESHADERCLASS_H_
#define _MULTITEXTURESHADERCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <d3d10.h>
#include <d3dx10.h>
#include <fstream>
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Class name: MultiTextureShaderClass
////////////////////////////////////////////////////////////////////////////////
class MultiTextureShaderClass
{
public:
MultiTextureShaderClass();
MultiTextureShaderClass(const MultiTextureShaderClass&);
~MultiTextureShaderClass();
bool Initialize(ID3D10Device*, HWND);
void Shutdown();
void Render(ID3D10Device*, int, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView**);
private:
bool InitializeShader(ID3D10Device*, HWND, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
void SetShaderParameters(D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView**);
void RenderShader(ID3D10Device*, int);
private:
ID3D10Effect* m_effect;
ID3D10EffectTechnique* m_technique;
ID3D10InputLayout* m_layout;
ID3D10EffectMatrixVariable* m_worldMatrixPtr;
ID3D10EffectMatrixVariable* m_viewMatrixPtr;
ID3D10EffectMatrixVariable* m_projectionMatrixPtr;
下面是新的纹理数组资源指针。
ID3D10EffectShaderResourceVariable* m_textureArrayPtr; }; #endif
Multitextureshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
// Filename: multitextureshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "multitextureshaderclass.h"
MultiTextureShaderClass::MultiTextureShaderClass()
{
m_effect = 0;
m_technique = 0;
m_layout = 0;
m_worldMatrixPtr = 0;
m_viewMatrixPtr = 0;
m_projectionMatrixPtr = 0;
在构造函数中将新的纹理数组资源指针设置为null。
m_textureArrayPtr = 0;
}
MultiTextureShaderClass::MultiTextureShaderClass(const MultiTextureShaderClass& other)
{
}
MultiTextureShaderClass::~MultiTextureShaderClass()
{
}
bool MultiTextureShaderClass::Initialize(ID3D10Device* device, HWND hwnd)
{
bool result;
multitexture.fx HLSL shader文件在Initialize方法中加载。
// Initialize the shader that will be used to draw the model.
result = InitializeShader(device, hwnd, L"../Engine/multitexture.fx");
if(!result)
{
return false;
}
return true;
}
Shutdown方法调用ShutdownShader释放shader。
void MultiTextureShaderClass::Shutdown()
{
// Shutdown the shader effect.
ShutdownShader();
return;
}
Render方法的参数变为指向纹理数组的指针,这样shader就可以访问两张纹理进行混合处理。
void MultiTextureShaderClass::Render(ID3D10Device* device, int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix,
D3DXMATRIX projectionMatrix, ID3D10ShaderResourceView** textureArray)
{
// Set the shader parameters that it will use for rendering.
SetShaderParameters(worldMatrix, viewMatrix, projectionMatrix, textureArray);
// Now render the prepared buffers with the shader.
RenderShader(device, indexCount);
return;
}
bool MultiTextureShaderClass::InitializeShader(ID3D10Device* device, HWND hwnd, WCHAR* filename)
{
HRESULT result;
ID3D10Blob* errorMessage;
D3D10_INPUT_ELEMENT_DESC polygonLayout[2];
unsigned int numElements;
D3D10_PASS_DESC passDesc;
// Initialize the error message.
errorMessage = 0;
// Load the shader in from the file.
result = D3DX10CreateEffectFromFile(filename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
device, NULL, NULL, &m_effect, &errorMessage, NULL);
if(FAILED(result))
{
// If the shader failed to compile it should have writen something to the error message.
if(errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, filename);
}
// If there was nothing in the error message then it simply could not find the shader file itself.
else
{
MessageBox(hwnd, filename, L"Missing Shader File", MB_OK);
}
return false;
}
Technique名称设置为MultiTextureTechnique匹配HLSL文件中的名称。
// Get a pointer to the technique inside the shader.
m_technique = m_effect->GetTechniqueByName("MultiTextureTechnique");
if(!m_technique)
{
return false;
}
// Now setup the layout of the data that goes into the shader.
// 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 = D3D10_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 = D3D10_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;
// Get a count of the elements in the layout.
numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// Get the description of the first pass described in the shader technique.
m_technique->GetPassByIndex(0)->GetDesc(&passDesc);
// Create the input layout.
result = device->CreateInputLayout(polygonLayout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize,
&m_layout);
if(FAILED(result))
{
return false;
}
// Get pointers to the three matrices inside the shader so we can update them from this class.
m_worldMatrixPtr = m_effect->GetVariableByName("worldMatrix")->AsMatrix();
m_viewMatrixPtr = m_effect->GetVariableByName("viewMatrix")->AsMatrix();
m_projectionMatrixPtr = m_effect->GetVariableByName("projectionMatrix")->AsMatrix();
创建指向shader中的纹理数组资源的指针。
// Get pointer to the texture array resource inside the shader.
m_textureArrayPtr = m_effect->GetVariableByName("shaderTextures")->AsShaderResource();
return true;
}
void MultiTextureShaderClass::ShutdownShader()
{
释放指向纹理数组的指针。
// Release the pointer to the texture in the shader file.
m_textureArrayPtr = 0;
// Release the pointers to the matrices inside the shader.
m_worldMatrixPtr = 0;
m_viewMatrixPtr = 0;
m_projectionMatrixPtr = 0;
// Release the pointer to the shader layout.
if(m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the pointer to the shader technique.
m_technique = 0;
// Release the pointer to the shader.
if(m_effect)
{
m_effect->Release();
m_effect = 0;
}
return;
}
void MultiTextureShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned 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;
}
void MultiTextureShaderClass::SetShaderParameters(D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix,
ID3D10ShaderResourceView** textureArray)
{
// Set the world matrix variable inside the shader.
m_worldMatrixPtr->SetMatrix((float*)&worldMatrix);
// Set the view matrix variable inside the shader.
m_viewMatrixPtr->SetMatrix((float*)&viewMatrix);
// Set the projection matrix variable inside the shader.
m_projectionMatrixPtr->SetMatrix((float*)&projectionMatrix);
下面的代码设置纹理数组。SetResourceArray方法用于设置纹理数组。第一个参数是纹理数组的指针,第二个参数为数组的开始位置,第三个参数为传递数组中几个纹理。
// Bind the texture array.
m_textureArrayPtr->SetResourceArray(textureArray, 0, 2);
return;
}
void MultiTextureShaderClass::RenderShader(ID3D10Device* device, int indexCount)
{
D3D10_TECHNIQUE_DESC techniqueDesc;
unsigned int i;
// Set the input layout.
device->IASetInputLayout(m_layout);
// Get the description structure of the technique from inside the shader so it can be used for rendering.
m_technique->GetDesc(&techniqueDesc);
// Go through each pass in the technique (should be just one currently) and render the triangles.
for(i=0; i<techniqueDesc.Passes; ++i)
{
m_technique->GetPassByIndex(i)->Apply(0);
device->DrawIndexed(indexCount, 0, 0);
}
return;
}
Texturearrayclass.h
TextureArrayClass替换了前面的教程中使用的TextureClass,它可以拥有多张纹理并访问这些纹理,本教程只处理两张纹理,但很容易扩展成处理更多的纹理。
////////////////////////////////////////////////////////////////////////////////
// Filename: texturearrayclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _TEXTUREARRAYCLASS_H_
#define _TEXTUREARRAYCLASS_H_
//////////////
// INCLUDES //
//////////////
#include <d3d10.h>
#include <d3dx10.h>
////////////////////////////////////////////////////////////////////////////////
// Class name: TextureArrayClass
////////////////////////////////////////////////////////////////////////////////
class TextureArrayClass
{
public:
TextureArrayClass();
TextureArrayClass(const TextureArrayClass&);
~TextureArrayClass();
bool Initialize(ID3D10Device*, WCHAR*, WCHAR*);
void Shutdown();
ID3D10ShaderResourceView** GetTextureArray();
private:
下面的私有变量为纹理数组。
ID3D10ShaderResourceView* m_textures[2]; }; #endif
Texturearrayclass.cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: texturearrayclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "texturearrayclass.h"
构造函数将纹理数组初始化为null。
TextureArrayClass::TextureArrayClass()
{
m_textures[0] = 0;
m_textures[1] = 0;
}
TextureArrayClass::TextureArrayClass(const TextureArrayClass& other)
{
}
TextureArrayClass::~TextureArrayClass()
{
}
Initialize方法参数为两张纹理文件的名称,然后在纹理数组中创建两个纹理资源。
bool TextureArrayClass::Initialize(ID3D10Device* device, WCHAR* filename1, WCHAR* filename2)
{
HRESULT result;
// Load the first texture in.
result = D3DX10CreateShaderResourceViewFromFile(device, filename1, NULL, NULL, &m_textures[0], NULL);
if(FAILED(result))
{
return false;
}
// Load the second texture in.
result = D3DX10CreateShaderResourceViewFromFile(device, filename2, NULL, NULL, &m_textures[1], NULL);
if(FAILED(result))
{
return false;
}
return true;
}
Shutdown方法释放纹理数组中的每个元素。
void TextureArrayClass::Shutdown()
{
// Release the texture resources.
if(m_textures[0])
{
m_textures[0]->Release();
m_textures[0] = 0;
}
if(m_textures[1])
{
m_textures[1]->Release();
m_textures[1] = 0;
}
return;
}
GetTextureArray返回只需纹理数组的指针。这样就可以访问纹理数组中的纹理了。
ID3D10ShaderResourceView** TextureArrayClass::GetTextureArray()
{
return m_textures;
}
Modelclass.h
ModelClass修改为可以使用纹理数组。
//////////////////////////////////////////////////////////////////////////////// // Filename: modelclass.h //////////////////////////////////////////////////////////////////////////////// #ifndef _MODELCLASS_H_ #define _MODELCLASS_H_ ////////////// // INCLUDES // ////////////// #include <fstream> using namespace std;
TextureArrayClass头文件替代了前面教程中的TextureClass头文件。
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "texturearrayclass.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: ModelClass
////////////////////////////////////////////////////////////////////////////////
class ModelClass
{
private:
struct VertexType
{
D3DXVECTOR3 position;
D3DXVECTOR2 texture;
};
struct ModelType
{
float x, y, z;
float tu, tv;
float nx, ny, nz;
};
public:
ModelClass();
ModelClass(const ModelClass&);
~ModelClass();
bool Initialize(ID3D10Device*, char*, WCHAR*, WCHAR*);
void Shutdown();
void Render(ID3D10Device*);
int GetIndexCount();
ID3D10ShaderResourceView** GetTextureArray();
private:
bool InitializeBuffers(ID3D10Device*);
void ShutdownBuffers();
void RenderBuffers(ID3D10Device*);
bool LoadTextures(ID3D10Device*, WCHAR*, WCHAR*);
void ReleaseTextures();
bool LoadModel(char*);
void ReleaseModel();
private:
ID3D10Buffer *m_vertexBuffer, *m_indexBuffer;
int m_vertexCount, m_indexCount;
ModelType* m_model;
使用TextureArrayClass代替前面教程的TextureClass。
TextureArrayClass* m_TextureArray; }; #endif
Modelclass.cpp
下面的代码只包含与上一个教程不同的部分。
////////////////////////////////////////////////////////////////////////////////
// Filename: modelclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "modelclass.h"
ModelClass::ModelClass()
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
m_model = 0;
在构造函数中将TextureArray变量设置为null。
m_TextureArray = 0;
}
ModelClass::ModelClass(const ModelClass& other)
{
}
ModelClass::~ModelClass()
{
}
bool ModelClass::Initialize(ID3D10Device* device, char* modelFilename, WCHAR* textureFilename1, WCHAR* textureFilename2)
{
bool result;
// Load in the model data.
result = LoadModel(modelFilename);
if(!result)
{
return false;
}
// Initialize the vertex and index buffer that hold the geometry for the triangle.
result = InitializeBuffers(device);
if(!result)
{
return false;
}
LoadTextures方法的参数为两张纹理的文件名称,这样两张纹理就会被加载到纹理数组中。
// Load the textures for this model.
result = LoadTextures(device, textureFilename1, textureFilename2);
if(!result)
{
return false;
}
return true;
}
void ModelClass::Shutdown()
{
在Shutdown方法中调用ReleaseTextures释放纹理数组。
> // Release the model textures. ReleaseTextures(); // Release the vertex and index buffers. ShutdownBuffers(); // Release the model data. ReleaseModel(); return; }
GetTextureArray方法可以访问纹理数组用于模型的绘制。
ID3D10ShaderResourceView** ModelClass::GetTextureArray()
{
return m_TextureArray->GetTextureArray();
}
LoadTextures方法进行了修改,它可以创建一个TextureArrayClass对象,然后根据输入的两张纹理文件的名称初始化这个对象。
bool ModelClass::LoadTextures(ID3D10Device* device, WCHAR* filename1, WCHAR* filename2)
{
bool result;
// Create the texture array object.
m_TextureArray = new TextureArrayClass;
if(!m_TextureArray)
{
return false;
}
// Initialize the texture array object.
result = m_TextureArray->Initialize(device, filename1, filename2);
if(!result)
{
return false;
}
return true;
}
ReleaseTextures方法释放TextureArrayClass对象。
void ModelClass::ReleaseTextures()
{
// Release the texture array object.
if(m_TextureArray)
{
m_TextureArray->Shutdown();
delete m_TextureArray;
m_TextureArray = 0;
}
return;
}
Graphicsclass.h
//////////////////////////////////////////////////////////////////////////////// // Filename: graphicsclass.h //////////////////////////////////////////////////////////////////////////////// #ifndef _GRAPHICSCLASS_H_ #define _GRAPHICSCLASS_H_ ///////////// // GLOBALS // ///////////// const bool FULL_SCREEN = true; const bool VSYNC_ENABLED = true; const float SCREEN_DEPTH = 1000.0f; const float SCREEN_NEAR = 0.1f; /////////////////////// // MY CLASS INCLUDES // /////////////////////// #include "d3dclass.h" #include "cameraclass.h" #include "modelclass.h"
MultiTextureShaderClass头文件现在包含在GraphicsClass之中。
#include "multitextureshaderclass.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: GraphicsClass
////////////////////////////////////////////////////////////////////////////////
class GraphicsClass
{
public:
GraphicsClass();
GraphicsClass(const GraphicsClass&);
~GraphicsClass();
bool Initialize(int, int, HWND);
void Shutdown();
bool Frame();
bool Render();
private:
D3DClass* m_D3D;
CameraClass* m_Camera;
ModelClass* m_Model;
下面是新的MultiTextureShaderClass对象。
MultiTextureShaderClass* m_MultiTextureShader; }; #endif
Graphicsclass.cpp
下面的代码只包含与前面的教程不同的部分。
////////////////////////////////////////////////////////////////////////////////
// Filename: graphicsclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "graphicsclass.h"
GraphicsClass::GraphicsClass()
{
m_D3D = 0;
m_Camera = 0;
m_Model = 0;
在构造函数中将multitexture shader对象设置为null。
m_MultiTextureShader = 0;
}
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
GraphicsClass::~GraphicsClass()
{
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
bool result;
D3DXMATRIX baseViewMatrix;
// Create the Direct3D object.
m_D3D = new D3DClass;
if(!m_D3D)
{
return false;
}
// Initialize the Direct3D object.
result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
if(!result)
{
MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
return false;
}
// Create the camera object.
m_Camera = new CameraClass;
if(!m_Camera)
{
return false;
}
// Initialize a base view matrix with the camera for 2D user interface rendering.
m_Camera->SetPosition(0.0f, 0.0f, -1.0f);
m_Camera->Render();
m_Camera->GetViewMatrix(baseViewMatrix);
// Create the model object.
m_Model = new ModelClass;
if(!m_Model)
{
return false;
}
ModelClass对象的Initialize方法有所不同。本教程我们加载的是square.txt模型,因为在一张平面上展示效果最好。我们还需要将两张纹理加载到纹理数组中,而不是上一个教程中的单张纹理。
// Initialize the model object.
result = m_Model->Initialize(m_D3D->GetDevice(), "../Engine/data/square.txt", L"../Engine/data/stone01.dds",
L"../Engine/data/dirt01.dds");
if(!result)
{
MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
return false;
}
下面的代码创建并初始化multitexture shader对象。
// Create the multitexture shader object.
m_MultiTextureShader = new MultiTextureShaderClass;
if(!m_MultiTextureShader)
{
return false;
}
// Initialize the multitexture shader object.
result = m_MultiTextureShader->Initialize(m_D3D->GetDevice(), hwnd);
if(!result)
{
MessageBox(hwnd, L"Could not initialize the multitexture shader object.", L"Error", MB_OK);
return false;
}
return true;
}
void GraphicsClass::Shutdown()
{
在Shutdown方法中释放multitexture shader。
// Release the multitexture shader object.
if(m_MultiTextureShader)
{
m_MultiTextureShader->Shutdown();
delete m_MultiTextureShader;
m_MultiTextureShader = 0;
}
// Release the model object.
if(m_Model)
{
m_Model->Shutdown();
delete m_Model;
m_Model = 0;
}
// Release the camera object.
if(m_Camera)
{
delete m_Camera;
m_Camera = 0;
}
// Release the Direct3D object.
if(m_D3D)
{
m_D3D->Shutdown();
delete m_D3D;
m_D3D = 0;
}
return;
}
bool GraphicsClass::Frame()
{
我们将相机位置向前靠一点能更清晰地观察混合效果。
// Set the position of the camera.
m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
return true;
}
bool GraphicsClass::Render()
{
D3DXMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
// Clear the buffers to begin the scene.
m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
// Generate the view matrix based on the camera's position.
m_Camera->Render();
// Get the world, view, projection, and ortho matrices from the camera and d3d objects.
m_D3D->GetWorldMatrix(worldMatrix);
m_Camera->GetViewMatrix(viewMatrix);
m_D3D->GetProjectionMatrix(projectionMatrix);
m_D3D->GetOrthoMatrix(orthoMatrix);
// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
m_Model->Render(m_D3D->GetDevice());
使用新的multitexture shader绘制模型,注意Render方法使用的参数是来自于ModelClass的纹理数组。
// Render the model using the multitexture shader. m_MultiTextureShader->Render(m_D3D->GetDevice(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTextureArray()); // Present the rendered scene to the screen. m_D3D->EndScene(); return true; }
总结
我们现在学习了一个可以组合两张纹理的shader,还可以施加gamma校正,我们还知道了如何使用纹理数组提高图形性能。

练习
1.编译并允许程序观察结果,按escape键退出。
2.使用两张其他的纹理观察效果。
文件下载(已下载 1187 次)发布时间:2012/8/2 下午10:58:33 阅读次数:10731
