segunda-feira, 17 de outubro de 2016

Hierarchical Transforms

After I made a simple Transform component to handle positions, scales and rotations, I stopped working on it in order to code other things. Then, came the situation where I needed hierarchical transforms, if I wanted to keep other components simple – 9 patches graphics moving around, for example. Basically, the idea is to have a “parent transform” in which “children” will inherit its position, scale and rotation properties.

So, how can that be done?

Searching around, I found out that there are two simple ways of achieving this. One is simply recalculate all children whenever a parent has been changed. It’s creepy. The other way is setting a dirty flag, and then recalculate the parents and children as their information is needed. This is the one I did!

Whenever a transform has one of its properties changed, it sets itself and all children, recursively, as dirty. When something requests information such as position, it will check if the transform itself is dirty. If it is, it requests the parent information so that its own information can be built accordingly to the current hierarchy, and then sets itself to not dirty anymore. This is a recursive behavior.

In order to avoid too many recalculation requests, each transform keeps a copy of it’s current, “resulting” transformation matrix. This increases memory usage and also the chance of cache misses but, right now, it’s very simple to understand and use. One drawback, though, is that children and parents can’t be easily reprocessed in parallel.

So far, performance is acceptable. I mean, I have nothing on my game scene….