Tuesday, April 9, 2013

I Hate Arguing With Libraries

... by which I mean, programming libraries. This week my frustration is being caused by the Bullet Physics library, which is included as part of the libGDX game library. When Bullet Physics is working correctly, it produces some impressive results, but getting it to the point where it's working correctly seems to be far from straightforward.

For instance, I have a mesh of a physical object that I want to introduce into the game. I want the physics library to detect collisions between my new object and the existing objects, so that they can bounce off of each other. According to the documentation, I'm using all the right calls to convert my mesh into a rigid body object, which should then generate collisions. Except that the existing game objects are passing right through my new object as if it wasn't there.

One problem is the the documentation for Bullet Physics isn't very helpful. It looks like someone just ran a documentation tool over the library code and posted the results on the web. This would be fine if the original code had been well-commented. For instance, look at this page and tell me: what is the purpose of the vertexStride parameter of the btTriangleIndexVertexArray constructor?

You might think that the overall library manual might be of assistance here, but I can tell you that the word "stride" doesn't appear anywhere in the manual. The manual does, however, at the very back, provide a few tips, such as "Keep the size of triangles reasonable, say below 10 units/meters. Also degenerate triangles with large size ratios between each sides or close to zero area can better be avoided." This would appear to apply to my case, since I know my mesh includes some long, narrow triangles, but what is a "large size ratio" in this case? 10:1? 3:1? 2:1? What are the expected symptoms if you have "degenerate" triangles? If I clean up my triangles, will this repair my collision problem, or is this just a performance optimization?

And then there's the fact that libGDX is a Java library, and it provides a Java wrapper over the Bullet Physics library, which itself is a C library. This is all well and good -- a C library will produce much better performance than a plain Java library -- but the C library doesn't play well with Java garbage collection. If you create an object in your Java code and pass it to the physics library, and then the object goes out of scope in your Java code, Java will eventually garbage collect it, even if the physics library is still using it. In order to prevent memory faults, your Java code needs to maintain references to everything passed to the physics library, which eliminates much of the convenience of using Java in the first place.

I like programming. I really do. But I really don't like spending hours trying to convince a library to do work that the library is supposedly designed to do.