Collision bugs are the best bugs

So that problem I mentioned yesterday — having roads end up being selected as though they were in front of objects which they were actually behind — eventually turned out to be a nasty little leak of temporary collision result data which was being generated as part of an optimisation.

Basically, when I’m trying to figure out what you’re pointing your cursor at, here’s what I do:  I create an imaginary line which starts at the camera, and travels out in a direction through the world which is determined by the 2D position of your cursor within the game window.  I then test that line against all the polygons in the terrain, all the polygons in the roads, all the polygons in the buildings, all the polygons in the toons, etc.  For each polygon that the line hits, I keep track of where it hit, and how far from the camera the polygon was.  Whichever polygon got hit closest to the camera, that’s the one that I consider you to be pointing at.

Now, doing this sort of test-every-polygon collision test takes a lot of CPU power, and so I’ve made a lot of optimisations to avoid testing polygons which I don’t absolutely need to test.  One of these optimisations (which is being used on everything but the terrain) is to create an invisible “bounding box” around each object in the world, and before testing any of the polygons in those objects, I test whether the line hits the bounding box at all, and if not, then I know that I don’t have to test any of the polygons inside the box;  the line didn’t hit the box, so it couldn’t possibly hit any of the polygons inside the box.

The bug that I fixed today was that anything which used this “bounding box” optimisation (which is almost everything) wasn’t calculating “point where I hit the polygon” and “distance from that point to the camera” as they were supposed to;  they were calculating “point where I hit the polygon” and “distance from where I hit the bounding box to the camera”.  Most of the current placeholder graphics in the game are cubes which exactly match their bounding boxes, and so this bug wasn’t noticeable on them;  the only exceptions were the roads, which undulate and have bounding boxes which are much larger than the roads themselves, often entirely surrounding the objects which travel on the roads.  Since the collision system was accidentally using the distance-to-bounding-box instead of distance-to-polygon, the roads were taking priority over those objects which looked like they were closer, but were actually encompassed within the roads’ bounding box.

This bug would have affected buildings and all sorts of other things as well, once full procedural building generation is implemented.  But it’s fixed now.

Also, my head hurts.  Too much debugging of collision code will do that.