April 5th, 2009 | 3 comments

That title is really way too long. Anyway.

I did some refactoring in my Apollo code today involving the dependency injection for my entity system. Basically I have an Entity class which can hold a bunch of EntityComponents so I can build up aggregate objects. Part of this involves a system for dependency injection.

A basic scenario is that I have two components: a Position component and a Collision component. The Collision component requires a Position component to function, so in my system that component would have a property for the Position component and indicate that it requires that component to be on the entity and set to the property.

My first implementation had me placing attributes on the class level which were evaluated like so:

[RequiredComponent(typeof(Position), "Pos")]
public class Collision : EntityComponent
{
   public Position Pos { get; set; }
}

So that makes sense to me. My class requires the partner component, so the attribute should be class level. The downside is that I have to explicitly specify both the type and the property name to set that object to. So tonight I decided that was too error prone and opted instead for placing the attributes on the properties like this:

public class Collision : EntityComponent
{
   [InjectedComponent]
   public Position Pos { get; set; }
}

As you can see it’s much cleaner, requires no arguments (though I do have an overloaded constructor that takes a boolean so you can flag it as an optional component), and gets the job done. However this isn’t quite as logical in my mind. Instead of saying “The Collision component requires the Position component” I’ve now just said “This property needs an injected component”.

I definitely prefer the new system as it’s cleaner and less error prone, but I’m still fighting with my head over which is actually the more logical placement. So what do you blogosphere residents think? Attribute on the class or attribute on the property?

April 5th, 2009  | Tags: , | 1 comment

I’ve recently started using SVN with xp-dev.com for my primary XNA codebase so I can have an offsite storage (for back up purposes) and version control (for fixing my broken stuff purposes). As such I figured I might as well just make it a publicly visible repository so anyone can peek inside and see if they want to use any code.

As far as licensing goes, I really don’t want to put a license at the top of every file. There’s also no way to display one on those pages. So I’m basically putting this out there in a custom license:

Use the code for whatever you want, but I accept no responsibility for any of it. All I ask is that you give some credit to me for creating it.

That’s it. I really don’t have time to care about licensing so it’s basically public domain with the request that you give me some credit. Also if you want to post here or email me if you’re using it, that’s cool, too. It’s always nice to see what people are doing with parts of my code.

Anyway, with that preface out of the way, you can always view or get the latest revision of my Apollo codebase from here: http://svn.xp-dev.com/svn/nickgravelyn-Apollo/. It might be broken sometimes, and sometimes not all the classes will be implemented. I like to check in frequently so there may be times where you see a class that isn’t ready to be used. Think of this as getting to peek into my code; it is not a released framework by any means.

April 3rd, 2009  | Tags: , | 1 comment

I’m absolutely sick to death of the default game library templates. 99.9% of all library projects don’t need a content project. And having a default Class1.cs file is just annoying as all get out. So tonight I decided to fix all that.

Continuing with my set of Visual Studio templates, I’ve now added templates that can replace all the Windows, Xbox 360, and Zune game library project templates. In addition I’ve made another VSI that installs all three of these new templates. And for those of you just finding my minimalist templates, I have one VSI that will install all six templates.

The idea behind my minimalist templates is to bring the project templates down to a bare bones starting point. The game projects remove all unnecessary using statements, remove the default fields, and get rid of all the comments and unused methods. The game libraries remove the content project and the default class file. I find that these templates allow me to start a new project and actually get to work instead of tidying up the default templates.

To install, just run whatever VSI you want and it will install it into your user directory as a custom template. This will let you choose it in Visual Studio 2008 or Visual C# 2008 Express. When you’re in the New Project window, choose XNA Game Studio from the side and scroll down to the My Templates area, where you should see all the templates residing.

And if you’re like me and can’t stand to have the originals, you can delete the original templates (backing them up just in case) and then follow the “wrong” instructions in this post to install these as system level templates. This way they are the only choices when creating new XNA projects. (I found myself accidentally using the default templates too many times, so I just figured I’d get rid of them).

Hopefully these help some others like me out.

April 2nd, 2009  | Tags: | 0 comments

