Showing posts with label Code Snippets. Show all posts
Showing posts with label Code Snippets. Show all posts

Monday, December 15, 2008

DRAWABLEGAMECOMPONENT TEMPLATE

If you have been using XNA GS for a while now, you should know what game components are.

What is more, you should also know that thanks to the integration of XNA GS with Visual Studio, in order to add a new component you just:

  1. Go to the solution Explorer,
  2. Browse the list of projects,
  3. Right click with you mouse over the selected project,
  4. Select Add -> New Item,
  5. Choose "Game Component" from the list of available components,
  6. Click the "Add" button, and
  7. Voilá ... your new game component file is included in the project.

This is great!

Now, and again: if you've been using the XNA Framework you should know that there is a specification of the game component class for those that will be drawed to the screen: "DrawableGameComponents".

Unfortunately, if you want to create one of those components there's no shortcut, meaning either you create it by scratch or use a game component file as your source file and then modify it accordingly. In short, there is no DGC template integrated into VS, yet.

To change this, however, you could just create your own DrawableGameComponent template by going in VS to "File -> Export Tamplate", and then choosing the item you want export as a template.

After following the whole exporting process you can get and also integrate your new template to the list of items that you can pick when using VS "Add New Item" feature.

The problem with this solution is that your new template will be listed by default under the "My Templates" section of the "Add" dialog control, completely unrelated to the "XNA Game Studio 3.0" items section. Maybe you're fine with this solution generated "by default", but if you don't, then you have to tweak a little your recently generated template, change its location and one more thing that I will explain in what follows.

First, I have uploaded a class template for the drawable-game component here:

http://www.megaupload.com/es/?d=74ITZDJX

This template contains all the proper files that will helps us to better integrate it into VS.

Thus, follow whis steps:

  1. Download the above-mentioned template .zip file,
  2. Optional: open the .vstemplate file to find how the trick works,
  3. Search for the "ItemTemplates" folder in the directory where your Visual Studio 2008 version is installed, and
  4. Copy the .zip file into that folder.

Usually, the "ItemTemplates" folder is located in "%vs90comntools%\Common7\IDE", so say if you're using VS08 Standard, Pro or Team edition, you'd probaly find something like "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates".

We are almost done, now. There is just one more little procedure we must follow before reaching our goal:

  1. Go to Start -> Microsoft Visual Studio 2008 -> Tools,
  2. Open "Visual Studio 2008 Command Prompt" as an Administrator,
  3. Execute the following self-explanatory command "devenv /installvstemplates".
  4. When the command finishes, (re)open Visual Studio.

In case you're using the express version you have to browse for the folder in the start menu for that edition and, instead of typing "devenv" as stated in (3.) above you must type "VCSExpress".

If everyhing goes ok, everytime you want to add a new item template you should see something like:

Or better yet:By the way, you can use your own icon design if you don't like the one I provided in within the zip. To replace it, just delete the "old" one and include your own in the zip file, respecting the old name (that is, the name requested by the template XML file).

Well, that's pretty much it. I hope you find this useful. And yes, you can repeat this same procedure for every item template you want to include under the "XNA Game Studio 3.0" items section.

Cheers!
~Pete

Monday, November 17, 2008

XNA & EXTENSION METHODS 3

With this third article, I'm closing my introductory series to the world of Extension Methods and XNA.

At first, this article was meant to focus on how to extend the Random class to get new colors, but Ziggy, in his article entitled "Particles Using LINQ" -worth reading, btw- has clearly shown how to achieve this so I will take that great article as a starting point to go a bit deeper in the discussion on the matter.

If you see Ziggy's method named "RandColor" -which from now on I will refer to it as "NextColor" to be in line with the Random class, he's showing one of the new features of the XNA Framework 3: when using floats there's no need to first create a Vector3 in order to then create a Color, anymore.

In previous versions of XNA, to use floats in order to create a color, you would have declared:

public static Color NextColor(this Random rand)
{
    return new Color(new Vector3(rand.NextFloat(), rand.NextFloat(), rand.NextFloat()));
}

But from the XNA Framework 3 and on, this also works:

public static Color NextColor(this Random rand)
{
    return new Color(rand.NextFloat(), rand.NextFloat(), rand.NextFloat());
}

Now, if you see the Particle2D class in the above-mentioned article, you will notice the field named "Color", which is declared as an variable in uppercase; a new extension method could be created for it, as follows:

public static void NextColor(this Random rand, out Color color)
{
    color = new Color(rand.NextFloat(), rand.NextFloat(), rand.NextFloat());
}

Thus, we can use it within the Update method in the referred example to replace this line:

p.Color = rand.NextColor();

By this new line:

rand.NextColor(out p.Color);

Since the type Color is a struct, the advantage of using the latter over the former could be generally deemed as marginal, but eventually you may get to the situation when even the slightest improvement in your code is desired, specially when you're targeting the compact framework.

New question: what if you followed the design guidelines of C#, declaring the color field in lowercase as a private field and instead, a public getter and setter was included in that class, in the form of a public property named "Color".

In that case, the new overloaded method cannot be used since Properties and Indexers cannot be passed as out/ref parameters. Why? Well, just remember that when you're using properties and indexers you're not directly dealing with variables but methods. In that particular case, the first implementation -that is, the one included in Ziggy's article- is the best solution.

Let's face it! You could be tempted to pass the existing instance of Particle2D as "ref" to sort out the above-mentioned constraint, as follows:

public static void NextColor(this Random rand, ref Particle2D particle)
{
    particle.Color = new Color(rand.NextFloat(), rand.NextFloat(), rand.NextFloat());
}

It should compile ok BUT ONLY if you're NOT PASSING to that method the temporary variable created by a foreach loop -as opposed to the base example. This operation is just NOT ALLOWED for the iteration variables of foreach loops. My advice here is simple: avoid this tempting implementation and as I said before just use the one presented by Ziggy. Generally, the simplest solution is the correct one.

One side note: in case you're new to C#, it's important to notice that in this case we are using "ref" instead of "out", since we need an existing (that is, a non-null) instance of the class in order to assign the new color. Otherwise, by using "out" we should have to create an instance of type Particle2D from within the extension method BEFORE assigning the new color to it.

Now, let's move onto an interesting situation. What if:

  1. We are not and will be not inside a foreach loop,
  2. We don't want to expose the whole Particle2D to the extension method, and at the same time
  3. We need to use this method for as many classes that have declared setter properties for colors?

If that is the case, then you should take a look to this implementation:

public interface IColor
{
    Color Color { get; set; }
}
 
public static class HelperMethods
{
    ...
 
    public static void NextColor<T>(this Random rand, ref T instance)
        where T : class, IColor
    {
        instance.Color = new Color(rand.NextFloat(), rand.NextFloat(), rand.NextFloat());
    }
}

As you can see, we are hereby combining the power of Generics with Extension Methods.

But, why the "IColor" constraint? What we are saying here is simple: only types that implement the Color property can call this extension method. And those non-null instances passed to the method as a parameter (remember we are using the "ref" word here) will be handled as IColor types.

Ok, but why the additional "class" constraint? Tricky one. As a corollary of the previous constraint, if we do not specify that only classes are accepted as parameters, then structs can be also passed when calling the method, and for that they will have to implement the IColor interface ... Meaning? ... Tic tac tic tac ... Yeap, boxing. Ugh! That nasty word. Handling structs through interfaces causes boxing. Chilly, isn't it? Now you know it, in case you didn't.

To sum up, as you can see Extension Methods are quite handy, but you have to use them with care if you want to avoid getting into a design trap. As usual, not all the situations can be solved the same way, even though at first it sounds logic to you. You may find your-self saying "Whaaat? Buy whyyy? ...". So, I hope these examples show you what to use and when and what to avoid and why.

Some final thoughts about Extension Methods:

  1. They are great for usual tasks: believe it or not, two common types where I always find my-self repeating usual tasks are TYPE and RANDOM classes, but this feature can be used with as many types as you need,
  2. They are ituitive to use: before this functionality was introduced to the .NET Framework, one usually used to write a static class filled with helpers; please don't misundertsand me, you still have, but now those helpers are presented in a more intuitive and user-friendly way. With Extension Methods, you don't have to look for the methods "by browsing" the static class were you declared and implementem them; instead, you just look on the instances of the types you are using. And last but not least,
  3. They comply with design principles: as said in my first article in the series, we are not breaking any design principles, since we have no direct access to private members of the "extended" types.

