My First Pony… I mean PCB.
I have been fiddling with electronics on-and-off for years now, and got pretty 'serious' about it early last year.
I have always just stuck to bread boards and simple prototyping. I never dared dream of designing my own circuit boards, let alone having them printed. Surely that would be, like, hard or something right?
Last night I decided to bite the bullet and find out by designing my first PCB. It is very, very, very simple, and it may fail horribly... but come next pay day, I am going to cross my fingers, and send the design off to be printed (after checking it roughly 10,000 more times).
The board is designed to replace the bread board in my Norby robot, allowing me to plug-in new sensors/servos with less fiddling, and maybe add a few pretty lights ^_^
I have kept the design super simple because it is my first shot, and because PCBs may not be hard to design, but getting them printed isn't exactly cheap (in low quantities).
I will note that some credit must go to The RobotGrrl, as watching her progress reports on RoboBrrd's brain inspired me to get off my lazy arse and give it a shot.
4-bit Decoder in Minecraft
I have had a bit of an obsession with Boolean logic recently, and 'thanks' to the flu, I have had a lot of spare time over the last few days.
So I decided to combine the two, and build a 4-bit to 16-line decoder in Minecraft.
For those that don't know, Minecraft is a sandbox-style game in which players can build many different things out of blocks (kind of like Lego).
But what interested me is a mechanic called 'redstone dust'. Players can make torches out of this dust and add them to blocks to power them. They can then use the dust to connect the powered block to other special blocks - like doors, and traps - to give them power.
What is really interesting, though, is what happens when you connect two or more torches together.
Run power from Torch A in to Torch B, and Torch B will switch off. In other words it acts like a NOT gate. More interestingly, if you connect two or more torches to one torch, the targeted torch acts like a NOR gate.
This is great, because the NOR gate is a universal gate.
And so I was able to build this 4-bit decoder:
The first half of the video shows the device working. The second half shows the actual device in all its glory.
I based it off a design that I put together recently for a different project, but had to add a lot of repeaters (NOT-NOT) because Minecraft limits the length of a 'wire' to 15 squares.
Norby Mark I
Over the past week or so, I have been playing with a new robot I built.
It isn't the most complex robot in the world, but that is fine. I built it mainly as a test platform for limited-input path finding algorithms.
I am using an Arduino Mega 2560 micro-controller with an Ardumoto Shield to drive the engines. The track base is a RP-5 Tank-Tread Platform, and is suprisingly awesome (fast and powerful).
The (only) sensor is a Seeed PING Ultrasonic Range Finder. I 'mounted' the sensor on a 180-degree servo motor so that the robot can look left and right.
To save on soldering, I am just using a bread board to create the circuit. Though (fair warning) I did need to solder the connectors to the motor shield.
I made the mounting boards with a bunch of plywood and my handy dremel tool.
The circuit I am using to connect everything together is fairly simple:
The Math Behind 3D Transformation
Tonight I wrote an article that acts as introduction to the math behind 3D transformations.
Depending on my motivation levels, this may be the first in a series of articles covering the math and algorithms underlying 3D programming.
Good seed for Random()
I often run in to a scenario where I need an easy way to generate random numbers. In most of these case, I don't care whether the numbers are entirely random, or just psuedo-random; all I want are numbers that have a decent level of variation.
In .NET, System.Random is great for this, but there is one issue: the default seed is time based.
In a lot of cases, the default seed is fine - because it is based on a high precision clock - but when you are working with multiple threads, it becomes problematic.
There are many (many, many) solutions to this, but today I stumbled across one that is simple, and reasonably elegant:
Random random = new Random(Guid.NewGuid().GetHashCode());
Because of the astronomically low chances of a GUID collision, this method of seeding as good as guarantees that each of your threads will be operating with a different seed.
The GUID needs to be hashed because the seed must be 32-bit.
I should note that you should not use this for anything relating to security. If you need a random number for security purposes, use a secure random number generator.
Thread-safe Singleton Initialisation
A co-worker who was unfamiliar with the singleton model recently asked me to explain the code to him; he was particularly curious about the locking on initialisation.
As it is fresh in my mind, I thought I might as well make a 'brief' post about it.
I am not going to go in to the singleton pattern itself - or the pros-and-cons; I am just going to cover the method I use for thread-safe initialisation in C#.
Like many people, I use double-checked locking during initialisation. It is actually a fairly simple concept, but looking at the code it can take a minute (or some explanation) before it clicks in to place...
public sealed class Example
{
private static volatile Example m_Instance;
private static object m_InstanceLock = new Object();
private Example() {}
public static Example Instance
{
get
{
if (m_Instance == null)
{
lock (m_InstanceLock)
{
if (m_Instance == null)
{
m_Instance = new Example();
}
}
}
return m_Instance;
}
}
}
Singletons are generally used with lazy initialisation. They are not initialised until they are first needed. The catch with this method of initialisation is that you run the very real risk of two threads attempting to initialise the singleton at the same time.
The only way to avoid this is to use locking, but this can add fairly significant overhead.
Do you have to lock every time someone attempts to access the instance? Well no, you don't... but to avoid doing so, you can't just lock the instance itself.
The solution is to create a separate, simple object that you lock only during initialisation.
To avoid having to lock every time a thread tries to get a reference to the instance, you first do a simple check to see if the instance is null. If it is not null, you simply return the instance. No locking required.
If the instance is null, however, the first thing you do is request a lock on the locking target.
Once you have the lock, you check to see if the instance is still null. Why do you check again? Well while you were waiting for a lock, another thread may have initialised the instance.
If the instance is still null you initialise it. If it is not null, you do nothing. In either case, you finally fall out to the standard return of the instance.
To ensure this pattern of initialisation works, the instance should be declared as volatile. This will prevent the .NET run-time - or the hardware - from creating issues by trying to be smart about optimising calls to the same object in a small space of time.
Generally speaking, declaring objects that will be used by multiple threads as volatile is worth consideration.
ASP.NET Performance
I often hear people question the performance of ASP.NET, and while I know it is complete nonsense, it is always nice to see the proof in reality.
My job currently focuses on the development and maintenance of high throughput transactional websites. Today was a big day for our main website, which is coded in ASP.NET (C#), and backed by an application layer coded in C#.
At peak, our site was processing over 1,000 transactions per second, per server. Our peak across all servers was just shy of 4,100 transactions per second.
There is no doubt in my mind it could have handled much, much more without faltering. And if it did falter with the current infrastructure? Well it is a completely scalable solution.
It is good design (architecture) that determines the performance of a solution. The choice of language/platform certainly has an impact, but rarely as much as decisions made during early implementation.
XNA MD2 Update
A long time ago - back in 2007, during the early days of XNA - I created a library to help load and animate MD2 models within the XNA framework.

It was a minor hit at the time, but in its original form the code is very dated and not compatible with XNA 4. I thought it was about time for that to change.
I have simplified the code some what - merging the animator and model in to one class - and cleaned it up a little.
You can grab the updated code here:
http://www.matthewlynch.net/stage/xna-md2/MD2Model.cs
It has been tested with a wide range of MD2 models, and seems to work fine. You will need to know what animations the model offers, but if you don't already know, just debug in to the class; it loads them all in to a dictionary.
Using it is fairly simple, but here is a rough guide:
MD2Model model = new MD2Model();
model.LoadFromFile(@"Content\model.md2");
model.Position = new Vector3(0, 0, 0);
model.Scale = 0.25f;
model.Rotation = 0.0f;
model.CurrentAnimation = "stand";
effect.Texture = Content.Load<Texture2D>("model-texture");
effect.World = model.WorldMatrix;
GraphicsDevice.DrawUserPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, model.GetVertexBuffer(gameTime), 0, model.TriangleCount);
If you are interested, the original can still be found on SourceForge, but I warn you the code is quite dated.
WCF and Using()
Encountered an interesting problem recently, while building a WCF solution.
My code ran fine on my development machines, but when I deployed the solution to production I started receiving a timeout exception; specifically a System.ServiceModel.CommunicationException.
This was strange because the supposed timeout was happening instantly on a system with a timeout threshold of 10 seconds...
After some head scratching and searching, I found the problem: If you use a WCF service client with the Using() statement, any exception that occurs during the call to Close() - implicitly done at the end of the using block - will mask exceptions that occur within the using statement.
To make matters worse, the call to Close() will almost always throw a System.ServiceModel.CommunicationException if the service client throws an exception higher up the chain.
The solution is fairly simple: use a try-catch-finally pattern instead.
In my case the actual exception was a System.ServiceModel.Security.MessageSecurityException, which was easily fixed with a configuration change.
Stored-Program Computer Model
After reading an article on Wikipedia about the Little Man Computer - an instructional model of a von Neumann architecture - I was inspired to code my own simple SPC model.
And in one of those "it made sense at the time... I think" decisions, I chose to code the model using HTML and JavaScript. Oh well, at least it makes it easy to access:
Block Map Generator Video
In my last post I mentioned I have been experimenting with an isometric map generator. I thought I might share a video of the results so far.
It is coded in C# and XNA, and the video simply shows me hitting the "randomly generate a map" button a number of times.
Isometric Helper Algorithms
Recently I have been experimenting with an isometric map generator. It is still in the very early stages, and I am not sure where I am going to go with it, but I thought I would share some of the algorithms I pieced together during my experiments.
Convert Screen Space to Map Space
Inputs
- float2 screenPoint - The point (pixel/coordinate) in screen space you wish to convert.
- int tileScreenWidth - The width (in pixels) of a tile in screen space.
- int tileScreenHeight - The height of a tile in screen space.
- float2 screenOriginPoint - The top-left most point in screen space of the top-left most tile in map space. Where the tiles start drawing.
- float2 screenOffset - How far (x/y) screen space has been shifted from the origin point. Used for scrolling.
Outputs
- float2 mapPoint - The calculated point (grid reference) in map space.
double tw, th, tx, ty; double sx, sy; tw = tileScreenWidth; th = tileScreenHeight; sx = screenPoint.X - (screenOriginPoint.X + screenOffset.X); sy = screenPoint.Y - (screenOriginPoint.Y + screenOffset.Y); tx = Math.Round((sx / tw) + (sy / th)) - 1; ty = Math.Round((-sx / tw) + (sy / th)); mapPoint.x = tx; mapPoint.y = ty;
Convert Map Space to Screen Space
Inputs
- float2 mapPoint - The point (grid reference) in map space you wish to convert.
- int tileScreenWidth - The width (in pixels) of a tile in screen space.
- int tileScreenHeight - The height of a tile in screen space.
- float2 screenOriginPoint - The top-left most point (pixel/coordinate) in screen space of the top-left most tile in map space. Where the tiles start drawing.
- float2 screenOffset - How far (x/y) screen space has been shifted from the origin point. Used for scrolling.
Outputs
- float2 screenPoint - The calculated point (pixel/coordinate) in screen space.
double tw, th, tx, ty; double sx, sy; tw = tileScreenWidth; th = tileScreenHeight; tx = mapPoint.X; ty = mapPoint.Y; sx = Math.Truncate((tw / 2) * tx - (tw / 2) * ty) + (screenOriginPoint.X + screenOffset.X); sy = Math.Truncate((th / 2) * tx + (th / 2) * ty) + (screenOriginPoint.Y + screenOffset.Y); screenPoint.x = sx; screenPoint.y = sy;