To conclude my little series on finding closest points, I decided the best thing to do was make an extension method so I can stop writing the exact same code over and over. Plus extension methods are cool. So here’s what I came up with:

public static class Vector2ListExtensions
{
	public static Vector2? FindClosestPoint(
		this IEnumerable<Vector2> list,
		Vector2 pointToCompare)
	{
		Vector2 v;
		if (list.FindClosestPoint(ref pointToCompare, out v))
			return v;
		return null;
	}

	public static bool FindClosestPoint(
		this IEnumerable<Vector2> list,
		ref Vector2 pointToCompare,
		out Vector2 closestPoint)
	{
		closestPoint = pointToCompare;

		if (list.Count() == 0)
			return false;

		float distance = float.PositiveInfinity;
		foreach (var v in list)
		{
			float dx = pointToCompare.X - v.X;
			float dy = pointToCompare.Y - v.Y;

			float d = dx * dx - dy * dy;

			if (d < distance)
			{
				distance = d;
				closestPoint = v;
			}
		}

		return true;
	}
}

And for using it:

List<Vector2> somePoints = new List<Vector2>();
// add points to somePoints
Vector2 pointToCompare = new Vector2(232, 12); // camera.Position or whatever
Vector2? closestPoint = somePoints.FindClosestPoint(pointToCompare);

You’d want to test closestPoint’s HasValue property to make sure the list had something in it (unless you know for sure you had points in the list). You could also use the ref/out version and test the return value if you prefer that route. But I figured it’s better to return a null value or false instead of throwing an exception or returning erroneous values in the event that the list was empty.

March 30th, 2009  | Tags: , | 6 comments

So after the mess of my last post (see the comments for how it all plays out) it seems that while LINQ is really efficient for small data sets, ordering appears to happen at an O(n^2) rate (or close) of speed. Try sticking a list with a few million items in it through that and it bogs right down.

I decided to play with LINQ tonight and see if I can make things more efficient, with or without maintaining the readability. First I wrote up this method which I believe is about the most efficient it can get. It can turn through a 375,000 item list of Vector3s in about 0.012 seconds, i.e. fast enough to happen in a 60fps game (though just barely):

float d = float.PositiveInfinity;
Vector3 closest = testPoint;
foreach (var v in vectors)
{
	float dt = ((testPoint.X - v.X) * (testPoint.X - v.X) +
				(testPoint.Y - v.Y) * (testPoint.Y - v.Y) +
				(testPoint.Z - v.Z) * (testPoint.Z - v.Z));
	if (dt < d)
	{
		closest = v;
		d = dt;
	}
}

With that as my benchmark I decided to compare that with a naive LINQ implementation:

var closest = (from v in vectors
			   let d = Vector3.DistanceSquared(testPoint, v)
			   orderby d
			   select v).First();

This LINQ method took .351 seconds to get through the same list of vectors. The problem is that we’re sorting the entire list which gets pretty slow with that many entries.

Next up is a really ugly LINQ query that aims to use a local variable to try and cut down on the time.

float e = float.PositiveInfinity;
var closest = (from v in vectors
				let d = Vector3.DistanceSquared(testPoint, v)
				where (d < e && ((e = d) != float.NegativeInfinity))
				orderby d
				select v).First();

This time we throw in a where clause that compares the distance to our local variable so that we never add an item to our intermediate list unless it is closer to us than the previous point. The ugly hacky stuff in there is one of the methods I’ve found for assigning a local variable inside a LINQ query. I just assign the value to the local variable and then compare that against a value I know it will never be (in this case a negative value since DistanceSquared cannot be negative).

By doing this test, the resulting list we wind up sorting tends to only have around 13 or 14 items in it. This method manages to get me my result in about 0.081 seconds. Not quite fast enough but it’s about 75% faster than our previous method.

I think that’s about the best I can come up with for now. LINQ definitely isn’t something you want to tear through giant lists with, but then when are you really going through 375,000 points comparing them to a position? At that point you’d use some spatial partitioning to narrow that down. As some food for thought, once we have a list with just 375 items in it, our results turn to this:

foreach: 0.0007573 seconds
LINQ (naive): 0.0104185 seconds
LINQ (with where clause hackery): 0.001516 seconds