In short, if you use Extension Methods with care and wisdom, they can be a true friend at the time of coding your XNA-based game or application: they simply help you extend any types with new methods AS IF these where originally part of those types, what in turn can be handy, for instance:

  1. When you don't want to create a specification of a class, or on the other hand,
  2. When you want to put more functionality into a sealed class somehow -to some extent, of course.

So go ahead, try Extension Methods and share what you find with the XNA Community. It would be great and fun to know what you are using them for!

Well, I hope you have found this series useful. Constructive comments and suggestions are always welcome.

Cheers!
~Pete

Monday, November 03, 2008

XNA & EXTENSION METHODS 2

Continuing with the topic of how to use the handy functionality provided by "Extension Methods" with our XNA-based creations, for this article we are going to need the "FuelCell" tutorial (remember that you shall find this tuto -along with the "TopDownShooter" one- in the help file under the "What's New In This Release" section).

Ok. In the chapter called "Finishing Touches" of the FuelCell' s tutorial, you'll find the following method at the very end of the "FuelCellGame.cs" file:

private Rectangle GetTitleSafeArea(Viewport viewport)
{
Rectangle retval = new Rectangle(viewport.X, viewport.Y, viewport.Width, viewport.Height);

#if XBOX
retval = viewport.TitleSafeArea;
#endif

return retval;
}

If you remember my last article on the subject, you'll be anticipating by now that the Viewport struct could be "extended" so as to retrieve its "unsafe" area with one method call.

If so, you guessed it right! We can use Extension Methods to declare an operation called, say "GetFullArea", and give it the proper implementation.

Not only can we pass again a parameter by reference (using the "out" reserved word) -like we did in Part 1 of this series- but also in this particular case, since we're dealing with a struct, we can afford to implement an overloaded method that locally declares, creates and returns an instance of a Rectangle (I know what you're thinking, but unfortunately, there are no "Extension Properties" in C#, so we need to get the rectangle from a method call).

Using Extension Methods, our solution should look like the following:

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MyNamespace.Math
{
public static class MathExtensions
{
public static void GetFullArea(this Viewport viewport, out Rectangle area)
{
area = new Rectangle(viewport.X, viewport.Y, viewport.Width, viewport.Height);
}

public static Rectangle GetFullArea(this Viewport viewport)
{
return new Rectangle(viewport.X, viewport.Y, viewport.Width, viewport.Height);
}
}
}


Now, the GetTitleSafeArea(...) method could be re-implemented like this:

private Rectangle GetTitleSafeArea(Viewport viewport)
{
Rectangle retval;

#if
XBOX
retval = viewport.TitleSafeArea;
#else
viewport.GetFullArea(out retval);
#endif

return retval;
}

Or also like this:

private Rectangle GetTitleSafeArea(Viewport viewport)
{
#if XBOX
return viewport.TitleSafeArea;
#else
return viewport.GetFullArea();
#endif
}


Remember two important things:

  • You'll have to add the proper "Using" statement in the file that will use the extension method (in my example: "MyNamespace.Math"), and
  • You'll have to manually add a reference to the "System.Core" assembly in your project.

This technique can be used to get, say -among other things, a Vector2 containing the width and height of the Viewport (as well as for the display and the client area). I leave it as an exercise for you to try (you'll see it's actually quite easy to implement).

I hope you find this article useful.

'till next time,
~Pete

XNA & EXTENSION METHODS 1

With the release of XNA GS 3, two new tutorials were included into the "What's New In This Release" section in the help file: "TopDownShooter" and "FuelCell" games. For what follows, we'll be referring to the first tutorial game: TopDownShooter.

Sometimes we need to get an instance of a sound effect without playing it. The good news is that it can be done. The bad news is that there's no built-in method provided yet to get that instance in one step.

So, what's next then? Open the AudioManager.cs file provided in the TopDownShooter example. You should find the following code on the LoadContent() method:

// We call Play silently to retrieve a specific instance we can
// use for subsequent Pause and Play calls
SeekerInstance = Seeker.Play(0, 0.75f, 0, true);
SeekerInstance.Stop();
SeekerInstance.Volume = FXVolume; // set the real volume

As you can see, the above-mentioned code gives an idea of what you should use to get the instance of a sound effect "without playing it".

But, what if we want to get that functionality in one method (as if it were provided built-in) without extending the SoundEffect class? Well, in that case since we are targeting the .NET Framework 3.5 we can use the magic of "Extension Methods".

I'm not going to explain what Extension Methods are (to get a first read on the subject, please refer to this page), but how we can take advantage of them for this particular case.

Our goal is to extend the SoundEffect class in a way that:

  1. We do not create a specification of that class,
  2. We get a new SoundEffectInstance without playing it,
  3. We do not generate unnecessary garbage when getting a new instance, and
  4. Our method runs efficiently in the .NET Compact Framework.

Thus, our solution should be the following:

  1. We'll use Extension Methods technique,
  2. We'll mimic the code of the "TopDownShooter" tutorial,
  3. We cannot declare a local reference of type SoundEffectInstance within our method, and
  4. We should pass a parameter by reference of type SoundEffectInstance that can be null.

Therefore, our final implementation should be something like this:

using System;
using Microsoft.Xna.Framework.Audio;

namespace MyNamespace.Audio
{
public static class AudioExtensions
{
private static float VolumeLevelByDefault = .5f;

public static void GetCue(this SoundEffect soundEffect, out SoundEffectInstance soundEffectInstance)
{
GetCue(soundEffect, out soundEffectInstance, VolumeLevelByDefault, 0f, 0f, false);
}

public static void GetCue(this SoundEffect soundEffect, out SoundEffectInstance soundEffectInstance, float volume, bool loop)
{
GetCue(soundEffect, out soundEffectInstance, volume, 0f, 0f, loop);
}

public static void GetCue(this SoundEffect soundEffect, out SoundEffectInstance soundEffectInstance, float volume, float pitch, float pan, bool loop)

{
// Play the sound silently and stop it immediately.
soundEffectInstance = soundEffect.Play(0f, pitch, pan, loop);
soundEffectInstance.Stop();

// Set the passed volume level.
soundEffectInstance.Volume = volume;
}
}
}

As you can see, I'm naming the static method "GetCue" but you can call it, say, "GetInstance" if you prefer. Also, since we cannot yet use optional parameters -we'll have to wait for C# 4.0 for that- you will have to create as many overloaded methods as you need.

Now, in the LoadContent() method of the AudioManager.cs file, all we should use instead is:

// Get the new instance of the seeker sound effect.
Seeker.GetCue(out SeekerInstance, FXVolume, 0.75f, 0, true);

Don't forget to add the proper "Using" statement on the AudioManager.cs, linking to the namespace where the extension method was declared and implemented (in my example "MyNamespace.Audio"), or your code won't compile.

Also, you will need to manually add a reference in your project to the "System.Core" assembly -in case it is not already referenced.


Well, this is it. Now you know how to extend the SoundEffect class to get a new instance of a sound effect in just one method call, virtually speaking ;)

One final note: by using "Extension Methods" we are not breaking any design principles, since we have no direct access to private members of the "extended" type (being the latter, in this example, the SoundEffect class).

Enjoy!
~Pete


Thursday, October 02, 2008

UNOFFICIAL SAMPLES FOR XNA 3 BETA

Hey folks!

Since the moment the CTP was out I spent some time to update all the samples available on the creators site to that early version of XNA 3.0, for my-own use.

Then, when the beta was published, and taking into account that maybe we will see no big changes to it until the final release, I decided to recreate them -complying with the license terms and conditions- so that I can publish them on the Web for those who eventually need them.

One important note: these files are NOT official so use them at your own risk!!! Otherwise, you can wait till 3.0 final gets released and thus, for the official education files.

The only changes in the code that you will see are those related to the 2D projects that used the WrapAngle method (created in the same class that used it). Instead, MathHelper.WrapAngle(...) is now in place. And ... yes! I almost forgot: each zip file contains a Windows-only project.

