Archive for the ‘XNA’ Category

Don’t Feed the Trolls available on Xbox Live Indie Games!

Friday, September 23rd, 2011

I am proud to tell you that my last game Don’t Feed the Trolls is now live on the XBLIG market. Here is the trailer:

Please download the game on the marketplace and tell me what you think about it!

As usual, I’ll post sales figures in a few weeks/months for the curious.

Have fun slapping trolls!

Useful C# and Visual Studio tips you might not know

Tuesday, May 31st, 2011

While working on my next game, I tried to keep notes of interesting tips I used. They are related to C# and Visual Studio.

Overriding ToString()

When debugging or prototyping, you often need to display complex objects on the screen on in the debugger output. A handy way to do this when dealing with complex classes is to override the ToString() member. Here is an example:

class ComplexClass
{
   int _number = 0;
   string _string = "My String";

   public ComplexClass( int n, string s )
   {
      _number = n;
      _string = s;
   }

   public override string ToString()
   {
      return String.Format( "{0} / {1}", _number, _string );
   }
}

ToString() is also used by the debugger in the Watch dialog.

?? operator

I discovered the ?? operator a few months ago. I don’t use it much but could be useful in some cases. It allows you to replace the following code:

if( a != null )
   b = a;
else
   b = c;

by

b = a ?? c;

New class template

When you create a new class (using the right-click on the project, Add, New Item…), the file created is not empty but already has a template and a few using statements. You can edit this template easily. For instance, I added a “using fg;” with my own game library to this template. The template is found in the Visual Studio directory: {Program Files}\Microsoft Visual Studio 10.0\Common7\IDE\VCSExpress\ItemTemplatesCache\1033\class.zip. There are templates for anything and you will probably want to edit a few of them.

new does not always allocates

In C#, even when using the new operator, you might not allocate memory. For instance, the following line:

Vector2 point = new Vector2( 10, 20 );

does not allocate memory, because Vector2 is not a class, but a structure. The rule is as simple as that: a class allocates memory (and returns a pointer) and a struct does not allocate memory. It’s simple, but often misunderstood, especially if you come from C++.

Add As Link source file

Recently, I re-used source files from a previous project for a new one. I used the Add Existing Item option but Visual C# creates a copy of the source file in the current project directory instead of referencing the old file. I want to reference the old file so that it can be modified in both projects. To avoid that, you must select the hidden Add As Link option, by clicking the small arrow next to the Add button of the dialog box.

add_as_link

Overloading the [] operator

I often have objects containing a list of items. For instance, in Spring Up Harmony, I have a Ball Manager used to manage and draw the balls. I found it very handy to overload the [] operator to access elements of the list inside the manager from the outside directly.

List<Ball> _balls = new List<Ball>();
public int Count { get { return _balls.Count; } }
public Ball this[int i] { get { return _balls[i]; } }

That’s it!

I hope you found some of the tips useful!

Feel free to share more tips in the comments!

Follow me on twitter or facebook to get notified of new posts.

Never released game design and prototype #2 : DJ Machine

Friday, April 29th, 2011

This is the second post of the series, you can read the introduction of the series in the first post.

Project 13

I will talk about a prototype called “DJ Machine” (Project 13), that I started while Spring Up Harmony (PC X360) was being approved for Xbox Live Indie Games. I was looking for something fun and that could only be done with XNA. I was playing DJ Hero at that time and logically started to create a simple program playing with the turntable (see image below). Nick Gravelyn already did some research on it and this information was very useful to get something working very quickly.
dj-hero-turntable

I didn’t want to make a clone of DJ Hero because I could not afford licensing many interesting songs and don’t want to compete with the AAA guys. After a few crazy ideas, I finally came up with the idea of manipulating a machine using the turntable. Each part of the turntable (scratch, buttons, euphoria, fx dial) activates/moves a section of the machine. Some of the inspiration came from a very old game called Night Shift where the player controls a worker that must take care of a machine and quickly becomes overwhelmed by the amount of elements requiring attention.

Screenshots and Video of DJ Machine

Here are a screenshot and a gameplay video of my prototype:

dj_machine_last_version

I removed the sounds in the video as I do not own the rights to some of them:

I suppose this requires some explanation. Refer to the image of the turntable while I explain the gameplay for those not familiar with the controller. The player is supposed to build objects using the “DJ Machine”. Of course, it’s still very abstract because of the programmer art.

  • Square items are coming from the left on the gray path. They stop at the first black square. Here, the player has to scratch with the corresponding button and direction (for example, blue scratch up, green scratch down). There are between one and three scratches to do per item.
  • When all the scratches for an item are done, the item moves to the next black square on the top right. Here, the player must spin the knob as fast as possible.
  • The item is then transformed in a shape (yellow circle, blue star or red octagon) that falls down the screen.
  • The player then controls the dark red claw with the cross fader (if the cross fader is on the left, the claw moves to the left, the player must move the cross fader back to center to stop the claw).
  • The player must move the claw below the shape items on the right and use the euphoria button to close the claw (keep euphoria button down) and catch the item.
  • He then moves the item to the corresponding area on the left and drop it by releasing the euphoria button.

There is also a penalty if the player activates elements when not needed. For instance, if he scratches when there is nothing in the top left section of the machine, the machine gets stucked and can’t be used for a few seconds.
You can also see the crosses on the top left (one is red, two are white on the screenshot). They represent the errors made by the player. After three errors, the game stops.
On the right, there is, from top to bottom the time, the score and the number of objects succesfully made. If the player drops an item when not on the proper location with the claw, the object is lost.
That’s basically it. The game was supposed to be played in short sessions where items come faster and faster.

I also planned another game mode where the player first choses between different music styles (techno, rap, funk…) and then scratches and mixes with proper sound samples on an abstract background. I named this game mode Freestyle DJ. Here is a gameplay video:

Sadly, without sound, it’s not very exciting but it is actually working pretty well. There is two short music loops that the player could mix with the cross fader, scratches play sound effects and fx dial speeds up/slows down the music.
The graphics in the background are made from Spring Up Harmony’s algorithm.

Design Document (notes)

Here is a copy of my design notes. I just translated the bits in french and added comments in blue. It’s in chronological order, it means that ideas on top have no connections with “DJ Machine” prototype and were discarded:

Byala 80 pts (a game (strange) name with a price: I think I made a mistake by pricing Spring Up Harmony at 240 pts at the beginning, so I precised very early I’d put the next one at 80 ;) )
Musical Arts (other idea : just playing music with nice backgrounds : not really a game, but gave birth to the freestyle game mode)
Platform game playable with turntable (first game idea: platform game (inspiration: Donkey Kong Country that is playable with drums))
Playable with guitar? drums?
Original rendering : squares, blobs, glow (Inspiration: the Sony PS3 dashboard but I finally used Spring Up Harmony’s algorithm as a starting base)
Night Shift (from here, I’m going toward the design described above, citing my main inspiration)
A cube comes to a platform, after 1 to 3 scratches, it goes in step 2, after fx dial, it goes in step 3. Movement with XFader, player has to make the cube fall in the right hole with euphoria (this is the sentence that resumes it all ;) )
Show a message to the player if he’s playing with a pad.
Classic “Freestyle DJ” game mode
Choices betwee left/right handed and buttons on the left/right (same as in DJ Hero)
Different difficulty levels: Tutorial, Easy, Medium, Hard, Expert and Hardcore
Game over because of three errors or machine full if player does not play fast enough
Restrictions of the free version: Only 4 difficulty levels out of 6, DJ Machine sessions only 3 minutes long, Freestyle DJ sessions only 1 minute long.

Here is a early prototype screenshot I used to set up of the gameplay:

dj_machine_history

Why I didn’t complete it, and thoughts