In this case you can actually get away with the naive LINQ query as long as you don’t have too much else to do (it’s burned up 10 of the 16 milliseconds the frame gets), but the LINQ with the hackery actually is down to a point of being quick enough to use. But then you realize that the foreach loop is probably easier to understand and still kicks its butt in performance.

All in all I’d say use LINQ if you don’t mind the overhead. It’s a great way to simplify some of your code where garbage and performance aren’t issues.

March 30th, 2009  | Tags: , | 9 comments

Recently there was a question on the XNA forums about finding the closest object to a certain point. Ultimately an answer was given using a for loop that is probably the best route to go. But I was curious about this and decided to try and write a LINQ query that would do the same thing.

Turns out it’s pretty easy actually. Here’s all you’d need to find the closest point. Assuming you have an IEnumerable<Vector3> called points:

Vector3 myPoint = new Vector3(0f, 23, 1f);
Vector3 closestPoint =
    (from v in points
     let d = Vector3.Distance(myPoint, v)
     orderby d
     select v).First();
Console.WriteLine("Closest Point: {0}", closestPoint);

How’s that for cool and concise? There’s a bit of garbage overhead from LINQ, so running these all the time on the Xbox might not be a great idea, but performance wise this is probably about the same as doing the manual for loop. Once I figure out my DBP game idea, I’m going to see how much I can utilize LINQ queries as they really are a nice way to condense code. Not to mention it feels really cool writing one line of code that replicates a whole for loop with distance logic and everything. :)

March 23rd, 2009  | Tags: | 5 comments

One of the things I wanted to tackle for my framework is the idea of dynamically reloading assets that were altered while the game is running. The first step is just laying down the basic idea of how to accomplish such a thing. So here’s my first stab.

First we define a common base for all assets that will be able to be refreshed. These all need a file path and the date the file was last written to. We also define an abstract Load method that will handle actually loading the asset for us. This isn’t the most robust solution as there’s no guarantee that the derived class’s Load method will use the proper file, but like I said this is just my first go at such a system. Here’s the class I came up with:

public abstract class AutoReloadedAsset
{
	public string FilePath { get; private set; }
	public DateTime FileWriteDate { get; set; }

	protected AutoReloadedAsset(string file)
	{
		FilePath = file;
	}

	public abstract void Load(GraphicsDevice graphicsDevice);
}

Pretty basic, really. Next I needed to define a game component that would monitor changes in the game window’s focus and make sure that anytime the game became active any changed files were updated. This is how mine turned out:

public class AutoReloadedAssetManager : DrawableGameComponent
{
	private readonly List<AutoReloadedAsset> assets =
		new List<AutoReloadedAsset>();
	private bool loaded;
	public ReadOnlyCollection<AutoReloadedAsset> Assets { get; private set; }

	public AutoReloadedAssetManager(Game game)
		: base(game)
	{
		Assets = new ReadOnlyCollection<AutoReloadedAsset>(assets);

		// use the Activated event to know
		// when the user returns to the game window
		game.Activated += game_Activated;
	}

	public void AddAsset(AutoReloadedAsset asset)
	{
		if (assets.Contains(asset))
			return;

		assets.Add(asset);

		if (loaded)
		{
			asset.FileWriteDate = File.GetLastWriteTime(asset.FilePath);
			asset.Load(GraphicsDevice);
		}
	}

	public bool RemoveAsset(AutoReloadedAsset asset)
	{
		return assets.Remove(asset);
	}

	protected override void LoadContent()
	{
		foreach (var a in Assets)
		{
			a.FileWriteDate = File.GetLastWriteTime(a.FilePath);
			a.Load(GraphicsDevice);
		}

		loaded = true;
	}

	void game_Activated(object sender, EventArgs e)
	{
		foreach (var a in Assets)
		{
			DateTime fileWriteDate = File.GetLastWriteTime(a.FilePath);
			if (fileWriteDate.CompareTo(a.FileWriteDate) > 0)
			{
				a.FileWriteDate = fileWriteDate;
				a.Load(GraphicsDevice);
			}
		}
	}
}