Well, here they go (hold on to something):

First Wave:

Second Wave:

Yes! Third Wave:
I think ... This Is The Fourth Wave (?)
Ok. Who Am I? And Why Am I Typing This?
No, Seriously ... (Why The Heck Am I Doing This?)
Phewww! At last, I finished ... man, I stopped counting after the first 20 links.

Well, I'm done, so in case you're using XNA 3.0 beta, I hope you find them useful.

Cheers!
~Pete

Wednesday, March 05, 2008

NOT THAT EMPTY ...

There's a great series of articles regarding game development with XNA being posted at this blog: "Running on Empty".

So far, 16 out of 25 articles have been posted covering a lot of aspects of game development both, in theory and in practice, not only to get started but also to help you implement advanced features such as "physics".

But the best is yet to come since the remaining articles will cover more advanced topics like "parallel split shadow mapping", deferred shading and "split space ambiet occlusion".

Happy reading!

Sunday, December 16, 2007

XNA & BEYOND: THE PATH TO VS 2008

I have uploaded my first article to "The Code Project" site, which shows how to integrate an XNA-based application into VS 2008 (an implementation for WPF is included) ... read it here.

Also in the article I present -what I think is- a simple solution for embedding your XNA games within a WinForms control; a topic that has been heavily discussed in the (XNA Creators) forums these days.

I hope you find it useful.

Cheers!

Tuesday, November 20, 2007

XNA GAME STUDIO 2.0 (BETA) IS NOW AVAILABLE

As announced by the XNA Team, the beta version of the awaited XNA GS 2.0 has been released!!!

So go and visit the following:

  1. The official announcement :)
  2. The "What's new" page, and
  3. The beta home page.

Don't forget to check the new "Project Upgrade Wizard", the newly updated demo sample projects, and the "Net Rumble Starter Kit".

Enjoy!

Friday, May 18, 2007

TESTDRIVEN.NET AND XNA

There has been many questions in the XNA Creators Club's forums regarding unit tests with the express editions and particularly with XNA GSE. Well, not only unit testing can be executed with the latter but also, TestDriven.NET can be also used again since version 2.5 (still in beta stages). However, from time to time we may found some exceptions with tests related to the content pipeline. Henning Degn explains us why and also brings a simple workaround to that issue.

From Degn's article: "... Some tests in XNA cannot be done dynamically. These tests usually require visual inspection and therefore need to be run manually. Using Testdriven.net you can run test scenarios, simply using an ad hoc test of a function containing the test. Simple. Effective. No need to modify the main method to run these functions.

However, when using any XNA content I have stumbled on the following error:

Microsoft.Xna.Framework.Content.ContentLoadException
File not found. ---> System.IO.DirectoryNotFoundException:
Could not find a part of the path 'C:\WINDOWS\assembly\GAC_32\Microsoft.Xna.Framework\1.0.0.0__6d5c3888ef60e27d\Content\myTexture.xnb'

The reason being that (naturally) I didn’t put my content inside the GAC (Global Assembly Cache)! The ContentManager is using the codebase of the assembly who’s main method called it as its root ...".

BTW, in some chapter of Benny's book it's stated that this tool cannot be used with XNA GSE. Please notice that by the time the book was written, v2.5 beta -the build that reimplmented support for express editions- hadn't been released.

Cheers!

"STENCIL SWIPES"

Shawn Hargreaves has published the third part of the series that cover "transitions", this time centering attention on the use of stencil buffers to produce some nice effects.

From the post: "... Stencil is usually an 8 bit integer value, and is attached to each pixel in addition to the usual color and depth values. You can set renderstates to control how values are written into the stencil buffer while drawing graphics, and also to specify that graphics should only be drawn in areas where the existing stencil values meet specified conditions ...".

Consice, accurate and practical. The best part on the series so far, imho of course ... cheers!

Thursday, May 17, 2007

"XMESSAGE" XNA COMPONENT

Created by X has published a new component for XNA , "xMessage", designed for displaying in-game chararacter dialogs.

From the post: "... the component allows an image to be displayed with the text, and the text is also dynamically changes acording to the size of the dialog. When running the demo use the left mouse button to move the dialog and the right mouse button to resize the dialog ...".