I started this project mostly for fun, to try to see how was working the turntable. I hesitated to complete and release it on XBLIG. I didn’t, because:

  • The market share is very small. According to numbers (DJ Hero, DJ Hero 2 and consoles) I could find, I estimate between 1.5 and 3% of xbox players have turntables (probably many DJ Hero 2 players also own DJ Hero 1). Also, XBL Indie Games are approved by other developers and you need multiple votes by creators to get your game on XBox Live. Therefore, I would need actual XBLIG developers to have turntables (well, that’s not entirely true as the game would be playable with only a pad too, but they would not fully test the game and might not want to try it). I already had to remove french support in Spring Up Harmony because I could not find two or three french-speaking developers. I honestly think there are more developers speaking french than developers with a working DJ Hero turntable.
  • Gameplay variety is very low. People might argue that DJ Hero also have few variety, but it’s of course in the musics and leaderboards that the players find variety even if the gameplay is roughly always the same. In DJ Machine, only speed brought variety.
  • However, now that the DJ Hero series will not be completed (LINK), DJ Hero players might love to be able to use their turntables again. :)

Today, I still don’t plan to work on this prototype again, but who knows. ;)

Feel free to comment and share ideas and talk about your unfinished projects in the comments section.
You can also follow me on twitter or facebook.

My Experience Converting from XNA Game Studio 3.1 to 4.0

Sunday, October 31st, 2010

Microsoft released a big update to XNA Game Studio with version 4.0. The main improvement is Windows Phone 7 support. I will probably not develop for WP7 (see reasons below) but I still need to upgrade my current Xbox 360 project from XNA 3.1 to 4.0.

The process was not as smooth as I though it would be, so I wrote this article to help people transitionning from 3.1 to 4.0.

Upgrading to XNA 4.0

To install Game Studio 4.0, you normally need Windows Vista or Windows 7. However, Microsoft made a version for Windows XP working only for Windows and X360 projects. I don’t want to buy a new OS, therefore I am going with this “light” version. However, this version does not support Windows Phone 7. That’s a shame as I’d be interested to try things with a touch screen but upgrading to Windows 7 is expensive.
To install GS 4.0, you need Visual C# 2010 Express, and to get Visual C# 2010 Express on XP, you need the Service Pack 3. Problem: SP3 install failed for some strange reason. I could find this article on Microsoft’s site: When you try to install Windows XP Service Pack, you receive the error message “Access is denied” and the third solution consisting in running command line utilities solved my problem. I was not really sure what I was doing, but it finally worked :)

Converting the Project

When opening a GS3.1 project with Visual C# 2010, it automatically tries to convert it to GS4.0. Each project of the solution is converted. Of course, if you are using a compiled library (dll), you need to get or compile a 4.0 version. I had to re-compile Box2D.XNA and download the latest version of TiledLib’s dlls.

However, I had a problem when compiling for the first time, with the following error: “The referenced assembly “Microsoft.Xna.Framework.Content.Pipeline, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553″ could not be resolved because it has a dependency on “Microsoft.Build.Utilities.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” which is not in the currently targeted framework “.NETFramework,Version=v4.0,Profile=Client”. Please remove references to assemblies not in the targeted framework or consider retargeting your project.”
Luckily, one guy had the same problem on Creators Club forums and the solution given by Stephen Styrchak solved my problem. It should be solved by changing the Target Framework in the application properties, but the option is greyed out. I had to edit my csproj manually with a text editor.

API changes

Ok, this is where the conversion really starts: fixing compiling errors due to numerous API changes in the framework. Here is a list of the main changes that affected my project:

Color struct: The Color struct has moved to XNA.Framework (from Xna.Framework.Graphics). A few constructors have also been removed, such as this one: Color( Color, float). I used it a lot. Easy to fix but Color is widely used in my project so that involved many changes.

Vertex buffers and Effects: There has been a few changes with vertex buffers and effects. There are many portions of code to update because of that but the new API is really simpler and better. For instance, you do not have to do Begin/End on effects and each pass, but you just use Pass.Apply: Less code to write for the same result. Also, when you have standard vertex types, you do not need to use VertexDeclarations. The GraphicsDevice.VertexDeclaration member has been removed. Again, less code to write!

Pixel/Vertex Shader compiler : I found the compiler more strict. For instance, I had a texture and a technique with the same name, it did compile with GS 3.1, but not with GS 4.0. I also had a pixel shader function called PixelShader and it does not compile on GS 4.0.

