DirectX 10 教程26:透明
原文地址:Tutorial 26: Transparency(http://www.rastertek.com/dx10tut26.html)。
源代码下载:dx10tut26.zip。
Transparency效果可以让一张带纹理的对象呈现透明效果。
例如下列一张纹理:
我们可以让此纹理半透明显示在另一张纹理上面,获得如下图所示的效果:
透明是使用alpha混合实现的。任意像素的alpha分量用于确定像素的透明程度。例如,一个像素的alpha值为0.5,则它会以半透明显示。许多纹理都有一个alpha分量,修改这个分量可以让纹理某些部分透明,某些部分不透明。
要让alpha值起作用,你必须首先在shader中打开alpha混合并设置混合方程。本教程使用的混合状态如下所示:
BlendState AlphaBlendingOn { BlendEnable[0] = TRUE; DestBlend = INV_SRC_ALPHA; SrcBlend = SRC_ALPHA; };
DestBlend用于目标颜色,它是该像素已经存在的颜色。我们使用的混合方程中将目标颜色设置为INV_SRC_ALPHA,即取源颜色的反相,即用1减去源颜色的alpha值。例如,如果源的alpha为0.3,则目标的alpha为0.7,这会将70%的目标像素颜色组合到最终颜色中。
SrcBlend用于源像素颜色,即本教程中输入的纹理颜色。混合方程用的是SRC_ALPHA,即源颜色乘以自己的alpha值。
源颜色和目标颜色值会叠加在一起生成最终的输出颜色。
框架
框架中新添了一个名为TransparentShaderClass的新类,这个类类似于TextureShaderClass,只不过多了一个alpha混合值。
Transparent.fx
//////////////////////////////////////////////////////////////////////////////// // Filename: transparent.fx //////////////////////////////////////////////////////////////////////////////// ///////////// // GLOBALS // ///////////// matrix worldMatrix; matrix viewMatrix; matrix projectionMatrix; Texture2D shaderTexture;
新添的变量blendAmount表示纹理的透明程度。
float blendAmount; /////////////////// // SAMPLE STATES // /////////////////// SamplerState SampleType { Filter = MIN_MAG_MIP_LINEAR; AddressU = Wrap; AddressV = Wrap; };
新添的alpha混合状态用来实现透明效果。
///////////////////// // BLENDING STATES // ///////////////////// BlendState AlphaBlendingOn { BlendEnable[0] = TRUE; DestBlend = INV_SRC_ALPHA; SrcBlend = SRC_ALPHA; }; ////////////// // TYPEDEFS // ////////////// struct VertexInputType { float4 position : POSITION; float2 tex : TEXCOORD0; }; struct PixelInputType { float4 position : SV_POSITION; float2 tex : TEXCOORD0; }; //////////////////////////////////////////////////////////////////////////////// // Vertex Shader //////////////////////////////////////////////////////////////////////////////// PixelInputType TransparentVertexShader(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; } //////////////////////////////////////////////////////////////////////////////// // Pixel Shader //////////////////////////////////////////////////////////////////////////////// float4 TransparentPixelShader(PixelInputType input) : SV_Target { float4 color; // Sample the texture pixel at this location. color = shaderTexture.Sample(SampleType, input.tex);
我们使用blendAmount变量设置纹理的透明程度,将像素的alpha值设置为这个变量,当绘制时就会使用alpha值和混合状态创建透明效果。
// Set the alpha value of this pixel to the blending amount to create the alpha blending effect. color.a = blendAmount; return color; }
在technique中使用SetBlendState开启混合状态。注意这个混合状态会一直开启直到在关闭为止,因此使用其他shaer前需要关闭这个状态。
//////////////////////////////////////////////////////////////////////////////// // Technique //////////////////////////////////////////////////////////////////////////////// technique10 TransparentTechnique { pass pass0 { SetBlendState(AlphaBlendingOn, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF); SetVertexShader(CompileShader(vs_4_0, TransparentVertexShader())); SetPixelShader(CompileShader(ps_4_0, TransparentPixelShader())); SetGeometryShader(NULL); } }
Transparentshaderclass.h
TransparentShaderClass只是TextureShaderClass的改编版本,只是添加了处理透明的代码。
//////////////////////////////////////////////////////////////////////////////// // Filename: transparentshaderclass.h //////////////////////////////////////////////////////////////////////////////// #ifndef _TRANSPARENTSHADERCLASS_H_ #define _TRANSPARENTSHADERCLASS_H_ ////////////// // INCLUDES // ////////////// #include <d3d10.h> #include <d3dx10.h> #include <fstream> using namespace std; //////////////////////////////////////////////////////////////////////////////// // Class name: TransparentShaderClass //////////////////////////////////////////////////////////////////////////////// class TransparentShaderClass { public: TransparentShaderClass(); TransparentShaderClass(const TransparentShaderClass&); ~TransparentShaderClass(); bool Initialize(ID3D10Device*, HWND); void Shutdown(); void Render(ID3D10Device*, int, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView*, float); private: bool InitializeShader(ID3D10Device*, HWND, WCHAR*); void ShutdownShader(); void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*); void SetShaderParameters(D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView*, float); 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_texturePtr;
新添一个指向shader中blendAmount变量的指针。
ID3D10EffectScalarVariable* m_blendAmountPtr; }; #endif
Transparentshaderclass.cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: transparentshaderclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "transparentshaderclass.h" TransparentShaderClass::TransparentShaderClass() { m_effect = 0; m_technique = 0; m_layout = 0; m_worldMatrixPtr = 0; m_viewMatrixPtr = 0; m_projectionMatrixPtr = 0; m_texturePtr = 0;
在类构造函数中将blend amount指针设置为null。
m_blendAmountPtr = 0; } TransparentShaderClass::TransparentShaderClass(const TransparentShaderClass& other) { } TransparentShaderClass::~TransparentShaderClass() { } bool TransparentShaderClass::Initialize(ID3D10Device* device, HWND hwnd) { bool result;
加载transparent HLSL shader文件。
// Initialize the shader that will be used to draw the triangle. result = InitializeShader(device, hwnd, L"../Engine/transparent.fx"); if(!result) { return false; } return true; } void TransparentShaderClass::Shutdown() { // Shutdown the shader effect. ShutdownShader(); return; }
Render方法中新添了一个类型为float的blend参数,它设置了纹理的透明程度。
void TransparentShaderClass::Render(ID3D10Device* device, int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D10ShaderResourceView* texture, float blend) { // Set the shader parameters that it will use for rendering. SetShaderParameters(worldMatrix, viewMatrix, projectionMatrix, texture, blend); // Now render the prepared buffers with the shader. RenderShader(device, indexCount); return; } bool TransparentShaderClass::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的名称修改为TransparentTechnique。
// Get a pointer to the technique inside the shader. m_technique = m_effect->GetTechniqueByName("TransparentTechnique"); 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(); // Get pointer to the texture resource inside the shader. m_texturePtr = m_effect->GetVariableByName("shaderTexture")->AsShaderResource();
获取对应shader中的blendAmount变量的指针。
// Get a pointer to the blend amount variable inside the shader. m_blendAmountPtr = m_effect->GetVariableByName("blendAmount")->AsScalar(); return true; } void TransparentShaderClass::ShutdownShader() {
在ShutdownShader方法中释放blendAmount指针。
// Release the pointer to the blend amount in the shader file. m_blendAmountPtr = 0; // Release the pointer to the texture in the shader file. m_texturePtr = 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 TransparentShaderClass::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 TransparentShaderClass::SetShaderParameters(D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D10ShaderResourceView* texture, float blend) { // 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); // Bind the texture. m_texturePtr->SetResource(texture);
设置shader中的blendAmount的值。
// Set the blend amount variable inside the shader. m_blendAmountPtr->SetFloat(blend); return; } void TransparentShaderClass::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; }
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" #include "textureshaderclass.h" #include "transparentshaderclass.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_Model1; ModelClass* m_Model2; TextureShaderClass* m_TextureShader;
创建TransparentShaderClass对象。
TransparentShaderClass* m_TransparentShader; }; #endif
Graphicsclass.cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: graphicsclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "graphicsclass.h"
在构造函数中声明两个模型和TransparentShaderClass。
GraphicsClass::GraphicsClass() { m_D3D = 0; m_Camera = 0; m_Model1 = 0; m_Model2 = 0; m_TextureShader = 0; m_TransparentShader = 0; } GraphicsClass::GraphicsClass(const GraphicsClass& other) { } GraphicsClass::~GraphicsClass() { } bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd) { bool result; // 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; }
创建并初始化第一个模型,它是一个纹理为dirt01.dds的正方形。
// Create the first model object. m_Model1 = new ModelClass; if(!m_Model1) { return false; } // Initialize the first model object. result = m_Model1->Initialize(m_D3D->GetDevice(), L"../Engine/data/dirt01.dds", "../Engine/data/square.txt"); if(!result) { MessageBox(hwnd, L"Could not initialize the first model object.", L"Error", MB_OK); return false; }
创建并初始化第二个模型,它是一个纹理为stone01.dds的正方形。
// Create the second model object. m_Model2 = new ModelClass; if(!m_Model2) { return false; } // Initialize the second model object. result = m_Model2->Initialize(m_D3D->GetDevice(), L"../Engine/data/stone01.dds", "../Engine/data/square.txt"); if(!result) { MessageBox(hwnd, L"Could not initialize the second model object.", L"Error", MB_OK); return false; } // Create the texture shader object. m_TextureShader = new TextureShaderClass; if(!m_TextureShader) { return false; } // Initialize the texture shader object. result = m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the texture shader object.", L"Error", MB_OK); return false; }
创建并初始化TransparentShaderClass对象。
// Create the transparent shader object. m_TransparentShader = new TransparentShaderClass; if(!m_TransparentShader) { return false; } // Initialize the transparent shader object. result = m_TransparentShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the transparent shader object.", L"Error", MB_OK); return false; } return true; }
在Shutdown方法中释放TransparentShaderClass对象和两个模型。
void GraphicsClass::Shutdown() { // Release the transparent shader object. if(m_TransparentShader) { m_TransparentShader->Shutdown(); delete m_TransparentShader; m_TransparentShader = 0; } // Release the texture shader object. if(m_TextureShader) { m_TextureShader->Shutdown(); delete m_TextureShader; m_TextureShader = 0; } // Release the second model object. if(m_Model2) { m_Model2->Shutdown(); delete m_Model2; m_Model2 = 0; } // Release the first model object. if(m_Model1) { m_Model1->Shutdown(); delete m_Model1; m_Model1 = 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; float blendAmount;
设置blend变量,这个变量会被发送到transparent shader中。
// Set the blending amount to 50%. blendAmount = 0.5f; // Clear the scene to the color of the fog. 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, and projection matrices from the camera and d3d objects. m_D3D->GetWorldMatrix(worldMatrix); m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetProjectionMatrix(projectionMatrix);
在屏幕中央绘制第一个正方形,使用的是常规的texture shader。
// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing. m_Model1->Render(m_D3D->GetDevice()); // Render the model using the texture shader. m_TextureShader->Render(m_D3D->GetDevice(), m_Model1->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model1->GetTexture());
在偏右的地方绘制第二个正方形,位于第一个正方形之上。使用的是新的TransparentShaderClass对象,输入的参数为blendAmount,这样就绘制了一个透明的石头纹理的正方形。
// Translate to the right by one unit and towards the camera by one unit. D3DXMatrixTranslation(&worldMatrix, 1.0f, 0.0f, -1.0f); // Put the second square model on the graphics pipeline. m_Model2->Render(m_D3D->GetDevice()); // Render the second square model with the stone texture and use the 50% blending amount for transparency. m_TransparentShader->Render(m_D3D->GetDevice(), m_Model2->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model2->GetTexture(), blendAmount); // Present the rendered scene to the screen. m_D3D->EndScene(); return true; }
总结
使用透明效果就可以让纹理和模型透明,并可以基于它实现许多不同的效果。
练习
1.编译并运行程序,按Escape键退出。
2.改变GraphicsRender方法中的blendAmount的值观察透明效果的差异。
文件下载(已下载 889 次)发布时间:2012/8/27 下午10:48:46 阅读次数:8029