Category Archives: C#

Markup text rendering in XNA

Update: New version, fixed some minor issues, add start()/stop() methods to support the video tag.

Now that I submitted my game to Dream.Build.Play 2011 and I’m all done with it I’ll try to post a few things I made while developing said game and may be useful to other XNA developers.

I’ll start with an update to the markup text engine/thingy I did to display the in-game dialog and help screens (I first wrote about in this post, look there for details and a bit of a tutorial on how to use it). Since that post I added a

Here it is in action, scroll down for source and demo project.

And the markup that generated the image above:

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Temporibus autem

Duis aute irure in reprehenderit.
Velit esse cillum dolore eu dolore eu.

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum. , temporibus autem quibusdam aut officiis debitis .
Et harum quidem rerum facilis est et expedita distinctio.

At vero eos et accusamus et iusto odio dignissimos ducimus!

Here is a list of supported tags:

  • sets the font and color. Nested text blocks are supported and will inherit any attributes from the enclosing parent tag.
  • obviously specifies an image and has color and scale attributes.
  • specifies a video and also supports the color and scale attributes.

  • adds a line break.
  • inserts a space.
  • is used for conditional rendering.

Download the source code, drop me a note if you use it in your game.

Note: The code is licensed under MS-PL

XNA AI Finite State Machine

Coding game AI naively with switch statements nested 3-4 levels deep is bad, really bad, really really bad (I just can’t find a better word), it starts simple enough – if this do that – and then it gets ugly real quick. I did not get to nest 3 levels of ifs but I was not very far from it either. There are a few approaches to coding game AI (GOAP seems interesting) but I have little time so it seems that the easiest way to solve my problem is an old friend, the Finite State Machine. A quick search of the internets revealed a number of C# FSM implementations but it seems that they were created to scratch specific itches that are almost but not quite exactly as mine, so I had to write my own. There is nothing special about it (I think it’s actually quite trivial) other than the fact that I could not find something like it and that’s the reason I’m sharing it. Also, the code is not really XNA or game or AI specific but I’m using it to implement AI in an XNA game so…

To see how it all started, this is the flow of one of the formation-flying enemies in Astralia:

Modeling the above flow with ifs and switch statements is possible but requires a level of obsessive compulsiveness that I do not have and after a little work I ended up with something more manageable that looks like this:

var idle = new State>("idle", null, null, null);
var follow = new State>("follow", null, null, null);
var lead = new State>("lead", null, EnterLead, null);
var rally = new State>("rally", Rally, EnterRally, null);
var patrol = new State>("patrol", Patrol, null, null);
var attack = new State>("attack", null, null, null);

