XNA UK User Group

A helping hand for bedroom coders throughout the land.
in

XNAGoodies

Articles and thoughts on working with the Microsoft XNA Framework.
  • Using Matrix.CreatePerspectiveOffCenter()

    I wanted to use Matrix.CreatePerspectiveOffCenter() recently but had a little trouble converting from my usage of Matrix.CreatePerspective(). The latter method requires field of view, aspect ratio and near far distances, the former requires the boundaries of the near plane in view space. Fortunately, calculating the near plane size is just a little simple trigonometry.

    // tan(angle) = opposite / adjacent
    // opposite = adjacent * tan(angle)
    float nearPlaneHSize = nearClip * (float)Math.Tan(fov*0.5f);
    projection = Matrix.CreatePerspectiveOffCenter(
        -nearPlaneHSize * aspectRatio,
        nearPlaneHSize * aspectRatio,
        -nearPlaneHSize, nearPlaneHSize,
        nearClip, farClip);
    

    Posted Jan 14 2008, 11:44 AM by leaf with no comments
    Filed under: , ,
  • Microsoft to release the source of the .Net Framework libraries

    Not XNA related (and I doubt it will include the XNA libraries) but Microsoft are going to be releasing the source to the .Net Framework libraries and, because Microsoft are nothing if not integrated, they will be making it easy to access the source from within VS 2008. Being able to read the source is nice but we've all been doing that for ages anyway with the aid of Reflector. Reflector only allows us to read the source, with the actual source files we will be able to step into the Framework library methods and see exactly what is happening to our data inside the debugger. I'm really pleased to hear this.

    See Scott Guthrie's post for more information. 

    Posted Oct 03 2007, 07:45 PM by leaf with no comments
    Filed under:
  • Upcoming XBLA Games

    Microsoft announced some of their upcoming games at the Tokyo Game Show, see xbox.com for the details. Amongst all the usual big, boxed games there were a few interesting XBLA games announced.

    Every Extend Extra Extreme (E4): I really enjoyed the free PC original of this simple twist on shmup games. The PSP version took the same basic idea and added the interactive music experience you would expect from Q Entertainment, makers of Lumines and Rez amongst others. Looking forward to more of the same but on a bigger screen.

    Rez: I missed Rez the first time round as I didn't have a PS2. Then when I did get a PS2 I couldn't find it anywhere, eventually my girlfriend tracked down a copy on Ebay and gave it to me for my birthday (she's nice like that). This is a minimalist, interactive techno experience/shoot 'em up. Reminds me of the visuals in clubs in the early 90's but this time I actually do control the music and the visuals.

    Braid: I've been following Jon Blow's blog about this and other things for what seems like ages, and then I hear its finally coming out on XBLA. Well done XBLA people, I say. Braid is a thoroughly independent, time manipulating twist on old-school 2D platform gaming. At least that's what I think it is, I've not played it yet. But having seen what our own David Johnstone has done with Shuggy, this is another one that I'm really looking forward to.

    Posted Sep 12 2007, 04:41 PM by leaf with no comments
    Filed under:
  • More Fog Sample

    Charles at RandomChaos took the fog sample we released previously and made it pretty, he also has some comments on how it does what it does. Read his post here.

    Posted Aug 28 2007, 12:36 PM by leaf with no comments
    Filed under: ,
  • Procedural Worlds

    I actually got dirty with procedural world creation in something I've been working on since forever - a pet project which I'm hoping to share with the user group at some point. Here are a few reflections.

    Procedural systems essentially take a varying input and use a fixed set of building blocks and rules to create an output. The way I thought about it was to decide what I wanted for the output, then think about how I wanted to specify the input, and finally deduce what the building blocks would have to be to make all this happen.

    That last stage - deciding on the building blocks and writing the code to make it all work - is incredibly good fun. You've got a set of nicely-defined tasks whose success can be easily verified, and there's a real sense of achievement in varying a few simple parameters and seeing whole new worlds appear.

    Now, locking down the inputs, outputs and building blocks is actually quite a challenge.

    Inputs

    Here are some input possibilities for a procedural, zelda-style dungeon game :

    • binary file created by level editing tool specifying exact positions of each monster and object
    • text file specifying overall populations of monster types and objects, and size of world
    • N greyscale textures showing probabilities of encountering N monsters/objects in world footprint
    • single 'difficulty' or 'game length' factor

    It's worth noting that each different method of authoring requires a unique ratio of 'user input' to 'pre-defined rules and building blocks', and because of this the levels will turn out quite different.

    For example : if the system just took 'difficulty' as an input, it would be very easy to author 100 levels which were progressively harder to pass - but they'd be pretty generic. No chance to make level 15 a really long corridor, level 20 a huge room with all the monsters hidden in the corners, and so on.

    A perfect example of this is the old C64 game The Sentinel by the legendary Geoff Crammond :


    It created entire 3D chess-board-like levels from a single number between 0 and 9999 (encoded as a password so you couldn't just jump to any old level). The idea was that when you beat a level you would be left with a certain number of health points, and these would get added to the number of the level you had just completed - and the result would be the next level you'd jump to. A simply amazing game, if you've never played it - plus, full 3D on the C64...

    A level editor on the other hand may allow for creation of very specific scenarios, but then you have a less conrete way of measuring the success of your designs (compared to a whole level created by 'difficulty'), and authoring requires a whole load of user input. Do you actually have time to make 100 levels?

    Another question to ask yourself is what method the author will find easiest. Textures for instance - as an artist, I have a good idea of the ways I can manipulate a texture in photoshop, and would have great fun making probability textures and messing with different kinds of fall-off etc - and could end up with something which couldn't really be expressed in, say, a text file.

    I recently heard of a sandbox game which had a dynamic rubbish-on-floor system driven by a greyscale texture : white meant "high probability of rubbish here" and black meant the opposite. So you could 'paint-in' trash where there were alleyways, carparks and so on - great! Unless of course you didn't know photoshop.

    Outputs

    What kind of thing could your system output?

    • text file specifying cleverly-weighted positions of monsters, objects and walls on a 2D grid
    • palettised texture where the value of each pixel refers to a wall/monster type/object/exit/player start position
    • vertex and index buffers of cleverly-weighted maze world walls; populated array of MyMonster() structs

    Basically, anything. You'll have to draw the world, and allow interactions with it, so output whatever is necessary to do all that.

    You could definitely argue that drawing a 3D world from the starting point of a text file is in fact another whole procedural system, and I'd have to agree (of course, any game which isn't just streaming in chunks of pre-populated memory - so pretty much every game - is doing this to some degree). So procedural systems can be multi-stage, with data getting munged from one format to another. Some of the stages may also happen offline, and some at runtime.

    Part 2 will discuss building blocks and rules, and how my pet project ties into all this!

  • Bit Twiddling, Texture Duplicating and the Activator

    I posted a sample texture processor that shows how to resize a texture in the content pipeline. Creating this highlighted a small issue with BitmapContent objects that I wanted to mention.

    To create a resized copy of a BitmapContent is pretty easy, you just have to copy the source bitmap to a destination bitmap that is a different size.

    BitmapContent.Copy(sourceBM, destinationBM); 
    

    The awkward bit is creating a destination bitmap that is the same type as the source bitmap. BitmapContent is an abstract class and the common concrete implementation of BitmapContent is the generic class PixelBitmapContent<T>. And that's where the problem lies, we need to create an instance of a generic class when the type of T is not known until run time. I could only think of two ways to do this; one, use a switch statement to handle all the different types that T in PixelBitmapContent<T> will usually be (Color, Vector4, HalfVector4, etc.); or two, use the Activator class to create an instance of a given type. The second option is shorter so that's my favourite.

     private static BitmapContent CreateBitmap(Type bitmapType, int width, int height)
    {
        return (BitmapContent)Activator.CreateInstance(
            bitmapType, 
            new object[] { width, height });            
    }
    

    The above method will create a bitmap of the type passed in. If the type isn't derived from BitmapContent, then this method will fail with an exception, so it should really have a try/catch block to deal with that. I don't mind using the Activator, this situation is perfect for it but it might be better if this method was available as BitmapContent.CreateBitmap() or similar so that it's a little more obvious for people who don't know about the Activator class.

    While writing the sample I had a need to deal with power of two numbers (that is the sequence of numbers given by 2^n). Computers like power of two numbers for all sorts of reasons and graphics cards are no exception - most graphics cards prefer textures to be power of two sizes (256x256, 128x512, etc.), especially textures with mipmaps. Here are a couple of methods that use bit twiddling magic (hey, it's magic to me) for dealing with power of two numbers.

    private static bool IsPowerOfTwo(int n)
    {
        return ((n & (n - 1)) == 0);
    }
    

    private static int RoundUpPowerOf2(int n)
    {
        n--;
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;
        n++;
    
        return n;
    }
    

    I can take no credit for them, I found them on this very useful page but I wanted to post them here for future use and just as a reminder that all that C/C++ style bit twiddling can still apply when working with C#.
     

  • VS2008 Xna Game Template

    I recently downloaded the VS2008 beta 2 release. It works well so far, runs very smoothly on Vista and looks a little prettier than VS2005. So that I could combine playing with VS2008 and playing with Xna I knocked up a Xna Windows Game project template similar to the one available in Xna GSE. It sets up references to the Xna assemblies and has a little custom MSBuild lovelyness to enable building content (but see notes on the download page). You can download the template here:

    Visual Studio 2008 Xna Windows Game Project Template



     

    Posted Aug 09 2007, 12:28 PM by leaf with no comments
    Filed under: ,
  • Fogging Sample

     

    After some prompting from Charles Humphrey on his blog and in the XNA forums, I knocked up a quick sample that shows how to do fogging in shaders without using the fixed function render states. You can download the Fogging Sample here.

    Posted Jul 18 2007, 11:22 PM by leaf with 4 comment(s)
    Filed under: , ,
  • Opaque Data from Max

    Eli has a post telling us how to export opaque data (often called custom attributes) from Max and Maya. Unfortunately those instructions seem to disagree with this post from one of the Autodesk FBX developers, which say that there is very limited support for custom attribute export. My tests show that the FBX developer is correct and that the Max exporter doesn't export string custom attribute types, which is a pity. If you are using Maya, the situation is a bit better as the comments to this Normal Map Sample mention a couple of ways of getting the Maya exporter to export opaque data.

    Posted Jul 10 2007, 01:55 PM by leaf with no comments
    Filed under: , , ,
  • Memories

    I couldn't resist posting a link to this game being developed by Matthieu Godet. It has a lovely look and feel to it, very reminiscent of the animation shorts produced by the National Film Board of Canada and European animation oddities that would show up on BBC2 every now and then. I particularly like the multi panel views (think Thomas Crown Affair, or Ang Lee's Hulk). Check out the video and screen shots.

  • Object Pools and Garbage Collection

    Advice From The Swamp has a new post about object pools, it includes a nicely implemented generic pool class that I suggest you take a look at. To add a little more background and depth to the article you should also read this article from the Compact Framework team, which explains some of the differences between the desktop and Compact Framework/Xbox 360 garbage collectors.

    While pooling objects is very useful you need to carefully manage the size of your pools. The Compact Framework article has this to say about live objects and latency.

    "We find that GC latency is approximately linear to the number of live objects… then add the cost of heap compaction on to that. Our benchmarks show that the difference between deep object hierarchies vs. shallow ones is negligible, so it’s mostly the number of objects that matter."

    Which means that if you have a large number of pooled objects and a garbage collection happens your pooled objects could actually cause the garbage collection to take longer. So, pool your objects but make sure that you carefully monitor the size of pools you need. Also use some of the other techniques that Compact Framework article mentions such as using arrays of value types - a single array of 10,000 unboxed value types counts as 1 object, the array. While you're thinking about these things read (fellow UK User Group member) cubed2D's article on profiling too.

  • Of Gods and Sandboxes

    Grass Block Danc from Lost Garden has another prototyping challenge. Take his (really very lovely) graphics and simple game design and create a game prototype to explore some of the mechanics and ideas he has written about. Obviously, I'd much prefer you to be working on competition entries but if you're not this looks like a lot of fun. Maybe you could even work it into the competition's Ocean Odyssey theme and still enter. As I can't enter the competition I might have a look at this, if only because I find the graphics so impossibly cute and I loved Populous.

  • It moves

    Hey, there's activity on the XNA UKUG site. It's taken a while to get this site up and running and we've got more to do but it's lovely to see it taking shape.

    Most excitingly, we've released details of the competition we're hosting and having seen the prizes, thanks to competition sponsor Microsoft, I kinda wish that I could enter now. Still, I get to judge which should be good fun.

    Posted May 16 2007, 11:03 AM by leaf with no comments
    Filed under: ,
  • Moving...

    Now that we're getting the XNA UKUG site up and running, I thought I'd move my XNA stuff from the old place to here. I'll move over whatever content is still valid and there will be more to come.