Point Sprites: They simply have been removed. I don’t use them in my current project, but my last game Spring Up Harmony used point sprites for the back ground effect. It takes some time to update to triangles.

Render Targets: In addition to a few simple API changes when setting render targets, the most notable change is the removal of the ResolveTexture2D class. You now need to use a RenderTarget2D and can’t directly get a texture from the backbuffer.

Storage changes: A few API changes have been made in the storage too. Biggest change is the OpenContainer method that is now asynchronous (Begin/EndOpenContainer). A few functions have been renamed too.

Executing of the Game

Ok, now that the game compiles, let’s run it! And another problem occured here: The game does not run at all and asks for a DX 10 graphics card. Easy to fix: modify the XNA project properties and choose “Reach” instead of “HiDef”. Difference is that Reach has a limited API for WP7 but should be enough for me.

References

Here is a list of resources/blogs that I found very useful while converting my game to GS 4.0. You should read them all ;)

MSDN Page: What’s new in XNA Game Studio 4.0

Shawn Hargreaves’ blog: articles on Vertex BuffersEffects, removal of point sprites, render targets.

Nick Gravelyn’s blog: article on storage in GS4.0

Done

And voilà! Conversion is done and the game runs properly (I did not test thoroughly yet). I was worried the new default use of premultiplied alpha would cause problem but I haven’t found any. If you had a problem converting your project that is not mentioned here, feel free to comment!

3 Simple Tips to Avoid Memory Allocations with XNA/C#

Friday, May 21st, 2010

Long time without posting. I’ve spent a lot of time working on the game, contracting art, buying sound effect and music assets, designing the levels… New screenshots/video should come very soon.

Anyway, back on topic: when developing from C++ to C#, I found out very strange that you can allocate memory but you cannot free it and have to let the garbage collector do it. But I finally got quickly used to it and found it quite handy… Until I found out that garbage collection is not free and usually causes framerate drops, especially on X360.

clrprof

Using the CLR Profiler (screenshot above), you can easily see where you are wasting memory (well, it can be scary the first time you see it but in fact, it’s easy). I nearly removed all my runtime allocations with this tool, here are the few tips that can be useful:

1. Be careful with the class string

String is allocating memory every time it returns a new string. StringBuilder is the key to the problem. I didn’t even know what StringBuilder was before working on memory and now I use it everywhere I need to take care about memory. There are some awesome tips (and source code) about StringBuilder on Gavin Pugh’ blog. Especially this and this. You have everything you need now :)

2. Reuse your lists

I had multiple sections of code creating a temporary List<> in order to add elements to need a special treatment. This was in an update function in my case. It is handy and fast to write code like that, but it allocates memory. To fix this, I know have the List<> as a member of the class. I clear it and reuse it when needed. When creating a list, you should use the constructor with an int used to define the default capacity of the list. (List<Vector2> l = new List<Vector2>(64) for instance).

3. foreach loops

I converted my foreach loops in C++ like for loops and it saved me some allocations. Memory allocated due to foreach loops on lists is showing up in the CLR Profiler as System.Collections.Generic.List<T>.

Conclusion

I hope you’ll find this useful. In Spring Up Harmony, I still have some run-time allocations, mostly in the particle engine, when a new fx is launched (I use Mercury for now). However, it seems that the garbage collector is not causing hick-ups therefore I’m ok with it.

Yes, multi-threading in XNA/C# can be that simple!

Wednesday, April 14th, 2010

Multi-threading is often causing problems for multiple reasons: synchronization, deadlocks, concurrent access to memory… But with my recent experience with multi-threading in XNA/C#, you can really do simple and efficient optimizations.

While looking for possible performance improvements in Spring Up Harmony for Xbox 360 (PC), I have seen a simple situation really suited for multi-threading. You can see that situation with the following screenshot of my in-game profiler (click to enlarge):
Frozax-4
I have two tasks with performance issues since I started to run the game on Xbox 360 : the dynamics of the background effect and the computation of the estimation of the launch of the ball (running a simplified physics simulation multiple times, through Box2D.XNA). On this screenshot, these tasks are called VelGrid.U(9) and Launchers.U(14). The first part of VelGrid.U (Comp.Balls,10) uses the data of the physics simulation but DynaColLines(11) doesn’t. Therefore, the VelGrid.DynaColLines and Launchers.U are totally independent with each others. No data is shared between these code sections. Perfect candidates for my initiation to multi-threading in XNA! :)

