# DirectX/10.0/Direct3D/Font Engine

Writing text onto the screen is a pretty important function of any application. Rendering text in DirectX 11 requires that you first know how to render 2D images. As we covered that topic in the previous tutorial this tutorial will just build on that knowledge.
The first thing you are going to need is your own font image. I built a really simple one with the characters I wanted and put it on a 1024x16 DDS texture:
As you can see it has the basic characters needed and they are all on a single texture file. We can now build a simple font engine which uses an index into that texture to draw individual characters to the screen as needed. How we do that in DirectX 11 is we build a square out of two triangles and then render the single character from the texture onto that square. So if we have a sentence we figure out the characters we need, create a square for each of them, and then render the characters to those squares. After doing that we render all the squares onto the screen to the location that forms the sentence. This is the same method we used in the previous tutorial to render a 2D image to the screen.
Now to index the texture we will need a text file that gives the location and size of each character in the texture. This text file will allow the font engine to quickly grab the pixels it needs out of the texture to form a character that it can render. Below is the index file for this font texture.
This format of the file is: [Ascii value of character] [The character] [Left Texture U coordinate] [Right Texture U Coordinate] [Pixel Width of Character]
With both the index file and texture file we have what we need to build the font engine. If you need to build your own index file just make sure that each character is only separated by spaces and you can write a bitmap parser yourself to create TU and TV coordinates based on where there are no blank spaces.
Remember that different users will run your application in different resolutions. One size font is not going to be clearly readable on all resolutions. So you may want to make 3-4 different font sizes and use certain ones for certain resolutions to fix this problem.

## Framework

As we will want to encapsulate the font functionality in its own set of classes we will add some new classes to our frame work. The updated frame work looks like the following:
In this tutorial we have three new classes called TextClass, FontClass, and FontShader class. FontShaderClass is the shader for rendering fonts similar to how TextureShaderClass was used for rendering bitmap images in the previous tutorial. FontClass holds the font data and constructs vertex buffers needed for rendering strings. TextClass contains the vertex and index buffers for each set of text strings that need to be rendered to the screen, it uses FontClass to create the vertex buffer for the strings and then uses FontShaderClass to render those buffers.

## Fontclass.h

We will look at the new FontClass first. This class will handle the texture for the font, the font data from the text file, and the function used to build vertex buffers with the font data. The vertex buffers that hold the font data for individual sentences will be in the TextClass and not inside this class.
The FontType structure is used to hold the indexing data read in from the font index file. The left and right are the TU texture coordinates. The size is the width of the character in pixels.
The VertexType structure is for the actual vertex data used to build the square to render the text character on. The individual character will require two triangles to make a square. Those triangles will have position and texture data only.
BuildVertexArray will handle building and returning a vertex array of triangles that will render the character sentence which was given as input to this function. This function will be called by the new TextClass to build vertex arrays of all the sentences it needs to render.

## Fontclass.cpp

The class constructor initializes all the private member variables for the FontClass to null.
Initialize will load the font data and the font texture.
Shutdown will release the font data and the font texture.
The LoadFontData function is where we load the fontdata.txt file which contains the indexing information for the texture.
First we create an array of the FontType structure. The size of the array is set to 95 as that is the number of characters in the texture and hence the number of indexes in the fontdata.txt file.
Now we open the file and read each line into the array m_Font. We only need to read in the texture TU left and right coordinates as well as the pixel size of the character.
The ReleaseFontData function releases the array that holds the texture indexing data.
The LoadTexture function reads in the font.dds file into the texture shader resource. This will be the texture we take the characters from and write them to their own square polygons for rendering.
ReleaseTexture function releases the texture that was used for the font.
GetTexture returns the font texture interface so the font graphics can be rendered.
BuildVertexArray will be called by the TextClass to build vertex buffers out of the text sentences it sends to this function as input. This way each sentence in the TextClass that needs to be drawn has its own vertex buffer that can be rendered easily after being created. The vertices input is the pointer to the vertex array that will be returned to the TextClass once it is built. The sentence input is the text sentence that will be used to create the vertex array. The drawX and drawY input variables are the screen coordinates of where to draw the sentence.
The following loop will now build the vertex and index arrays. It takes each character from the sentence and creates two triangles for it. It then maps the character from the font texture onto those two triangles using the m_Font array which has the TU texture coordinates and pixel size. Once the polygon for that character has been created it then updates the X coordinate on the screen of where to draw the next character.