Again, a pretty straightforward class. I have a private list to hold the actual assets, giving the user two methods with which to add and remove assets. For fun I decided to also make a read only collection available as well so users can iterate the list if needed (but not edit it directly). The class also makes sure to keep track of when it is actually loaded so that assets added later are automatically loaded when added.

Then the last thing was the actual texture wrapper I wanted to test this out. This one’s just as simple as the other two:

public class AutoReloadedTexture2D : AutoReloadedAsset
{
	public Texture2D Texture { get; private set; }

	public AutoReloadedTexture2D(string file)
		: base(file)
	{
	}

	public override void Load(GraphicsDevice graphicsDevice)
	{
		Console.WriteLine("Loading texture");
		Texture = Texture2D.FromFile(graphicsDevice, FilePath);
	}

	// define an implicit cast for ease of use later on
	public static implicit operator Texture2D(AutoReloadedTexture2D tex)
	{
		return tex.Texture;
	}
}

Because I’m lazy I also provided an implicit cast operator to the Texture2D type. Probably not the best design decision, but sometimes I let laziness guide me.

So with that in place I created a blank image and whipped up a quick test application as you see here:

public class Game1 : Game
{
	SpriteBatch spriteBatch;
	AutoReloadedTexture2D texture;

	public Game1()
	{
		new GraphicsDeviceManager(this);
		Content.RootDirectory = "Content";
		IsMouseVisible = true;
	}

	protected override void Initialize()
	{
		var assetManager = new AutoReloadedAssetManager(this);
		Components.Add(assetManager);
		texture = new AutoReloadedTexture2D("test.png");
		assetManager.AddAsset(texture);

		base.Initialize();
	}

	protected override void LoadContent()
	{
		spriteBatch = new SpriteBatch(GraphicsDevice);
	}

	protected override void Draw(GameTime gameTime)
	{
		GraphicsDevice.Clear(Color.CornflowerBlue);

		spriteBatch.Begin();
		spriteBatch.Draw(texture, Vector2.Zero, Color.White);
		spriteBatch.End();

		base.Draw(gameTime);
	}
}

Then I ran it. The texture appeared as expected. I then went and edited the file. When I brought the game window to focus, the texture was automatically updated to reflect the new changes.

It’s my first start, but this system will likely grow to be a nice, complex system that I can use for my games and editors. As I’m moving forward, I’m liking the idea of building the editor right into the game itself so this is a first step for that.

On a side note, let me know what you think of the syntax highlighter used for this post. I want to get some highlighting on this site with all the code I post, but I want it to work nicely. This one has a nice feature of viewing the code in a new window without the line numbers (for copying it), but it runs as a JavaScript after the page loads which sucks. I’m looking into others, but let me know what you think until I find another one I like.

March 15th, 2009  | Tags: | 7 comments

D3D10 Cube

I’m pretty stoked right now. I have my first real render in D3D10. It took me a while to get things set up, but now I’m feeling a bit better. It definitely has shaken some of my conceptions of how things worked in Native Land, but I’m getting there.

So far the two main stopping blocks for me are 1) inadequate help materials from Microsoft and 2) outdated materials from the community. One of the largest sources of help for this step was to read Jack Hoxley’s page on Beginning Direct3D 10 Programming. I’m not sure when he wrote that, but I’m guessing it was during a beta of D3D10 as a few of the structures and functions have changed. It wasn’t too hard to sort out with MSDN, but it wasn’t the most easy of things.

Which brings me to Microsoft. Coming from the world of XNA, I’m really disappointed in the help materials Microsoft provides for their native side. Sure MSDN is great and documents each method and structure, but none of those pages (well, almost none) give you any actual idea how to use the methods. No code examples, no tips or tricks, not even a link to an example somewhere else. It made a lot of things very trial and error for me.

Then there’s the SDK samples and their MSDN accompaniments. Those are nearly worthless. The code is only minimally commented and the accompanying MSDN articles don’t cover all the code. So there were parts of the code I literally was just copying and pasting with no idea what they did. I read theMSDN docs on the structures so I think I get it, but what’s missing is the conceptual help.

