Wednesday, September 13, 2006

FRAMERATE COMPONENT FOR XNA

Just a quick note: I have posted the source code for a simple component that calculates and display the framerate of your XNA-game project.

Considerations:

  • You might change the namespace in line to your game's namespace.
  • Currently, the game window's title will be used to display the framerate (this will change when XNA supports fonts). As a workaround, you can use garykac's bitmap fonts example to modify this behavior.
  • If "Enabled" is set to false, framerates are not calculated (Current is set to 0).
  • If "Visible" is set to false, the current framerate value is not displayed (but yet it can be calculated if enabled).
  • When you want to show the decimal part of the framerate value (that is, "ShowDecimals" is set to true), you can set the display format to the fixed one (like "0.00").
  • You can also set whether the time step must be fixed or not.
  • You are free to modify/optimize the source code as desired. Please share your optimizations with the community.

Enjoy!!!

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Components;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame1
{
/// <summary>
/// Simple class to calculate the frame-per-seconds rate of your game.
/// </summary>
public sealed partial class Framerate : GameComponent
{
#region Instance Fields

private float deltaFPSTime;
private double currentFramerate;
private string windowTitle, displayFormat;
private bool enabled, visible, canDraw, showDecimals;

#endregion

#region Instance Properties

/// <summary>
/// Gets the current framerate.
/// </summary>
/// <remarks>
/// The 'Enabled' property must have been set to true to retrieve values greater than zero.
/// </remarks>
public double Current
{
get{ return this.currentFramerate; }

}

/// <summary>
///
Gets or Sets a value to enable framerate calculation.
/// </summary>
public bool
Enabled
{
get { return this.enabled; }
set
{
this.enabled = value;
this
.currentFramerate = 0;

if (this.Game != null && this.windowTitle != null && !this
.enabled)
this.Game.Window.Title = this.windowTitle;
}
}

/// <summary>
///
Gets or Sets a value to display framerate on screen.
/// </summary>
/// <remarks>
///
Currently, the framerate is shown in the window's title of the game.
/// </remarks>
public bool Visible{

get { return this.visible; }
set
{
this.visible = value;

if (this.Game != null && this.windowTitle != null && !this
.visible)
this.Game.Window.Title = this.windowTitle;
}
}

/// <summary>
///
Gets or sets a value indicating whether the time step must be fixed or not.
/// </summary>
/// <remarks>
///
If set to true, the game will target the desired constant framerate set in your main class ('Game1', by default).
/// </remarks>
public bool
IsFixedTimeStep
{
get { return this.Game.IsFixedTimeStep; }
set
{
if(this.Game != null)
this.Game.IsFixedTimeStep = value;
}
}

/// <summary>
///
Gets or sets a value indicating whether the framerate will display decimals on screen or not.
/// </summary>
public bool
ShowDecimals
{
get { return this.showDecimals; }
set { this.showDecimals = value; }
}

/// <summary>
///
Gets or sets a value indicating whether the decimal part of the framerate value must be display as fixed format (or as double format, otherwise).
/// </summary>
/// <remarks>
///
The 'ShowDecimals' property must be set to true in order to set the proper format.
/// </remarks>
public bool
FixedFormatDisplay
{
get { return this.displayFormat == "F"; }
set { this.displayFormat = value == true ? "F" : "R"; }
}

#endregion

#region Constructors

/// <summary>
/// Parameterless constructor for this class.

/// </summary>
public
Framerate()
{
InitializeComponent();
}

#endregion

#region Instance Methods

/// <summary>
/// Called after game initialization but before the first frame of the game.
/// </summary>
public override void Start()
{
this
.canDraw = false
;
this.currentFramerate = 0;

this.windowTitle = this.Game != null ? this.Game.Window.Title : String.Empty;
}

/// <summary>
///
Called when the gamecomponent needs to be updated.
/// </summary>
public override void
Update()
{
if (this.enabled)
{
// The time since Update() method was last called.
float elapsed = (float)this
.Game.ElapsedTime.TotalMilliseconds;

// Ads the elapsed time to the cumulative delta time.
this
.deltaFPSTime += elapsed;

// If delta time is greater than a second: (a) the framerate is calculated, (b) it is marked to be drawn, and (c) the delta time is adjusted, accordingly.
if (this.deltaFPSTime > 1000)
{
this.currentFramerate = 1000 / elapsed;
this.deltaFPSTime -= 1000;
this.canDraw = true;
}
}
}

/// <summary>

///
Called when the gamecomponent needs to be drawn.
/// </summary>
/// <remarks>
///
Currently, the framerate is shown in the window's title of the game.
/// </remarks>
public override void
Draw()
{
// If the framerate can be drawn, it is shown in the window's title of
the game.

if (this.visible && this.canDraw)
{
string currentFramerateString = this.showDecimals ? this.currentFramerate.ToString(this.displayFormat) : ((int)this.currentFramerate).ToString("D");

this.Game.Window.Title = "FPS: " + currentFramerateString;

this.canDraw = false;
}
}

#endregion
}
}