## Font.vs

The font vertex shader is just a modified version of the texture vertex shader in the previous tutorial that was used to render 2D images. The only change is the vertex shader name.

## Font.ps

We have a new constant buffer that contains the pixelColor value. We use this to control the color of the pixel that will be used to draw the font text.
The FontPixelShader first samples the font texture to get the pixel. If it samples a pixel that is black then it is just part of the background triangle and not a text pixel. In this case we set the alpha of this pixel to zero so when the blending is calculated it will determine that this pixel should be see-through. If the color of the input pixel is not black then it is a text pixel. In this case we multiply it by the pixelColor to get the pixel colored the way we want and then draw that to the screen.

## Fontshaderclass.h

The FontShaderClass is just the TextureShaderClass from the previous tutorial renamed with a couple code changes for rendering fonts.
We have a new structure type to match the PixleBuffer in the pixel shader. It contains just the pixel color of the text that will be rendered.
The FontShaderClass has a constant buffer for the pixel color that will be used to render the text fonts with color.

## Fontshaderclass.cpp

We initialize the pixel color constant buffer to null in the class constructor.
Initialize loads the new font vertex shader and pixel shader HLSL files.
Shutdown calls ShutdownShader which releases the font shader related pointers and data.
Render will set the shader parameters and then draw the buffers using the font shader. Notice the is the same as TextureShaderClass except that it takes in the new pixelColor parameter.
The InitializeShader function loads the new HLSL font vertex and pixel shaders as well as the pointers that interface with the shader.
The name of the vertex shader has been changed to FontVertexShader.
The name of the pixel shader has been changed to FontPixelShader.
Here we setup the new pixel color constant buffer that will allow this class to set the pixel color in the pixel shader.
The ShutdownShader function releases all the shader related data.
The new pixel color constant buffer is released here.
OutputShaderErrorMessage writes any shader compilation errors to a text file that can be reviewed in the event of a failure in compilation.
The SetShaderParameters function sets all the shader variables before rendering.
Here is where we set the pixel color before rendering. We lock the pixel constant buffer and then set the pixel color inside it and unlock it again. We set the constant buffer position in the pixel shader and it is ready for use.
RenderShader draws the prepared font vertex/index buffers using the font shader.

## Textclass.h

The TextClass handles all the 2D text drawing that the application will need. It renders 2D text to the screen and uses the FontClass and FontShaderClass to assist it in doing so.
SentenceType is the structure that holds the rendering information for each text sentence.
The VertexType must match the one in the FontClass.
We will use two sentences in this tutorial.

## Textclass.cpp

The class constructor initializes the private member variables to null.
Store the screen size and the base view matrix, these will be used for rendering 2D text.
Create and initialize the font object.
Create and initialize the font shader object.
Create and initialize the two strings that will be used for this tutorial. One string says Hello in white at 100, 100 and the other says Goodbye in yellow at 100, 200. The UpdateSentence function can be called to change the contents, location, and color of the strings at any time.
The Shutdown function will release the two sentences, the font object, and the font shader object.
Render will draw the two sentences to the screen.
The InitializeSentence function creates a SentenceType with an empty vertex buffer which will be used to store and render sentences. The maxLength input parameter determines how large the vertex buffer will be. All sentences have a vertex and index buffer associated with them which is initialized first in this function.
During the creation of the vertex buffer description for the sentence we set the Usage type to dynamic as we may want to change the contents of the sentence at any time.
The index buffer is setup as a normal static buffer since the contents will never need to change.
UpdateSentence changes the contents of the vertex buffer for the input sentence. It uses the Map and Unmap functions along with memcpy to update the contents of the vertex buffer.
Set the color and size of the sentence.
Calculate the starting location to draw the sentence on the screen at.
Build the vertex array using the FontClass and the sentence information.
Copy the vertex array information into the sentence vertex buffer.
ReleaseSentence is used to release the sentence vertex and index buffer as well as the sentence itself.
The RenderSentence function puts the sentence vertex and index buffer on the input assembler and then calls the FontShaderClass object to draw the sentence that was given as input to this function. Notice that we use the m_baseViewMatrix instead of the current view matrix. This allows us to draw text to the same location on the screen each frame regardless of where the current view may be. Likewise we use the orthoMatrix instead of the regular projection matrix since this should be drawn using 2D coordinates.