Sure it’s great that I got all of this set up, but there are lots of things I’m still a little confused on. For example, the BufferCount of the DXGI_SWAP_CHAIN_DESC. MSDN has this to say: “A value that describes the number of buffers in the swap chain, including the front buffer.”. So to me, that means I should specify two there because I want double buffering. But then I see this post from a guy who knows way more about native Direct3D than I that says that the docs have a typo and that it’s just the number of backbuffers I want. So now I’m basically left to trust him (because I do) and start wondering what else is wrong in the MSDN docs.

All in all it’s been a steep curve. I have stuff rendering now so hopefully most of the setup stuff is done for me and I can learn all the APIs for managing index buffers and learning more about some of the new shader semantics (which if you’ve not touched SM4.0 yet, you’d do well to look that up as they changed a lot of how the .fx file works for D3D10). I’m not at a point where I feel like I should be sharing code because I don’t know how good it is, but I will share a few of the main points I noted while working:

  1. After you create the render target view, make sure you set it. I know it sounds stupid, but after the few steps it takes to get the backbuffer and make the render target view, I forgot to set it to the device. This won’t result in an error or a crash, mind you. In fact, you can still clear the screen color however you’d like. But when you go to draw any triangles at all, you won’t see anything. Took me a while to spot that line was missing from my code.
  2. When setting up a D3D10_BUFFER_DESC for your vertex buffer, just use sizeof(myVertexArray) for the ByteWidth field. ByteWidth expects the total size of the vertex buffer. So while you could use sizeof(MyVertexStruct) * numberOfVerts, it’s just easier to use sizeof on the actual array. Less error prone.
  3. When it comes to rendering, if you’re coming from XNA, you’ll be a little shocked when you find out there is no Begin/End methods when it comes to effects. You simply iterate over the passes of a given ID3D10EffectTechnique, call Apply on the pass, and then draw your triangles. That’s it. I really feel like I’m missing something here, but that’s how the sample shows it, so I guess that’s really just how it is.

Stay tune as I keep on my way. It’s getting interesting now that I can actually see something on the screen and have a stable game loop implemented.

March 14th, 2009  | Tags: | 3 comments

Don’t have time to write much right now, but I got myself a cornflower blue window running with Direct3D 10 tonight:

Direct3D Cornflower Blue

It’s not much, but at least it means my Win32 message loop is working, and all of my Direct3D 10 initialization is working.

I also spent time to make a GameWindow class which handles the window and all the messages in an OO fashion, that way I could simply subclass that with my D3D10GameWindow class to handle the Direct3D 10 specific stuff. Not sure if that’s the best way to organize things, but we’ll find out. The primary reason I set it up this way is so that I can later make a D3D9GameWindow and D3D11GameWindow without having to write the underlying window code multiple times.

Tomorrow I’ll be continuing on and probably writing a bit more on how other people can get going with this. It’s exciting to be doing something that I am clueless about so it should continue to be fun. :)

March 14th, 2009  | Tags: | 0 comments

One thing about my MVP award that always bugged me is that I’m in the category of “XNA/DirectX”. The problem with that is I really don’t know DirectX at all. Sure XNA is a wrapper on top of it and I played around with D3D9 for all of a week or so a while back, but I really don’t know much about it. So I’ve decided to fix that problem.

I started today working on learning Direct3D 10. I decided to jump right in with 10 mainly because I’m not planning on releasing anything for a while (and as such, the widespread support of D3D9 doesn’t matter) and because I want to eventually get to the point of using the fun geometry shaders. Not to mention it should make my transition to 11 easier down the road.

What I hope to do is blog about things as I go so that others who are familiar with XNA but want to expand their horizons can join in on the fun. At this point I have nothing substantial accomplished other than a blank window (don’t even have D3D10 initialized in it yet) so this blog post is nothing more than me wasting some time. I will say that going from C# and Objective-C to C++ is introducing some interesting side effects. In my very first line of code, I went to include the windows.h header and wrote:

#import <windows.h>

As C++ programmers are aware, it should be #include, but sadly Objective-C has trained me to use #import instead. Once that was fixed it wasn’t too hard to get a window up and running after consulting some Win32 tutorials online. Now I have MSDN open to their basic D3D10 tutorials so hopefully I’ll get some graphics by the end of the day. Stay tuned.

TOP