The e-book found here (recommended in multiple threading articles) is really awesome and helped me find the algorithm I need to use. I want to start the Launchers.U at the same time than VelGrid.DynaColLines and wait until both are finished. I know this is not optimal, but it allows me to simplify the problem and avoid so many threading pitfalls.

I just have to use two AutoResetEvents. The Launchers.U section is created in a thread and waits for a “Go” signal from VelGrid. After doing its job, it sets a Ready signal so that VelGrid knows when to carry on after doing its own stuff. Two different cases can happen, depending on which section finishes before the other.

Here are screenshots of the in-game profiler showing the differences (taken on X360). Every code section prefixed by a * means it’s executed on the thread.

Case 1 : The code on the main thread completed before the code on the worker thread:

thread_slower
The Velgrid section has to wait for the Launchers to complete, shown with the red arrow.

Case 2 : the code on the main thread completed after the code on the worker thread:

thread_faster

The thread is idle while the main thread still works (red arrow).

With this simple threading mechanism (coded and tested in a few hours only), I have been able to optimize the game. In the basic test level shown here, instead of 2.3 + 3.1 = 5.4 milliseconds spent on the main thread for both features, the game now spends 3.6 milliseconds, running two threads at the same time (33% gain). In this test scene, the Velgrid.DynaColLines is “free”.

Since I took these screenshots, I have made a few more changes : now, the whole Box2D update used while the game is in motion is threaded too.

Last important thing to know, on Xbox 360, you must choose which core to use for your thread. Just read the msdn page about the SetProcessorAffinity, everything you need to know is here. You can see in this article that I still have a few cores available :)

In conclusion, if you have independent sections of code that take some time to run, you can improve that very quickly using this method.

On-screen profiling for XNA

Wednesday, April 7th, 2010

A few days ago, I read an article called Among Friends: How Naughty Dog Built Uncharted 2. The interesting screenshots on the third page gave me the urge to create what I call an “on-screen profiling” tool for Spring Up XNA. I talked before about profilers and how to use them to find which sections of your code need to be optimized. But a visual tool is really handy, because it’s real time, and with Edit and Continue on PC, you can even see your improvements live!

So, I spend some time working on it, and here is a sample screenshot (click to enlarge):

onscreen_profiling_sample_x360The bars show the timeline of the current frame. In the bars, there is the name of the section. For clarity, all profiled sections are also displayed in plain text with the following informations: Name, Time elapsed this frame (in millisecond), smooth time elapsed, percentage of the 60 fps frame (16.6 ms). The vertical magenta line is the limit of the 60 fps frame. On this screenshot, my objective of 60 fps is not met, there are some bars displayed after it :)

I am really happy with the results, you instantly see where optimization is needed and you also see the results quickly. For instance, after seeing the previous screenshot, I concentrated on the “Velgrid.D” section (section drawing the background effect that is seen in motion here). After some improvement, it still was not fast enough. I noticed that the problem was simply the overhead of calling SpriteBatch.Draw more than 5000 times. I therefore decided to write my own vertex+pixel shaders and you can see the result here:

onscreen_profiling_final_x360It’s now so fast that we can’t even see the name of the section in the bars and I have to have a look at the list to see the exact time taken by this section of the game (number 15).

The profiling works obviously on both Xbox 360 and PC so I could compare both hardware. As I could read here and there, the X360 build is much slower than the Windows one. I made two screenshots of the same scene with a scale of the bars so that the length in pixels of the full frame is around the same on each platform. Here is the screenshot of the windows build that you can compare to the first screenshot of this post: 
onscreen_profiling_pc_scaled

The “slower” sections are not the same. Globally, the X360 is better at using its GPU and the PC using its CPU. Of course, this is heavily dependant on the PC platform. For information, I am using a 3.4 GHz computer with a X850 graphics card.