## D3dclass.h

We have also modified the D3DClass in this tutorial to incorporate blending states. Blending allows the font to blend with the 3D objects in the background. If we don't turn on blending we see the black triangles behind the text. But with blending turned on only the pixels for the text show up on the screen and the rest of the triangle is completely see-through. I won't get into great detail about blending here but a simple blend was needed for this tutorial to work correctly.
We have two new functions for turning on and off alpha blending.
We have two new blending states. m_alphaEnableBlendingState is for turning on alpha blending and m_alphaDisableBlendingState is for turning off alpha blending.

## D3dclass.cpp

We will just cover the functions that have changed in this class since the previous tutorial.
Set the two new blending states to null.
We have a new description variable for setting up the two new blend states.
First initialize the blend state description.
To create an alpha enabled blend state description change BlendEnable to TRUE and DestBlend to D3D11_BLEND_INV_SRC_ALPHA. The other settings are set to their default values which can be looked up in the Windows DirectX Graphics Documentation.
We then create an alpha enabled blending state using the description we just setup.
Now to create an alpha disabled state we change the description we just made to set BlendEnable to FALSE. The rest of the settings can be left as they are.
We then create an alpha disabled blending state using the modified blend state description. We now have two blending states we can switch between to turn on and off alpha blending.
Release the two new blending states.
The first new function TurnOnAlphaBlending allows us to turn on alpha blending by using the OMSetBlendState function with our m_alphaEnableBlendingState blending state.
The second new function TurnOffAlphaBlending allows us to turn off alpha blending by using the OMSetBlendState function with our m_alphaDisableBlendingState blending state.

## Graphicsclass.h

We now include the new TextClass header file.
There is a new private variable for the TextClass object.

## Graphicsclass.cpp

We will just look at the functions that have changed since the previous tutorial.
Initialize the new TextClass object to null in the class constructor.
We create a new view matrix from the camera object for the TextClass to use. It will always use this view matrix so that the text is always drawn in the same location on the screen.
Here we create and initialize the new TextClass object.
Here we release the TextClass object.
Here we turn on alpha blending so the text will blend with the background.
We call the text object to render all its sentences to the screen here. And just like with 2D images we disable the Z buffer before drawing and then enable it again after all the 2D has been drawn.
Here we turn off alpha blending so anything else that is drawn will not alpha blend with the objects behind it.

## Summary

Now we are able to render colored text to any location of the screen.

## To Do Exercises

1. Recompile the code and ensure you get a white "Hello" written to 100x100 on your screen as well as a yellow "Goodbye" beneath it.
2. Change the pixel color, location, and content of the sentences.
3. Create a third sentence structure and have it render also.
4. Comment out the blending calls in the GraphicsClass::Render function and set m_D3D->BeginScene(0.0f, 0.0f, 1.0f, 1.0f); in the GraphicsClass::Render function.
This will show why blending is needed.
5. Add the blending calls back into the GraphicsClass::Render function and keep m_D3D->BeginScene(0.0f, 0.0f, 1.0f, 1.0f); in the GraphicsClass::Render function to see the difference.