Pre-rendering SpriteFont Text for Improved Performance


No bones about it. Video games have a LOT of text in them. From character names to item descriptions to names for screen-clearing special attacks, there is a lot of text that, at some point or another, has to be rendered to the screen.

With XNA, rendering text to screen is a no-brainer. The SpriteFont implementation makes rendering strings to the screen with a variety of fonts trivially easy. There is one problem though: rendering SpriteFonts with DrawText() can be really slow.

Take a look at the screen shot below to get an idea of how much time it takes to render a screen full of text.

Each sentence is a separate DrawText() call of the same string. As you’ll notice, rendering 102 sentences takes over 13ms. That’s almost an entire frame at 60fps. Thankfully, there’s a simple trick you can use to eliminate this performance cost.

Less than a millisecond? What brand of witchcraft is this?
Simple pre-rendering, my friend.

Using a RenderTarget2D, it’s easy to render the text first to a separate texture just large enough to contain the text. After that, I can use the rendered texture instead of DrawText() to display my text on-screen.

Granted, this technique is most useful for static text that doesn’t need to change every few frames. If your text needs to change frequently, you’d probably still be better off rendering that text directly to the screen with DrawText(). That being said, most games have large amounts of text that doesn’t need to change once it’s been set, so those make good candidates for pre-rendering which allows you to save more performance for areas that really need it.

The code for my demo program follows:

#define PRERENDER_TEXT

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace LotsOfText
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        SpriteFont stopWatchFont;
        System.Diagnostics.Stopwatch stopWatch;

        const string displayText = "The quick, red Mario jumped over the goomba";
        SpriteFont displayTextFont;
#if PRERENDER_TEXT
        Texture2D displayTextTexture;
#endif

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 720;

            this.IsFixedTimeStep = false;
            graphics.SynchronizeWithVerticalRetrace = false;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            stopWatchFont = Content.Load<SpriteFont>("DefaultFont");
            displayTextFont = Content.Load<SpriteFont>("DisplayTextFont");

#if PRERENDER_TEXT
            Vector2 stringDimensions = displayTextFont.MeasureString(displayText);
            RenderTarget2D renderTarget = new RenderTarget2D(GraphicsDevice, (int)stringDimensions.X, (int)stringDimensions.Y);

            GraphicsDevice.SetRenderTarget(renderTarget);
            GraphicsDevice.Clear(Color.Transparent);
            spriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.PointClamp, null, null);
            spriteBatch.DrawString(displayTextFont, displayText, Vector2.Zero, Color.White);
            spriteBatch.End();
            GraphicsDevice.SetRenderTarget(null);

            displayTextTexture = renderTarget;
#endif

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
                Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            long ticks = stopWatch.ElapsedTicks;
            TimeSpan drawTime = stopWatch.Elapsed;
            stopWatch.Reset();
            stopWatch.Start();

            GraphicsDevice.Clear(Color.CornflowerBlue);

            Vector2 drawPosition = new Vector2(-350.0f, 30.0f);
            spriteBatch.Begin();
            const int rows = 34;
            const int columns = 3;
            for (int i = 0; i < rows * columns; ++i)
            {
                if (i % rows == 0)
                {
                    drawPosition.Y = 30.0f;
                    drawPosition.X += 400.0f;
                }
#if PRERENDER_TEXT
                spriteBatch.Draw(displayTextTexture, drawPosition, Color.White);
#else
                spriteBatch.DrawString(displayTextFont, displayText, drawPosition, Color.White);
#endif
                drawPosition.Y += 20.0f;
            }
            spriteBatch.End();

            spriteBatch.Begin();
            spriteBatch.DrawString(stopWatchFont, "Frame Time ms: " + drawTime.TotalMilliseconds, Vector2.UnitX * 500.0f + Vector2.UnitY * 10.0f, Color.DarkMagenta);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
Share this Article:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Print