And just for fun :) , the first screenshot of the profiler on X360, before I started any optimizations:

onscreen_profiling_first version x360The frame took 165% of my objective target frame (60 fps). I can’t even see it all on screen. I am now at 75% of the frame, and with an additional feature (glow around objects, section 9 on the second screenshot).

So the small amount time taken to make this in-game tool is very well spent. It’s obviously quicker than running a profiler and waiting for the results, even if it’s not as precise. And the great thing is that this was easy and interesting to program :)

First Run on Xbox 360 : Problems and Solutions

Friday, April 2nd, 2010

I decided about a month ago to start working on the Xbox 360 version of Spring Up in April. I think it can be interesting to share my experience about that.

Part 1 : XNA Creator Membership

Basically, you just need to pay creator membership (99 € for one year in Europe), launch XNA Game Studio Connect on your console and that’s it.

Problem 1 : You have problems to redeem your XNA account to a new X360 profile?

Solution 1 : Do not mix up your forum name and GamerTag. Yes, this one was easy but it took me at least 30 minutes to find out what was happening. :)

Problem 2 : XNA Game Studio Connect does not recognize your account as premium when you launch it even though you paid for membership?

Solution 2 : You have to wait for some time (a few hours, maybe half a day) and everything will be fine. Quite frustrating, I know.

Part 2 : Compiling your game for Xbox 360

Microsoft made something simple : just right click on your project in Visual C# and choose “Create copy of Project for Xbox 360″. I took my main project and all the dependencies were converted too.

Problem 3 : You have very strange compiling errors? When converting Box2D.XNA, I had weird errors such as “Class C does not implement inherited abstract member M” AND “no suitable method found to override M”.

Solution 3 : Make sure you use the proper version of assemblies. I don’t know why but the converter put assemblies of XNA 3.0 instead of 3.1. Using 3.1 assemblies fixed my problem.

Problem 4 : The code does not compile but it works fine on Windows?

Solution 4 : Make sure you do not use windows specific code. You will be able to see warning icons if you have invalid assemblies in your Xbox 360 projects. If you want to keep windows specific code, just use #if WINDOWS / #endif so that it compiles properly on Xbox 360. In my case, my level and dialog box editors are only available on windows because it needs to create XML files.

Problem 5 : You can’t build your XNB data from XML using your own classes?

Solution 5 : Make sure the Content projects still have references to windows builds. Resources are built on the development computer, using the windows assemblies.

Part 3 : Running the Game on Xbox 360

Problem 6 : Code 3 Error?

Solution 6 : When you have Code X errors, it is because the console hangs without being able to break or throw an exception to the debugger. To track this problem, I simply traced the code I suspected. As the problem happened on a specific action, I could easily see where was the problem. My problem was just a null pointer access that happens only when there is no savegame. I always have a savegame on PC, so I did not see the problem before. The strange fact is that when I traced the code the second time, I properly had the NullPointerException.

Problem 7 : Your game is slow?

Solution 7 : I knew Xbox 360’s are usually slower than PCx with XNA but I was still very surprised my I ran my game for the first time. I immediatly launched a release build to try to reassure myselft but it’s still quite slow. I am not sure what is the problem for now so I will improve my profiling code to see which GameComponent is the problem.

Conclusion

That’s it for my first run on X360. I hoped this helped some of you!

Measuring game performance : framerate is not everything

Thursday, March 11th, 2010

I am currently having a few problems with performance in Spring Up XNA. I have two features that are too expensive in processing power : the background effect and the computation of the preview trajectory of the ball.

I know these features are not usable at this cost because as soon as I activate one of them, my framerate drops and the game does not run at 60 FPS. When your game runs at 60 FPS, everything’s fine. When it does not, how can you tell how “far” you are from it. And because XNA is trying to catch up when your game is slow, this is even more obscure (there is a very good article on Shawn Hargreaves Blog about this topic called Understanding GameTime).

fpsTherefore, in order to have accurate and useful performance information in real-time , I am displaying on screen the time spent to compute and draw the last frame, in milliseconds.