See ya!

Wednesday, May 16, 2007

DEALING WITH MATRICES IN XNA

Rhysyngsun has submitted to Ziggyware the article: "Introduction to Matrices in XNA".

From the article: "... Understanding matrices is a fundamental part of creating effective games in XNA. Matrices particularly flex their muscle when you're working in full 3D space, however, the math behind them can be daunting. Fortunately, XNA provides most of the functionality for matrices that you will ever need without having to worry about the complicated math behind that functionality. However, it is necessary to have an understanding of what this functionality is actually doing in order to apply it correctly in your code ...".

Watch this space!

QUATERNION CAMERA IN XNA

Scot Boyd, author of the upcoming book "Expert One on One: XNA Game Programming for Xbox 360 and Windows", has provided the source code of the "QuaternionCamera" class which will help you avoid that nasty Gimbal Lock problem that you may face when working with yaw, pitch and roll at a time.

From the post: "... XNA unfortunately does not provide a QuaternionCamera class in it's Framework. Nowhere on the Internet could I find a camera class that provides six degrees of freedom without requiring additional coding from the reader ... In the process of attacking this problem in my book, I've made a few camera classes. I'm posting the simplest class here - good for beginners. The final camera class in the book will be more complicated. This class should provide a good jumping-off point for anybody interested, or a simple helper class for those who just want a camera without hassles. In the camera, GetViewMatrix and CreateYawPitchRoll are where the money is ...".

Read on!

Tuesday, May 15, 2007

RESOURCEMANAGER COMPONENT

Wizzie has released a component for handling resources, and thus the name: "ResourceManagement Component".

From the post: "... This is a very useful component since it allows for managing all of your resources in one object that is available anywhere in your engine via XNA Game Services. The code was written with the 360 in mind so there are work arounds in place for the .NET Compact Framework ...".

Nice!

USERCONTROL FOR RUNNING YOUR XNA GAME WITHIN A WINDOWS FORM

... or as Nuclex has posted: "XNA Windows.Forms UserControl".

The preview: "... as can be seen in one of my recent news posts, I did just that while developing a world editor for my upcoming game Island War. Because of the great demand for such a component, I decided to release my XNA GameControl class to the public ...".

The screenshot:

And the link to it.

Handy, very handy ...

CRIMSON UPDATE ... AGAIN

Diagrams showing the layout of the engine are now available:

Plus a new video:


Also, as usual, a preview of the post: "... Animated sprites have been a fun feature to add, my implementation hangs around the concept of an animation sheet. my orc test sprite has some animations in separate.png files and some bunched together on the same .png. So how do i handle them? every animation gets a animation sheet, which contains its start frame, end frame and a reference to its texture. these are held in a dictionary as a value, the key to that dictionary is a CompassDirection (north, NorthEast ect). I have a load of these in a list, and i keep there indexes in another dictionary with a AnimationState(move, idle, jump etc). To get the correct animation sheet you just need to know what direction and animation you currently in and pull em out ...".

Ultrahead's out.

TRANSITIONS - PART 2

Shawn has published the second installment on his series of articles regarding "trabsitions", this time focusing on the physics part.

From the post: "... you may not know exactly when you want things to start or stop moving. When the factors controlling your transitions get more complicated, it can be easier to switch to a physics based approach ...".

Read on!

"GETTING STARTED WITH XNA" - THE SERIES

Remember this post? Brecht is back with more tutos:

Read on!

Sunday, May 13, 2007

LINEAR COLLISIONS WITH XNA - PART II

McCoder has released the source code of the linear collision tests referred on my previous post.

From the post: "... There’s a ton of hack lying around in the code for my collision test app, but I figured my collision response code was probably clean enough to be useful to someone so I figured I’d post it up for everyone to check it ...".

Happy coding!

Thursday, May 10, 2007

MORE ON QUADTREES

Kyle strikes again on quadtrees, this time focusing on code design.

From kyle's article: "... Before I explain the classes, a picture of how the node tree is constructed in a Quadtree as objects are added and move through the tree (individual frames on click-through) ...".

Read on!