3D Pixel Perfect Object Picking with Hash

Pope Kim May 28, 2009

I ran into this article, which describes how to do object picking using a render target and a simple shader. Yes, this is basically how we support pickings in game editors nowadays thanks to programmable shaders. =)

If you are using a 32-bit integer hash number to keep track of scene objects' name or something equivalent, you can make this system even better by directly storing that 32-bit number onto the render target.

so the code for setting the colour would be something like this:

int a = (hash >> 24) & 0xff;
int r = (hash >> 16) & 0xff;
int g = (hash >> 8) & 0xff;
int b = hash & 0xff;
 

Vector4 Colour;
Colour.X = r / 255f;
Colour.Y = g / 255f;
Colour.Z = b / 255f;
Colour.W = a / 255f;

Later, when you try to get a hash value on a certain pixel, you would just interpret the whole 32-bit value as integer like this:

int hash = Texture.getPixelAsInt(x, y);

Isn't this much better? :)