This is done easily using the Stopwatch class. This class is standard C# system library, it is not part of XNA. It is very easy to use:

stopwatch.Reset();
stopwatch.Start();
// Code to time here
stopwatch.Stop();

You just have to time the whole Update and Draw functions. Then you can read the number of milliseconds directly in the ElapsedMilliseconds member of Stopwatch. However, as this value is a long type, I prefer to compute the number of millisecond more precisely using this code:

(float)StopwatchUpdate.ElapsedTicks/(float)Stopwatch.Frequency*1000.0f

And to display it properly, I use the following formatting:

string fps = string.Format( "fps:   {0:00.0}\nupdate:{1,4:00.0}\n
draw:  {2,4:00.0}", _fps,
(float)StopwatchUpdate.ElapsedTicks/(float)Stopwatch.Frequency*1000.0f,
(float)StopwatchDraw.ElapsedTicks/(float)Stopwatch.Frequency*1000.0f );

I first thought that the numbers would change so quickly that it would not be usable but it’s pretty constant in my game. I can see huge differences when disabling some GameComponents. It is also useful to see if you spend more time in the update part or the draw part. You must have separated game logic and rendering properly, of course.

I told before in this blog that you must not spend time optimizing when you do not need too. But having this few lines of code is harmless and can be useful while adding new features:

  • If you see that you spend 5 more milliseconds in this session than in your previous one, you may need to have a closer look at this new code.
  • As Spring Up XNA is heavily using dynamics (through BOX2D), I can also compare the performance of the different levels.
  • You can see when a single frame takes much longer to update/draw (choppy framerate).

Hope this helps!

NProf : A Simple, Efficient and Free XNA Profiler (3.1 and 4.0)

Sunday, February 14th, 2010

Update: I have many visitors coming here from search engines. So here is a quick update if you want to use NProf with XNA 4.0. When you run NProf with your game, if the UI of NProf stays empty after running your game, it’s because you are running a XNA 4.0 game. There is a workaround here: Run NProf.exe with a .bat containing:

set COMPLUS_ProfAPI_ProfilerCompatibilitySetting=EnableV2Profiler
NProf.exe

Original post:

On its google code page, NProf is described as a statistical profiler for .NET applications. Good news: XNA being .NET, it can be used to profile games.

It’s well known that in order to optimize, you first need to find what part of your code is slow. That’s where a profiler comes handy, it finds the bottlenecks of your game and then you can optimize what needs to be.

The title of the post says it all, NProf is trivial to use, efficient and free. Once you download it, you select your XNA game executable, play it for some time and that’s it! I spent some time trying to find great profilers when I developed for PC and Mac but could not find anything really usable and affordable. I finally timed critical code sections with custom code and studied the log manually. Fortunately, NProf does all that for me in XNA.

I had a few surprises when I ran NProf. For instance, yesterday I could see that 21% of the game was spent in one method:
Color.Color( Vector3 )

This XNA constructor converts a Vector3 in a Color and it is called a lot in my game to create my background effect (see an old version in motion here). In this constructor, the expensive call is PackUtils.ClampAndRound. I do not have access to this code, but I can use another basic constructor and do the conversion myself. Here is what I ended up doing:

Before
Color col = new Color( vColor +
    new Vector3( start_val, start_val, start_val ) );
After
int r = (int)(( vColor.X + start_val) * 255 );
int g = (int)(( vColor.Y + start_val) * 255 );
int b = (int)(( vColor.Z + start_val) * 255 );
Color col = new Color( ( r > 255 ) ? (byte)255 : (byte)r,
    ( g > 255 ) ? (byte)255 : (byte)g,
    ( b > 255 ) ? (byte)255 : (byte)b );

The new code doesn’t clamp values below zero but I don’t need that feature. The really important thing is that it is now more than 12 times faster than before!

Without NProf, I would not have guessed that this constructor was that critical.

The main problem I see with NProf is that it only profiles your game on Windows and bottlenecks may be different on the X360.

Anyway, I really advise you to run your game in this profiler before you optimise anything. Be sure to use a release build.

Feel free to share your experiences with NProf!