idle.AddTransition(lead, () => Leader == null);
idle.AddTransition(follow, () => Leader != null);
follow.AddTransition(lead, () => Leader == null);
lead.AddTransition(rally, () => Members.Count rally.AddTransition(patrol, () => Members.Count == FormationSize);
patrol.AddTransition(attack, () => Target != null);
attack.AddTransition(patrol, () => Target == null);
aiMachine = new StateMachine

What happens should be reasonably obvious, first declare the states and then add transitions between them.

A state has a name (for debugging purposes mostly), a tag which is whatever you want to associate with that state and two more actions that get called when entering/leaving the state.

State(string name, T tag, Action onEnter, Action onExit)

Adding a transition to a state requires the next state and a condition function that “guards” the transition, the condition needs to be true for the transition to happen. If there are multiple transitions leaving a state they are simply checked in the order they were added and the first one that has the condition satisfied is used.

public void AddTransition(State<lT> nextState, Func condition)

All that is left now is to update the state machine in your game loop and do whatever you need to do with the state tag (in my case I have a delegate that I call).


And now for the code:

public class State {
internal readonly Action OnEnter;
internal readonly Action OnExit;
internal readonly List> Transitions = new List>();

public State(string name, T tag, Action onEnter, Action onExit) {
OnEnter = onEnter;
OnExit = onExit;
Name = name;
Tag = tag;

public string Name { get; private set; }
public T Tag { get; set; }

public void AddTransition(State nextState, Func condition) {
Transitions.Add(new Transition(nextState, condition));

internal class Transition {
internal readonly Func Condition;
internal readonly State NextState;

internal Transition(State nextState, Func condition) {
NextState = nextState;
Condition = condition;

public class StateMachine {
public StateMachine(State currentState) {
CurrentState = currentState;

public State CurrentState { get; private set; }

public void Update() {
while (MoveToNext()) {}

private bool MoveToNext() {
for (int i = 0; i < CurrentState.Transitions.Count; i++) {
Transition t = CurrentState.Transitions[i];
if (t.Condition()) {
if (CurrentState.OnExit != null) CurrentState.OnExit();
CurrentState = t.NextState;
if (CurrentState.OnEnter != null) CurrentState.OnEnter();
return true;
return false;

This is it.

HTML-like formatted text in XNA (fonts, colors and images)

Check out the updated version, now with a complete example project and MSPL licensing.

After looking for something that will help me display nicely formatted text in XNA I ended up
writing my own somewhat naive text markup rendering engine. I really like the result, the thing does text-wrapping with multiple fonts, colors and images and I even added conditional rendering, you can find the source code at the end of the post. For now here is what it can produce:

If you recovered after the crazy colors burning your retina keep reading. Here is the code that rendered into the abomination above:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Quisque tincidunt elit et augue viverra vel lacinia risus varius.
Morbi rutrum, orci auctor congue molestie.
Nibh neque semper orci,

at volutpat ligula libero sit amet sapien.

We are here.

We are there.

  • The tag sets font and color. Nested text blocks are supported and will inherit any missing attributes from the enclosing parent tag.
  • The tag obviously specifies an image and it also support a color attribute.
  • The
    tag inserts a line break.
  • The tag is the interesting one and is used for conditional rendering. I came up with it when I had to render text differently on Windows and the Xbox but I used it everywhere after that. Probably not a very good idea to use it too much.

The markup engine uses little strategies (I called them resolvers) to translate from an attribute string to whatever it needs to render the markup, e.g. the image resolver translates a string into a Texture2D. The source text is “compiled” into an representation that can be drawn repeatedly without generating garbage (at least this was my intention). Here is the relevant C#/XNA code:

public override void LoadContent() {
if (content == null)
content = new ContentManager(ScreenManager.Game.Services, "Content");
font = content.Load("Font1");


//setup the font, image and condition resolvers for the engine
//the resolvers are simple lambdas that map a string to its corresponding data
//e.g. an image resolver maps a string to a Texture2D
var fonts = new Dictionary();
Func fontResolver = f => fonts[f];
var buttons = new Dictionary();
Func imageResolver = b => buttons[b];
var conditions = new Dictionary();
Func conditionalResolver = c => conditions[c];
markupTextEngine = new MarkupTextEngine(fontResolver, imageResolver, conditionalResolver);

fonts.Add("Font1", content.Load("Font1"));
fonts.Add("Font2", content.Load("Font2"));

buttons.Add("Planet1", content.Load("Planet1"));
buttons.Add("Star1", content.Load("Star1"));
buttons.Add("Star2", content.Load("Star2"));

conditions.Add("IsCondition1", false);
conditions.Add("IsCondition2", true);

buttons.Add("B", content.Load("Textures/Controller/xboxControllerButtonB"));

var text = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Quisque tincidunt elit et augue viverra vel lacinia risus varius.
Morbi rutrum, orci auctor congue molestie.
Nibh neque semper orci,

at volutpat ligula libero sit amet sapien.

We are here.

We are there.

//generate the compiled representation
compiledMarkup = markupTextEngine.Compile(text, 800);

public override void Draw(GameTime gameTime) {
var location = new Vector2(100, 100);
//this is easy
compiledMarkup.Draw(spriteBatch, location);

Some things in the implementation are quite naive, my C# skills being what they are – I probably speak C# with a Java accent. The code is not very robust and the error reporting is terrible, the thing will basically explode with exceptions if there are any problems, but it does what I need it to do so here it is. Drop me a note and maybe show a link to here if you are using it.

Source code MarkupTextEngine.cs