[We will discuss and focus on XNA GSE later.]

Tuesday, September 12, 2006

SAY AGAIN ... GAME DEVELOPMENT?

Now that you have done some deep research on OOP paradigm and C# programming we can approach a bit further to the main topic of this site. Shall we? (not there yet but getting closer, be patience)

Well, the main three questions that you should ask your-self before jumping into deep waters are:

  1. Which is the story-line of my game?
  2. Will I design and program the game engine by my-self?
  3. How the h#$& am I going to finance this project?

And yes, this is a short list.

1. Every game -even the simplest of all out there- has a plot, a story, a script; something that tells the player what the game is about, what he/she might do during game-play, the characters/roles that do exist, etc.

If you think it thoroughly, you may end up finding a bunch of similarities with filming: you prepare the set, you place the characters, you establish the rules, you are the director. The main difference is that game development goes some steps further since everything happens real-time and not in a (fully) deterministic way (meaning, every time the game is played things always differ sometime, somewhere, somehow).

But the point is: your game has to count on a script. At least some sketches of a plot (general idea), spots (places in the universe of the game), characters (who's the good, the bad and the ugly), missions ("take the flag"), stages (level 1, ..., level n) and any other objects/subjects of relevance (like key dialogs and possible cut-scenes, if any).

Lot of games have soared because they lacked of a (good) script. Technically speaking, these games may have introduced advances in the fields of game programming, superb graphic effects (GFXs) and astonishing sound effects (SFXs), but gamers flamed it -or even the game never shipped, because of a bad-designed, repetitive (monotonous sequel) or non-existing story-line.

It is always educational to read post-mortem articles of abandon-ware and finished products. Also comments of gamers about published games -AAA or not; you will be surprised to find that sometimes (rarely) a game succeeds even though GFXs are not that good.

2. Before starting to program the game itself there is always a "Game Engine" that lays beneath it. So, what is this "engine"? Think of it as the logic structure that will support the implementation of your game.

You will need to handle lots of aspects like, among others:

  • Loading/unloading assets to/from memory: meshes, levels, sounds, etc..
  • Rendering process: fixed pipeline vs. Shaders, lighting and shadows (static vs. Dynamic), post processing effects.
  • General mechanics (the so called "Physics"): collisions, gravity, rigid bodies, dynamic action, reaction and interaction of objects (cars, spaceships, .
  • Artificial Intelligence ("AI"): finite state machines, neural networks, flocking, etc.
  • User Input/Output: mouse, keyboard, joysticks, (force-feedback) game-pads.
  • GFXs: particles, billboards, water, clouds, skies, backgrounds in general, day/night cycles, lens flares.
  • SFXs: mono/stereo sounds, and 3D sounds.
  • Music: start/finish loop, midi or pre-recorded?
  • Story: cut-scenes management.
  • Main loop process: one thread vs. Multiple threads.
  • Gameplay: single-player vs. multi-player.
Ufff! I'm just tired of simply mention it, mate. You can build a generic engine (it can be used on other game projects of different types) or one specific to your (type of) project (it can be only used to produce, say, racing games or sequels of your game). Then comes the game programming: type of game, menu of the game, levels of the game, etc.

So there are two stages of implementation: (I) the game engine, and (II) the game.

The good news: you may not need to program a game engine and concentrate on the game itself. The bad news: even so, you will still have to deal with the above-mentioned areas. It's important that you know in advance that an engine will not handle all things for you, but provide you with "pre-made" implementations that you could use in order to handle those things. So where's the catch?

There are plenty of (full or partial middle-ware) engines out there you can integrate to your projects and use as a base for your games. The problem is that you have to integrate them properly, like assembling a puzzle. And this is not always that easy. As we will see in future articles, not all of the engines available in the market:
  • Handle all of the areas of a game as you wish (so you may end up bringing together multiple "partial" engines/components or implemeting by your-self the ones that there is lack of),
  • Target the .NET technology (you may end up using a third-party wrapper or creating your-own), and
  • Are free and/or royalty free (very important point).
Therefore, it's a trade-off:
  1. If you decide to design and implement (all of some of the aspects of) the game engine by your-self you could get trapped in something that either is out of your league, takes so much time that when your finish it you have not time/money left to implement the game or the standard technology has changed in the industry, or you decide to quite your original project and enter the game-engine buisness (that is, you offer your engine to the market in different flavors and licenses as many Companies do), and
  2. If you decide to use third-party engines -since there has been lately a boost in the number of engines available, you will have to choose carefully the one suitable for your project after a lot of testing: performance, bugs, support, how easy it can be integrated to your project (programming language, technology, etc.) and last but not least, price plus terms and conditions. Switching engines in a middle/advanced stage of the development process of a project is always very expensive in terms of time, effort and money. The nearer your project's deadlines are, the worse the price your project will pay ...
As any trade-off, a bad decision could result in "no shortcuts" for you and your team.

3. Tough one. Maybe you have resolved both two above with superb ease, but let's face it: do you have the needed resources to back up your idea from scratch to completion? Or do you know someone willing to finance your "Know-how"?

Game development is not a game. Period.

If you are (just about to get) in, you'd better realize that in order to succeed -either as a "pro" or as an "indie"- you will have to work full time on the project, or you will be eventually getting out of the industry with your tail between your legs.

And by "full time" I mean that you cannot share your time with other jobs if you expect to finish and ship your creation this century. Exceptions exist but it's a general rule.

Thus, the problem is: you have an idea, you believe in your idea, you have played tons and tons of videogames so you know what gamers want ... ok, basically, you feel in your gutts that your idea will rock ... now, "who is with me?" (you see that your shadow start to run away from you ... sad).

You need to feed your-self and -in many cases- your family. Plain and simple. So it is hazardous to quit a job to pursue a dream. So, unless you abandon your idea of being and "indie" and start looking for a job in the industry (or the worst-case scenario for you: getting back to your previous job totally defeated), you better start looking for ways of raising money to support your project. What in fact you should have been done/assessed before jumping to the swimming pool (aways look for water first).

There are many ways of accomplish this task, like:

  1. You have a job for years so as to save the money you will need (or that you think you will) to go on "solo" later.
  2. You start a joint venture with other people with the same goal (team), sharing risks, costs and profit, proportionally.
  3. You managed to find someone that know someone else that knows how to contact a final someone else who -maybe and almost remotely- could think of invest some capital in your project and are in the talks with this visionary ... ejem! ... businessman. In general, the percentage of your final proceedings in this situation will be as low as it could get (you knew that, of course). Risk-reward law.

There is some sites with interesting figures on their projects' costs and profits.

Dissapointed? Don't. Just bear in mind that nothing is as strightforward as it looks at first sight. Being and "indie" is always complicated. You don't have access to the same quantity and quality of resources that big companies have. It doesn't rain money and you have to eat. Time won't wait for you. A year and a half has gone, you are still not even close to a beta and the next season of "Lost" is coming ...

However, in spite of all of the above, you got the strenght to overcome these assymetries, right? That is one of the main things that will help you achieve your goals: your conviction. A needed but not sufficient condition. You will have to combine it with other factors like, among others: your capacity to solve problems efficiently, your speed to accommodate to changes in the industry (like techniques, technology, game-quality standards and so on), your skills as a developer/programmer, your wisdom to deal with potential investors and customers, your means to promote your game worldwide, the moral support of your family and close friends, and your growing collection of four-leaf clovers!

It always start with a dream ... now, let's check on the results of those six number I picked for yesterday's Loto ...

[Next time we will be talking about some of the .NET-based game engines out there so that you can go and check them]

Friday, September 08, 2006

WHAT'S THE MEANING OF ..... ?

Just a quick note folks: need to find the meaning of a concept? Search "Wikipedia", a free on-line encyclopedia available in many languages, which holds thousands of articles that cover many topics on different categories.

It's the first site you should consult, given that not only provides fully detailed descriptions of each concept but also external links to sites were you can find further references on the topic.